1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
210 #define Cydia_ CYDIA_VERSION
212 #define lprintf(args...) fprintf(stderr, args)
215 #define TraceLogging (1 && !ForRelease)
216 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
217 #define ProfileTimes (0 && !ForRelease)
218 #define ForSaurik (0 && !ForRelease)
219 #define LogBrowser (0 && !ForRelease)
220 #define TrackResize (0 && !ForRelease)
221 #define ManualRefresh (1 && !ForRelease)
222 #define ShowInternals (0 && !ForRelease)
223 #define AlwaysReload (0 && !ForRelease)
224 #define TryIndexedCollation (0 && !ForRelease)
228 #define _trace(args...)
233 #define _profile(name) {
236 #define PrintTimes() do {} while (false)
239 // Hash Functions/Structures {{{
240 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248 static NSString *Colon_;
250 static NSString *Error_;
251 static NSString *Warning_;
253 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
255 static _finline NSString *CydiaURL(NSString *path) {
257 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
258 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
259 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
260 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
261 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
263 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
266 static _finline void UpdateExternalStatus(uint64_t newStatus) {
268 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
269 notify_set_state(notify_token, newStatus);
270 notify_cancel(notify_token);
272 notify_post("com.saurik.Cydia.status");
275 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
276 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
277 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
280 /* NSForcedOrderingSearch doesn't work on the iPhone */
281 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
282 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
283 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
285 /* Insertion Sort {{{ */
287 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
288 const char *ptr = (const char *)list;
290 CFIndex half = count / 2;
291 const char *probe = ptr + elementSize * half;
292 CFComparisonResult cr = comparator(element, probe, context);
293 if (0 == cr) return (probe - (const char *)list) / elementSize;
294 ptr = (cr < 0) ? ptr : probe + elementSize;
295 count = (cr < 0) ? half : (half + (count & 1) - 1);
297 return (ptr - (const char *)list) / elementSize;
300 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
301 const char *ptr = (const char *)list;
303 CFIndex half = count / 2;
304 const char *probe = ptr + elementSize * half;
305 CFComparisonResult cr = comparator(element, probe, context);
306 if (0 == cr) return (probe - (const char *)list) / elementSize;
307 ptr = (cr < 0) ? ptr : probe + elementSize;
308 count = (cr < 0) ? half : (half + (count & 1) - 1);
310 return (ptr - (const char *)list) / elementSize;
313 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
314 if (range.length == 0)
316 const void **values(new const void *[range.length]);
317 CFArrayGetValues(array, range, values);
319 #if HistogramInsertionSort > 0
320 uint32_t total(0), *offsets(new uint32_t[range.length]);
323 for (CFIndex index(1); index != range.length; ++index) {
324 const void *value(values[index]);
325 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
326 CFIndex correct(index);
327 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
328 #if HistogramInsertionSort > 1
329 NSLog(@"%@ < %@", value, values[correct - 1]);
334 if (correct != index) {
335 size_t offset(index - correct);
336 #if HistogramInsertionSort
340 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
342 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
343 values[correct] = value;
347 CFArrayReplaceValues(array, range, values, range.length);
350 #if HistogramInsertionSort > 0
351 for (CFIndex index(0); index != range.length; ++index)
352 if (offsets[index] != 0)
353 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
354 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
361 /* Apple Bug Fixes {{{ */
362 @implementation UIWebDocumentView (Cydia)
364 - (void) _setScrollerOffset:(CGPoint)offset {
365 UIScroller *scroller([self _scroller]);
367 CGSize size([scroller contentSize]);
368 CGSize bounds([scroller bounds].size);
371 max.x = size.width - bounds.width;
372 max.y = size.height - bounds.height;
380 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
381 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
383 [scroller setOffset:offset];
389 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
390 size_t length([self length] - state->state);
393 else if (length > count)
395 for (size_t i(0); i != length; ++i)
396 objects[i] = [self item:state->state++];
397 state->itemsPtr = objects;
398 state->mutationsPtr = (unsigned long *) self;
402 /* Cydia NSString Additions {{{ */
403 @interface NSString (Cydia)
404 - (NSComparisonResult) compareByPath:(NSString *)other;
405 - (NSString *) stringByCachingURLWithCurrentCDN;
406 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
409 @implementation NSString (Cydia)
411 - (NSComparisonResult) compareByPath:(NSString *)other {
412 NSString *prefix = [self commonPrefixWithString:other options:0];
413 size_t length = [prefix length];
415 NSRange lrange = NSMakeRange(length, [self length] - length);
416 NSRange rrange = NSMakeRange(length, [other length] - length);
418 lrange = [self rangeOfString:@"/" options:0 range:lrange];
419 rrange = [other rangeOfString:@"/" options:0 range:rrange];
421 NSComparisonResult value;
423 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
424 value = NSOrderedSame;
425 else if (lrange.location == NSNotFound)
426 value = NSOrderedAscending;
427 else if (rrange.location == NSNotFound)
428 value = NSOrderedDescending;
430 value = NSOrderedSame;
432 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
433 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
434 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
435 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
437 NSComparisonResult result = [lpath compare:rpath];
438 return result == NSOrderedSame ? value : result;
441 - (NSString *) stringByCachingURLWithCurrentCDN {
443 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
444 withString:@"://cache.cydia.saurik.com/"
448 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
449 return [(id)CFURLCreateStringByAddingPercentEscapes(
454 kCFStringEncodingUTF8
461 /* C++ NSString Wrapper Cache {{{ */
462 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
463 return size == 0 ? NULL :
464 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
465 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
468 static _finline CFStringRef CYStringCreate(const char *data) {
469 return CYStringCreate(data, strlen(data));
478 _finline void clear_() {
479 if (cache_ != NULL) {
486 _finline bool empty() const {
490 _finline size_t size() const {
494 _finline char *data() const {
498 _finline void clear() {
503 _finline CYString() :
510 _finline ~CYString() {
514 void operator =(const CYString &rhs) {
518 if (rhs.cache_ == nil)
521 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
524 void copy(apr_pool_t *pool) {
525 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
526 memcpy(temp, data_, size_);
531 void set(apr_pool_t *pool, const char *data, size_t size) {
537 data_ = const_cast<char *>(data);
545 _finline void set(apr_pool_t *pool, const char *data) {
546 set(pool, data, data == NULL ? 0 : strlen(data));
549 _finline void set(apr_pool_t *pool, const std::string &rhs) {
550 set(pool, rhs.data(), rhs.size());
553 bool operator ==(const CYString &rhs) const {
554 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
557 _finline operator CFStringRef() {
559 cache_ = CYStringCreate(data_, size_);
563 _finline operator id() {
564 return (NSString *) static_cast<CFStringRef>(*this);
567 _finline operator const char *() {
568 return reinterpret_cast<const char *>(data_);
572 /* C++ NSString Algorithm Adapters {{{ */
574 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
577 struct NSStringMapHash :
578 std::unary_function<NSString *, size_t>
580 _finline size_t operator ()(NSString *value) const {
581 return CFStringHashNSString((CFStringRef) value);
585 struct NSStringMapLess :
586 std::binary_function<NSString *, NSString *, bool>
588 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
589 return [lhs compare:rhs] == NSOrderedAscending;
593 struct NSStringMapEqual :
594 std::binary_function<NSString *, NSString *, bool>
596 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
597 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
598 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
599 //[lhs isEqualToString:rhs];
604 /* CoreGraphics Primitives {{{ */
609 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
610 CGFloat color[] = {red, green, blue, alpha};
611 return CGColorCreate(space, color);
620 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
621 color_(Create_(space, red, green, blue, alpha))
623 Set(space, red, green, blue, alpha);
628 CGColorRelease(color_);
635 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
637 color_ = Create_(space, red, green, blue, alpha);
640 operator CGColorRef() {
646 /* Random Global Variables {{{ */
647 static const int PulseInterval_ = 50000;
649 static const NSString *UI_;
652 static bool RestartSubstrate_;
653 static NSArray *Finishes_;
655 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
656 #define NotifyConfig_ "/etc/notify.conf"
658 static bool Queuing_;
660 static CYColor Blue_;
661 static CYColor Blueish_;
662 static CYColor Black_;
664 static CYColor White_;
665 static CYColor Gray_;
666 static CYColor Green_;
667 static CYColor Purple_;
668 static CYColor Purplish_;
670 static UIColor *InstallingColor_;
671 static UIColor *RemovingColor_;
673 static NSString *App_;
675 static BOOL Advanced_;
676 static BOOL Ignored_;
678 static _H<UIFont> Font12_;
679 static _H<UIFont> Font12Bold_;
680 static _H<UIFont> Font14_;
681 static _H<UIFont> Font18Bold_;
682 static _H<UIFont> Font22Bold_;
684 static const char *Machine_ = NULL;
685 static NSString *System_ = nil;
686 static NSString *SerialNumber_ = nil;
687 static NSString *ChipID_ = nil;
688 static NSString *BBSNum_ = nil;
689 static _H<NSString> Token_;
690 static NSString *UniqueID_ = nil;
691 static NSString *PLMN_ = nil;
692 static NSString *Build_ = nil;
693 static NSString *Product_ = nil;
694 static NSString *Safari_ = nil;
696 static CFLocaleRef Locale_;
697 static NSArray *Languages_;
698 static CGColorSpaceRef space_;
700 static NSDictionary *SectionMap_;
701 static NSMutableDictionary *Metadata_;
702 static _transient NSMutableDictionary *Settings_;
703 static _transient NSString *Role_;
704 static _transient NSMutableDictionary *Packages_;
705 static _transient NSMutableDictionary *Values_;
706 static _transient NSMutableDictionary *Sections_;
707 static _transient NSMutableDictionary *Sources_;
708 static _transient NSNumber *Version_;
709 static _transient _H<NSString> CydiaSource_;
710 static bool Changed_;
714 static CGFloat ScreenScale_;
715 static NSString *Idiom_;
717 static _H<NSMutableDictionary> SessionData_;
718 static _H<NSObject> HostConfig_;
719 static _H<NSMutableSet> BridgedHosts_;
720 static _H<NSMutableSet> TokenHosts_;
721 static _H<NSMutableSet> InsecureHosts_;
722 static _H<NSMutableSet> PipelinedHosts_;
723 static _H<NSMutableSet> CachedURLs_;
725 static NSString *kCydiaProgressEventTypeError = @"Error";
726 static NSString *kCydiaProgressEventTypeInformation = @"Information";
727 static NSString *kCydiaProgressEventTypeStatus = @"Status";
728 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
731 static void AddSource(NSDictionary *source) {
732 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
736 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
737 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
740 distribution, @"Distribution",
741 sections ?: [NSMutableArray array], @"Sections",
745 static void WriteSources() {
746 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
747 _assert(file != NULL);
749 fprintf(file, "deb http://%s/ tangelo-3.7 main\n",
750 [CydiaSource_ UTF8String]
753 for (NSString *key in [Sources_ allKeys]) {
754 NSDictionary *source([Sources_ objectForKey:key]);
756 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
758 fprintf(file, "%s %s %s%s%s\n",
759 [[source objectForKey:@"Type"] UTF8String],
760 [[source objectForKey:@"URI"] UTF8String],
761 [[source objectForKey:@"Distribution"] UTF8String],
762 [sections count] == 0 ? "" : " ",
763 [[sections componentsJoinedByString:@" "] UTF8String]
770 /* Display Helpers {{{ */
771 inline float Interpolate(float begin, float end, float fraction) {
772 return (end - begin) * fraction + begin;
775 static _finline const char *StripVersion_(const char *version) {
776 const char *colon(strchr(version, ':'));
777 return colon == NULL ? version : colon + 1;
780 NSString *LocalizeSection(NSString *section) {
781 static Pcre title_r("^(.*?) \\((.*)\\)$");
782 if (title_r(section)) {
783 NSString *parent(title_r[1]);
784 NSString *child(title_r[2]);
786 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
787 LocalizeSection(parent),
788 LocalizeSection(child)
792 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
795 NSString *Simplify(NSString *title) {
796 const char *data = [title UTF8String];
797 size_t size = [title length];
799 static Pcre square_r("^\\[(.*)\\]$");
800 if (square_r(data, size))
801 return Simplify(square_r[1]);
803 static Pcre paren_r("^\\((.*)\\)$");
804 if (paren_r(data, size))
805 return Simplify(paren_r[1]);
807 static Pcre title_r("^(.*?) \\((.*)\\)$");
808 if (title_r(data, size))
809 return Simplify(title_r[1]);
815 NSString *GetLastUpdate() {
816 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
819 return UCLocalize("NEVER_OR_UNKNOWN");
821 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
822 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
824 CFRelease(formatter);
826 return [(NSString *) formatted autorelease];
829 bool isSectionVisible(NSString *section) {
830 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
831 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
832 return hidden == nil || ![hidden boolValue];
835 static NSObject *CYIOGetValue(const char *path, NSString *property) {
836 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
837 if (entry == MACH_PORT_NULL)
840 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
841 IOObjectRelease(entry);
845 return [(id) value autorelease];
848 static NSString *CYHex(NSData *data, bool reverse = false) {
852 size_t length([data length]);
853 uint8_t bytes[length];
854 [data getBytes:bytes];
856 char string[length * 2 + 1];
857 for (size_t i(0); i != length; ++i)
858 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
860 return [NSString stringWithUTF8String:string];
865 /* Delegate Prototypes {{{ */
868 @class CydiaProgressEvent;
870 @protocol DatabaseDelegate
871 - (void) repairWithSelector:(SEL)selector;
872 - (void) setConfigurationData:(NSString *)data;
873 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
876 @class CYPackageController;
878 @protocol CydiaDelegate
879 - (void) returnToCydia;
881 - (void) retainNetworkActivityIndicator;
882 - (void) releaseNetworkActivityIndicator;
883 - (void) clearPackage:(Package *)package;
884 - (void) installPackage:(Package *)package;
885 - (void) installPackages:(NSArray *)packages;
886 - (void) removePackage:(Package *)package;
887 - (void) beginUpdate;
889 - (void) distUpgrade;
893 - (void) addSource:(NSDictionary *)source;
894 - (void) addTrivialSource:(NSString *)href;
895 - (void) showSettings;
896 - (UIProgressHUD *) addProgressHUD;
897 - (void) removeProgressHUD:(UIProgressHUD *)hud;
898 - (CyteViewController *) pageForPackage:(NSString *)name;
899 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
900 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
904 /* Status Delegation {{{ */
906 public pkgAcquireStatus
909 _transient NSObject<ProgressDelegate> *delegate_;
919 void setDelegate(NSObject<ProgressDelegate> *delegate) {
920 delegate_ = delegate;
923 NSObject<ProgressDelegate> *getDelegate() const {
927 virtual bool MediaChange(std::string media, std::string drive) {
931 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
934 virtual void Fetch(pkgAcquire::ItemDesc &item) {
935 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
936 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
937 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
940 virtual void Done(pkgAcquire::ItemDesc &item) {
943 virtual void Fail(pkgAcquire::ItemDesc &item) {
945 item.Owner->Status == pkgAcquire::Item::StatIdle ||
946 item.Owner->Status == pkgAcquire::Item::StatDone
950 std::string &error(item.Owner->ErrorText);
954 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
955 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
958 virtual bool Pulse(pkgAcquire *Owner) {
959 bool value = pkgAcquireStatus::Pulse(Owner);
962 double(CurrentBytes + CurrentItems) /
963 double(TotalBytes + TotalItems)
966 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
967 [NSNumber numberWithDouble:percent], @"Percent",
969 [NSNumber numberWithDouble:CurrentBytes], @"Current",
970 [NSNumber numberWithDouble:TotalBytes], @"Total",
971 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
972 nil] waitUntilDone:YES];
974 if (value && ![delegate_ isProgressCancelled])
982 _finline bool WasCancelled() const {
986 virtual void Start() {
987 pkgAcquireStatus::Start();
988 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
991 virtual void Stop() {
992 pkgAcquireStatus::Stop();
993 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
994 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
998 /* Database Interface {{{ */
999 typedef std::map< unsigned long, _H<Source> > SourceMap;
1001 @interface Database : NSObject {
1007 pkgCacheFile cache_;
1008 pkgDepCache::Policy *policy_;
1009 pkgRecords *records_;
1010 pkgProblemResolver *resolver_;
1011 pkgAcquire *fetcher_;
1013 SPtr<pkgPackageManager> manager_;
1014 pkgSourceList *list_;
1016 SourceMap sourceMap_;
1017 _H<NSMutableArray> sourceList_;
1019 CFMutableArrayRef packages_;
1021 _transient NSObject<DatabaseDelegate> *delegate_;
1022 _transient NSObject<ProgressDelegate> *progress_;
1030 std::map<const char *, _H<NSString> > sections_;
1033 + (Database *) sharedInstance;
1036 - (void) _readCydia:(NSNumber *)fd;
1037 - (void) _readStatus:(NSNumber *)fd;
1038 - (void) _readOutput:(NSNumber *)fd;
1042 - (Package *) packageWithName:(NSString *)name;
1044 - (pkgCacheFile &) cache;
1045 - (pkgDepCache::Policy *) policy;
1046 - (pkgRecords *) records;
1047 - (pkgProblemResolver *) resolver;
1048 - (pkgAcquire &) fetcher;
1049 - (pkgSourceList &) list;
1050 - (NSArray *) packages;
1051 - (NSArray *) sources;
1052 - (Source *) sourceWithKey:(NSString *)key;
1053 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1061 - (void) updateWithStatus:(Status &)status;
1063 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1065 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1066 - (NSObject<ProgressDelegate> *) progressDelegate;
1068 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1070 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1074 /* ProgressEvent Implementation {{{ */
1075 @implementation CydiaProgressEvent
1077 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1078 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1081 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1082 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1083 [event setPackage:package];
1087 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1088 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1090 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1091 NSArray *fields([description componentsSeparatedByString:@" "]);
1092 [event setItem:fields];
1094 if ([fields count] > 3) {
1095 [event setPackage:[fields objectAtIndex:2]];
1096 [event setVersion:[fields objectAtIndex:3]];
1099 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1104 + (NSArray *) _attributeKeys {
1105 return [NSArray arrayWithObjects:
1115 - (NSArray *) attributeKeys {
1116 return [[self class] _attributeKeys];
1119 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1120 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1123 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1124 if ((self = [super init]) != nil) {
1130 - (NSString *) message {
1134 - (NSString *) type {
1138 - (NSArray *) item {
1139 return (id) item_ ?: [NSNull null];
1142 - (void) setItem:(NSArray *)item {
1146 - (NSString *) package {
1147 return (id) package_ ?: [NSNull null];
1150 - (void) setPackage:(NSString *)package {
1154 - (NSString *) url {
1155 return (id) url_ ?: [NSNull null];
1158 - (void) setURL:(NSString *)url {
1162 - (void) setVersion:(NSString *)version {
1166 - (NSString *) version {
1167 return (id) version_ ?: [NSNull null];
1170 - (NSString *) compound:(NSString *)value {
1172 NSString *mode(nil); {
1173 NSString *type([self type]);
1174 if ([type isEqualToString:kCydiaProgressEventTypeError])
1175 mode = UCLocalize("ERROR");
1176 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1177 mode = UCLocalize("WARNING");
1181 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1187 - (NSString *) compoundMessage {
1188 return [self compound:[self message]];
1191 - (NSString *) compoundTitle {
1194 if (package_ == nil)
1196 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1197 title = [package name];
1201 return [self compound:title];
1207 // Cytore Definitions {{{
1208 struct PackageValue :
1211 Cytore::Offset<PackageValue> next_;
1213 uint32_t index_ : 23;
1214 uint32_t subscribed_ : 1;
1231 Cytore::Offset<PackageValue> packages_[1 << 16];
1234 static Cytore::File<MetaValue> MetaFile_;
1236 // Cytore Helper Functions {{{
1237 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1238 SplitHash nhash = { hashlittle(name, length) };
1240 PackageValue *metadata;
1242 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1243 offset: if (offset->IsNull()) {
1244 *offset = MetaFile_.New<PackageValue>(length + 1);
1245 metadata = &MetaFile_.Get(*offset);
1247 if (metadata == NULL) {
1251 metadata = new PackageValue();
1252 memset(metadata, 0, sizeof(*metadata));
1255 memcpy(metadata->name_, name, length + 1);
1256 metadata->nhash_ = nhash.u16[1];
1258 metadata = &MetaFile_.Get(*offset);
1260 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1261 offset = &metadata->next_;
1269 static void PackageImport(const void *key, const void *value, void *context) {
1270 bool &fail(*reinterpret_cast<bool *>(context));
1273 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1274 NSLog(@"failed to import package %@", key);
1278 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1279 NSDictionary *package((NSDictionary *) value);
1281 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1282 if ([subscribed boolValue] && !metadata->subscribed_)
1283 metadata->subscribed_ = true;
1285 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1286 time_t time([date timeIntervalSince1970]);
1287 if (metadata->first_ > time || metadata->first_ == 0)
1288 metadata->first_ = time;
1291 NSDate *date([package objectForKey:@"LastSeen"]);
1292 NSString *version([package objectForKey:@"LastVersion"]);
1294 if (date != nil && version != nil) {
1295 time_t time([date timeIntervalSince1970]);
1296 if (metadata->last_ < time || metadata->last_ == 0)
1297 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1298 size_t length(strlen(buffer));
1299 uint16_t vhash(hashlittle(buffer, length));
1301 size_t capped(std::min<size_t>(8, length));
1302 char *latest(buffer + length - capped);
1304 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1305 metadata->vhash_ = vhash;
1307 metadata->last_ = time;
1313 /* Source Class {{{ */
1314 @interface Source : NSObject {
1315 CYString depiction_;
1316 CYString description_;
1322 CYString distribution_;
1328 _H<NSString> authority_;
1330 CYString defaultIcon_;
1332 _H<NSDictionary> record_;
1336 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1338 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1340 - (NSString *) depictionForPackage:(NSString *)package;
1341 - (NSString *) supportForPackage:(NSString *)package;
1343 - (NSDictionary *) record;
1347 - (NSString *) distribution;
1348 - (NSString *) type;
1350 - (NSString *) base;
1353 - (NSString *) host;
1355 - (NSString *) name;
1356 - (NSString *) shortDescription;
1357 - (NSString *) label;
1358 - (NSString *) origin;
1359 - (NSString *) version;
1361 - (NSString *) defaultIcon;
1365 @implementation Source
1369 distribution_.clear();
1374 description_.clear();
1380 defaultIcon_.clear();
1387 + (NSString *) webScriptNameForSelector:(SEL)selector {
1389 else if (selector == @selector(addSection:))
1390 return @"addSection";
1391 else if (selector == @selector(removeSection:))
1392 return @"removeSection";
1393 else if (selector == @selector(remove))
1399 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1400 return [self webScriptNameForSelector:selector] == nil;
1403 + (NSArray *) _attributeKeys {
1404 return [NSArray arrayWithObjects:
1412 @"shortDescription",
1420 - (NSArray *) attributeKeys {
1421 return [[self class] _attributeKeys];
1424 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1425 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1428 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1431 trusted_ = index->IsTrusted();
1433 uri_.set(pool, index->GetURI());
1434 distribution_.set(pool, index->GetDist());
1435 type_.set(pool, index->GetType());
1437 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1438 if (dindex != NULL) {
1439 base_.set(pool, dindex->MetaIndexURI(""));
1442 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1445 pkgTagFile tags(&fd);
1447 pkgTagSection section;
1454 {"default-icon", &defaultIcon_},
1455 {"depiction", &depiction_},
1456 {"description", &description_},
1458 {"origin", &origin_},
1459 {"support", &support_},
1460 {"version", &version_},
1463 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1464 const char *start, *end;
1466 if (section.Find(names[i].name_, start, end)) {
1467 CYString &value(*names[i].value_);
1468 value.set(pool, start, end - start);
1474 record_ = [Sources_ objectForKey:[self key]];
1476 NSURL *url([NSURL URLWithString:uri_]);
1480 host_ = [host_ lowercaseString];
1485 authority_ = [url path];
1488 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1489 if ((self = [super init]) != nil) {
1490 [self setMetaIndex:index inPool:pool];
1494 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1495 NSDictionary *lhr = [self record];
1496 NSDictionary *rhr = [source record];
1498 if ((lhr == nil) != (rhr == nil))
1499 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1501 NSString *lhs = [self name];
1502 NSString *rhs = [source name];
1504 if ([lhs length] != 0 && [rhs length] != 0) {
1505 unichar lhc = [lhs characterAtIndex:0];
1506 unichar rhc = [rhs characterAtIndex:0];
1508 if (isalpha(lhc) && !isalpha(rhc))
1509 return NSOrderedAscending;
1510 else if (!isalpha(lhc) && isalpha(rhc))
1511 return NSOrderedDescending;
1514 return [lhs compare:rhs options:LaxCompareOptions_];
1517 - (NSString *) depictionForPackage:(NSString *)package {
1518 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1521 - (NSString *) supportForPackage:(NSString *)package {
1522 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1525 - (NSArray *) sections {
1526 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1529 - (void) _addSection:(NSString *)section {
1532 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1533 if (![sections containsObject:section]) {
1534 [sections addObject:section];
1538 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1543 - (bool) addSection:(NSString *)section {
1547 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1551 - (void) _removeSection:(NSString *)section {
1555 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1556 if ([sections containsObject:section]) {
1557 [sections removeObject:section];
1562 - (bool) removeSection:(NSString *)section {
1566 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1571 [Sources_ removeObjectForKey:[self key]];
1576 bool value(record_ != nil);
1577 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1581 - (NSDictionary *) record {
1589 - (NSString *) uri {
1593 - (NSString *) distribution {
1594 return distribution_;
1597 - (NSString *) type {
1601 - (NSString *) base {
1605 - (NSString *) key {
1606 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1609 - (NSString *) host {
1613 - (NSString *) name {
1614 return origin_.empty() ? (id) authority_ : origin_;
1617 - (NSString *) shortDescription {
1618 return description_;
1621 - (NSString *) label {
1622 return label_.empty() ? (id) authority_ : label_;
1625 - (NSString *) origin {
1629 - (NSString *) version {
1633 - (NSString *) defaultIcon {
1634 return defaultIcon_;
1639 /* CydiaOperation Class {{{ */
1640 @interface CydiaOperation : NSObject {
1641 _H<NSString> operator_;
1642 _H<NSString> value_;
1645 - (NSString *) operator;
1646 - (NSString *) value;
1650 @implementation CydiaOperation
1652 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1653 if ((self = [super init]) != nil) {
1654 operator_ = [NSString stringWithUTF8String:_operator];
1655 value_ = [NSString stringWithUTF8String:value];
1659 + (NSArray *) _attributeKeys {
1660 return [NSArray arrayWithObjects:
1666 - (NSArray *) attributeKeys {
1667 return [[self class] _attributeKeys];
1670 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1671 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1674 - (NSString *) operator {
1678 - (NSString *) value {
1684 /* CydiaClause Class {{{ */
1685 @interface CydiaClause : NSObject {
1686 _H<NSString> package_;
1687 _H<CydiaOperation> version_;
1690 - (NSString *) package;
1691 - (CydiaOperation *) version;
1695 @implementation CydiaClause
1697 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1698 if ((self = [super init]) != nil) {
1699 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1701 if (const char *version = dep.TargetVer())
1702 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1704 version_ = (id) [NSNull null];
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 *) package {
1727 - (CydiaOperation *) version {
1733 /* CydiaRelation Class {{{ */
1734 @interface CydiaRelation : NSObject {
1735 _H<NSString> relationship_;
1736 _H<NSMutableArray> clauses_;
1739 - (NSString *) relationship;
1740 - (NSArray *) clauses;
1744 @implementation CydiaRelation
1746 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1747 if ((self = [super init]) != nil) {
1748 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1749 clauses_ = [NSMutableArray arrayWithCapacity:8];
1751 pkgCache::DepIterator start;
1752 pkgCache::DepIterator end;
1753 dep.GlobOr(start, end); // ++dep
1756 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1758 // yes, seriously. (wtf?)
1766 + (NSArray *) _attributeKeys {
1767 return [NSArray arrayWithObjects:
1773 - (NSArray *) attributeKeys {
1774 return [[self class] _attributeKeys];
1777 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1778 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1781 - (NSString *) relationship {
1782 return relationship_;
1785 - (NSArray *) clauses {
1789 - (void) addClause:(CydiaClause *)clause {
1790 [clauses_ addObject:clause];
1795 /* Package Class {{{ */
1796 struct ParsedPackage {
1799 CYString architecture_;
1802 CYString depiction_;
1812 @interface Package : NSObject {
1815 uint32_t essential_ : 1;
1816 uint32_t obsolete_ : 1;
1817 uint32_t ignored_ : 1;
1823 _transient Database *database_;
1825 pkgCache::VerIterator version_;
1826 pkgCache::PkgIterator iterator_;
1827 pkgCache::VerFileIterator file_;
1833 CYString installed_;
1835 const char *section_;
1836 _transient NSString *section$_;
1840 PackageValue *metadata_;
1841 ParsedPackage *parsed_;
1843 _H<NSMutableArray> tags_;
1846 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1847 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1849 - (pkgCache::PkgIterator) iterator;
1852 - (NSString *) section;
1853 - (NSString *) simpleSection;
1855 - (NSString *) longSection;
1856 - (NSString *) shortSection;
1860 - (MIMEAddress *) maintainer;
1862 - (NSString *) longDescription;
1863 - (NSString *) shortDescription;
1866 - (PackageValue *) metadata;
1869 - (bool) subscribed;
1870 - (bool) setSubscribed:(bool)subscribed;
1874 - (NSString *) latest;
1875 - (NSString *) installed;
1876 - (BOOL) uninstalled;
1879 - (BOOL) upgradableAndEssential:(BOOL)essential;
1882 - (BOOL) unfiltered;
1886 - (BOOL) halfConfigured;
1887 - (BOOL) halfInstalled;
1889 - (NSString *) mode;
1892 - (NSString *) name;
1894 - (NSString *) homepage;
1895 - (NSString *) depiction;
1896 - (MIMEAddress *) author;
1898 - (NSString *) support;
1900 - (NSArray *) files;
1901 - (NSArray *) warnings;
1902 - (NSArray *) applications;
1904 - (Source *) source;
1907 - (BOOL) matches:(NSArray *)query;
1909 - (bool) hasSupportingRole;
1910 - (BOOL) hasTag:(NSString *)tag;
1911 - (NSString *) primaryPurpose;
1912 - (NSArray *) purposes;
1913 - (bool) isCommercial;
1915 - (void) setIndex:(size_t)index;
1917 - (CYString &) cyname;
1919 - (uint32_t) compareBySection:(NSArray *)sections;
1924 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1925 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1926 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1927 - (bool) isVisibleInSection:(NSString *)section;
1928 - (bool) isVisibleInSource:(Source *)source;
1932 uint32_t PackageChangesRadix(Package *self, void *) {
1937 uint32_t timestamp : 30;
1938 uint32_t ignored : 1;
1939 uint32_t upgradable : 1;
1943 bool upgradable([self upgradableAndEssential:YES]);
1944 value.bits.upgradable = upgradable ? 1 : 0;
1947 value.bits.timestamp = 0;
1948 value.bits.ignored = [self ignored] ? 0 : 1;
1949 value.bits.upgradable = 1;
1951 value.bits.timestamp = [self seen] >> 2;
1952 value.bits.ignored = 0;
1953 value.bits.upgradable = 0;
1956 return _not(uint32_t) - value.key;
1959 uint32_t PackagePrefixRadix(Package *self, void *context) {
1960 size_t offset(reinterpret_cast<size_t>(context));
1961 CYString &name([self cyname]);
1963 size_t size(name.size());
1966 char *text(name.data());
1969 if (!isdigit(text[0]))
1973 while (size != digits && isdigit(text[digits]))
1981 if (offset == 0 && zeros != 0) {
1982 memset(data, '0', zeros);
1983 memcpy(data + zeros, text, 4 - zeros);
1985 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1986 if (size <= offset - zeros)
1989 text += offset - zeros;
1990 size -= offset - zeros;
1993 memcpy(data, text, 4);
1995 memcpy(data, text, size);
1996 memset(data + size, 0, 4 - size);
1999 for (size_t i(0); i != 4; ++i)
2000 if (isalpha(data[i]))
2008 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2010 /* XXX: ntohl may be more honest */
2011 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2014 CYString &(*PackageName)(Package *self, SEL sel);
2016 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2017 _profile(PackageNameCompare)
2018 CYString &lhi(PackageName(lhs, @selector(cyname)));
2019 CYString &rhi(PackageName(rhs, @selector(cyname)));
2020 CFStringRef lhn(lhi), rhn(rhi);
2023 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2024 else if (rhn == NULL)
2025 return NSOrderedDescending;
2027 _profile(PackageNameCompare$NumbersLast)
2028 if (!lhi.empty() && !rhi.empty()) {
2029 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2030 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2031 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2032 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2033 return lha ? NSOrderedAscending : NSOrderedDescending;
2037 CFIndex length = CFStringGetLength(lhn);
2039 _profile(PackageNameCompare$Compare)
2040 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2045 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2046 return PackageNameCompare(*lhs, *rhs, context);
2049 struct PackageNameOrdering :
2050 std::binary_function<Package *, Package *, bool>
2052 _finline bool operator ()(Package *lhs, Package *rhs) const {
2053 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2057 @implementation Package
2059 - (NSString *) description {
2060 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2064 if (parsed_ != NULL)
2069 + (NSString *) webScriptNameForSelector:(SEL)selector {
2071 else if (selector == @selector(clear))
2073 else if (selector == @selector(getField:))
2075 else if (selector == @selector(hasTag:))
2077 else if (selector == @selector(install))
2079 else if (selector == @selector(remove))
2085 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2086 return [self webScriptNameForSelector:selector] == nil;
2089 + (NSArray *) _attributeKeys {
2090 return [NSArray arrayWithObjects:
2110 @"shortDescription",
2123 - (NSArray *) attributeKeys {
2124 return [[self class] _attributeKeys];
2127 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2128 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2131 - (NSArray *) relations {
2132 @synchronized (database_) {
2133 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2134 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2135 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2139 - (NSString *) architecture {
2141 @synchronized (database_) {
2142 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2145 - (NSString *) getField:(NSString *)name {
2146 @synchronized (database_) {
2147 if ([database_ era] != era_ || file_.end())
2150 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2152 const char *start, *end;
2153 if (!parser.Find([name UTF8String], start, end))
2154 return (NSString *) [NSNull null];
2156 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2160 if (parsed_ != NULL)
2162 @synchronized (database_) {
2163 if ([database_ era] != era_ || file_.end())
2166 ParsedPackage *parsed(new ParsedPackage);
2169 _profile(Package$parse)
2170 pkgRecords::Parser *parser;
2172 _profile(Package$parse$Lookup)
2173 parser = &[database_ records]->Lookup(file_);
2178 _profile(Package$parse$Find)
2183 {"architecture", &parsed->architecture_},
2184 {"icon", &parsed->icon_},
2185 {"depiction", &parsed->depiction_},
2186 {"homepage", &parsed->homepage_},
2187 {"website", &website},
2188 {"bugs", &parsed->bugs_},
2189 {"support", &parsed->support_},
2190 {"sponsor", &parsed->sponsor_},
2191 {"author", &parsed->author_},
2194 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2195 const char *start, *end;
2197 if (parser->Find(names[i].name_, start, end)) {
2198 CYString &value(*names[i].value_);
2199 _profile(Package$parse$Value)
2200 value.set(pool_, start, end - start);
2206 _profile(Package$parse$Tagline)
2207 const char *start, *end;
2208 if (parser->ShortDesc(start, end)) {
2209 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2212 while (stop != start && stop[-1] == '\r')
2214 parsed->tagline_.set(pool_, start, stop - start);
2218 _profile(Package$parse$Retain)
2219 if (parsed->homepage_.empty())
2220 parsed->homepage_ = website;
2221 if (parsed->homepage_ == parsed->depiction_)
2222 parsed->homepage_.clear();
2227 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2228 if ((self = [super init]) != nil) {
2229 _profile(Package$initWithVersion)
2232 database_ = database;
2233 era_ = [database era];
2237 pkgCache::PkgIterator iterator(version.ParentPkg());
2238 iterator_ = iterator;
2240 _profile(Package$initWithVersion$Version)
2241 if (!version_.end())
2242 file_ = version_.FileList();
2244 pkgCache &cache([database_ cache]);
2245 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2249 _profile(Package$initWithVersion$Cache)
2250 name_.set(NULL, iterator.Display());
2252 latest_.set(NULL, StripVersion_(version_.VerStr()));
2254 pkgCache::VerIterator current(iterator.CurrentVer());
2256 installed_.set(NULL, StripVersion_(current.VerStr()));
2259 _profile(Package$initWithVersion$Tags)
2260 pkgCache::TagIterator tag(iterator.TagList());
2262 tags_ = [NSMutableArray arrayWithCapacity:8];
2264 const char *name(tag.Name());
2265 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2267 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2268 if (strcmp(name + 6, "enduser") == 0)
2270 else if (strcmp(name + 6, "hacker") == 0)
2272 else if (strcmp(name + 6, "developer") == 0)
2274 else if (strcmp(name + 6, "cydia") == 0)
2280 if (strncmp(name, "cydia::", 7) == 0) {
2281 if (strcmp(name + 7, "essential") == 0)
2283 else if (strcmp(name + 7, "obsolete") == 0)
2288 } while (!tag.end());
2292 _profile(Package$initWithVersion$Metadata)
2293 const char *mixed(iterator.Name());
2294 size_t size(strlen(mixed));
2295 char lower[size + 1];
2297 for (size_t i(0); i != size; ++i)
2298 lower[i] = mixed[i] | 0x20;
2301 PackageValue *metadata(PackageFind(lower, size));
2302 metadata_ = metadata;
2304 id_.set(NULL, metadata->name_, size);
2306 const char *latest(version_.VerStr());
2307 size_t length(strlen(latest));
2309 uint16_t vhash(hashlittle(latest, length));
2311 size_t capped(std::min<size_t>(8, length));
2312 latest = latest + length - capped;
2314 if (metadata->first_ == 0)
2315 metadata->first_ = now_;
2317 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2318 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2319 metadata->vhash_ = vhash;
2320 metadata->last_ = now_;
2321 } else if (metadata->last_ == 0)
2322 metadata->last_ = metadata->first_;
2325 _profile(Package$initWithVersion$Section)
2326 section_ = iterator.Section();
2329 _profile(Package$initWithVersion$Flags)
2330 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2331 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2336 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2337 pkgCache::VerIterator version;
2339 _profile(Package$packageWithIterator$GetCandidateVer)
2340 version = [database policy]->GetCandidateVer(iterator);
2348 _profile(Package$packageWithIterator$Allocate)
2349 package = [Package allocWithZone:zone];
2352 _profile(Package$packageWithIterator$Initialize)
2354 initWithVersion:version
2361 _profile(Package$packageWithIterator$Autorelease)
2362 package = [package autorelease];
2368 - (pkgCache::PkgIterator) iterator {
2372 - (NSString *) section {
2373 if (section$_ == nil) {
2374 if (section_ == NULL)
2377 _profile(Package$section$mappedSectionForPointer)
2378 section$_ = [database_ mappedSectionForPointer:section_];
2383 - (NSString *) simpleSection {
2384 if (NSString *section = [self section])
2385 return Simplify(section);
2390 - (NSString *) longSection {
2391 return LocalizeSection([self section]);
2394 - (NSString *) shortSection {
2395 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2398 - (NSString *) uri {
2401 pkgIndexFile *index;
2402 pkgCache::PkgFileIterator file(file_.File());
2403 if (![database_ list].FindIndex(file, index))
2405 return [NSString stringWithUTF8String:iterator_->Path];
2406 //return [NSString stringWithUTF8String:file.Site()];
2407 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2411 - (MIMEAddress *) maintainer {
2412 @synchronized (database_) {
2413 if ([database_ era] != era_ || file_.end())
2416 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2417 const std::string &maintainer(parser->Maintainer());
2418 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2422 @synchronized (database_) {
2423 if ([database_ era] != era_ || version_.end())
2426 return version_->InstalledSize;
2429 - (NSString *) longDescription {
2430 @synchronized (database_) {
2431 if ([database_ era] != era_ || file_.end())
2434 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2435 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2437 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2438 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2439 if ([lines count] < 2)
2442 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2443 for (size_t i(1), e([lines count]); i != e; ++i) {
2444 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2445 [trimmed addObject:trim];
2448 return [trimmed componentsJoinedByString:@"\n"];
2451 - (NSString *) shortDescription {
2452 if (parsed_ != NULL)
2453 return static_cast<NSString *>(parsed_->tagline_);
2455 @synchronized (database_) {
2456 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2458 const char *start, *end;
2459 if (!parser.ShortDesc(start, end))
2462 if (end - start > 200)
2466 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2469 while (end != start && end[-1] == '\r')
2473 return [(id) CYStringCreate(start, end - start) autorelease];
2477 _profile(Package$index)
2478 CFStringRef name((CFStringRef) [self name]);
2479 if (CFStringGetLength(name) == 0)
2481 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2482 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2484 return toupper(character);
2488 - (PackageValue *) metadata {
2493 PackageValue *metadata([self metadata]);
2494 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2497 - (bool) subscribed {
2498 return [self metadata]->subscribed_;
2501 - (bool) setSubscribed:(bool)subscribed {
2502 PackageValue *metadata([self metadata]);
2503 if (metadata->subscribed_ == subscribed)
2505 metadata->subscribed_ = subscribed;
2513 - (NSString *) latest {
2517 - (NSString *) installed {
2521 - (BOOL) uninstalled {
2522 return installed_.empty();
2526 return !version_.end();
2529 - (BOOL) upgradableAndEssential:(BOOL)essential {
2530 _profile(Package$upgradableAndEssential)
2531 pkgCache::VerIterator current(iterator_.CurrentVer());
2533 return essential && essential_;
2535 return !version_.end() && version_ != current;
2539 - (BOOL) essential {
2544 return [database_ cache][iterator_].InstBroken();
2547 - (BOOL) unfiltered {
2548 _profile(Package$unfiltered$obsolete)
2549 if (_unlikely(obsolete_))
2553 _profile(Package$unfiltered$hasSupportingRole)
2554 if (_unlikely(![self hasSupportingRole]))
2562 if (![self unfiltered])
2567 _profile(Package$visible$section)
2568 section = [self section];
2571 _profile(Package$visible$isSectionVisible)
2572 if (!isSectionVisible(section))
2580 unsigned char current(iterator_->CurrentState);
2581 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2584 - (BOOL) halfConfigured {
2585 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2588 - (BOOL) halfInstalled {
2589 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2593 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2594 return state.Mode != pkgDepCache::ModeKeep;
2597 - (NSString *) mode {
2598 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2600 switch (state.Mode) {
2601 case pkgDepCache::ModeDelete:
2602 if ((state.iFlags & pkgDepCache::Purge) != 0)
2606 case pkgDepCache::ModeKeep:
2607 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2608 return @"REINSTALL";
2609 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2613 case pkgDepCache::ModeInstall:
2614 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2615 return @"REINSTALL";
2616 else*/ switch (state.Status) {
2618 return @"DOWNGRADE";
2624 return @"NEW_INSTALL";
2635 - (NSString *) name {
2636 return name_.empty() ? id_ : name_;
2639 - (UIImage *) icon {
2640 NSString *section = [self simpleSection];
2643 if (parsed_ != NULL)
2644 if (NSString *href = parsed_->icon_)
2645 if ([href hasPrefix:@"file:///"])
2646 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2647 if (icon == nil) if (section != nil)
2648 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2649 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2650 if ([dicon hasPrefix:@"file:///"])
2651 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2653 icon = [UIImage applicationImageNamed:@"unknown.png"];
2657 - (NSString *) homepage {
2658 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2661 - (NSString *) depiction {
2662 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2665 - (MIMEAddress *) sponsor {
2666 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2669 - (MIMEAddress *) author {
2670 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2673 - (NSString *) support {
2674 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2677 - (NSArray *) files {
2678 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2679 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2682 fin.open([path UTF8String]);
2687 while (std::getline(fin, line))
2688 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2693 - (NSString *) state {
2694 @synchronized (database_) {
2695 if ([database_ era] != era_ || file_.end())
2698 switch (iterator_->CurrentState) {
2699 case pkgCache::State::NotInstalled:
2700 return @"NotInstalled";
2701 case pkgCache::State::UnPacked:
2703 case pkgCache::State::HalfConfigured:
2704 return @"HalfConfigured";
2705 case pkgCache::State::HalfInstalled:
2706 return @"HalfInstalled";
2707 case pkgCache::State::ConfigFiles:
2708 return @"ConfigFiles";
2709 case pkgCache::State::Installed:
2710 return @"Installed";
2711 case pkgCache::State::TriggersAwaited:
2712 return @"TriggersAwaited";
2713 case pkgCache::State::TriggersPending:
2714 return @"TriggersPending";
2717 return (NSString *) [NSNull null];
2720 - (NSString *) selection {
2721 @synchronized (database_) {
2722 if ([database_ era] != era_ || file_.end())
2725 switch (iterator_->SelectedState) {
2726 case pkgCache::State::Unknown:
2728 case pkgCache::State::Install:
2730 case pkgCache::State::Hold:
2732 case pkgCache::State::DeInstall:
2733 return @"DeInstall";
2734 case pkgCache::State::Purge:
2738 return (NSString *) [NSNull null];
2741 - (NSArray *) warnings {
2742 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2743 const char *name(iterator_.Name());
2745 size_t length(strlen(name));
2746 if (length < 2) invalid:
2747 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2748 else for (size_t i(0); i != length; ++i)
2750 /* XXX: technically this is not allowed */
2751 (name[i] < 'A' || name[i] > 'Z') &&
2752 (name[i] < 'a' || name[i] > 'z') &&
2753 (name[i] < '0' || name[i] > '9') &&
2754 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2757 if (strcmp(name, "cydia") != 0) {
2760 bool _private = false;
2763 bool repository = [[self section] isEqualToString:@"Repositories"];
2765 if (NSArray *files = [self files])
2766 for (NSString *file in files)
2767 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2769 else if (!user && [file isEqualToString:@"/User"])
2771 else if (!_private && [file isEqualToString:@"/private"])
2773 else if (!stash && [file isEqualToString:@"/var/stash"])
2776 /* XXX: this is not sensitive enough. only some folders are valid. */
2777 if (cydia && !repository)
2778 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2780 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2782 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2784 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2787 return [warnings count] == 0 ? nil : warnings;
2790 - (NSArray *) applications {
2791 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2793 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2795 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2796 if (NSArray *files = [self files])
2797 for (NSString *file in files)
2798 if (application_r(file)) {
2799 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2800 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2801 if ([id isEqualToString:me])
2804 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2806 display = application_r[1];
2808 NSString *bundle([file stringByDeletingLastPathComponent]);
2809 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2810 if (icon == nil || [icon length] == 0)
2812 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2814 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2815 [applications addObject:application];
2817 [application addObject:id];
2818 [application addObject:display];
2819 [application addObject:url];
2822 return [applications count] == 0 ? nil : applications;
2825 - (Source *) source {
2826 if (source_ == nil) {
2827 @synchronized (database_) {
2828 if ([database_ era] != era_ || file_.end())
2829 source_ = (Source *) [NSNull null];
2831 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2835 return source_ == (Source *) [NSNull null] ? nil : source_;
2842 - (BOOL) matches:(NSArray *)query {
2843 if (query == nil || [query count] == 0)
2852 string = [self name];
2853 length = [string length];
2855 for (NSString *term in query) {
2856 range = [string rangeOfString:term options:MatchCompareOptions_];
2857 if (range.location != NSNotFound)
2858 rank_ -= 6 * 1000000 / length;
2863 length = [string length];
2865 for (NSString *term in query) {
2866 range = [string rangeOfString:term options:MatchCompareOptions_];
2867 if (range.location != NSNotFound)
2868 rank_ -= 6 * 1000000 / length;
2872 string = [self shortDescription];
2873 length = [string length];
2874 NSUInteger stop(std::min<NSUInteger>(length, 200));
2876 for (NSString *term in query) {
2877 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2878 if (range.location != NSNotFound)
2879 rank_ -= 2 * 100000;
2885 - (bool) hasSupportingRole {
2890 if ([Role_ isEqualToString:@"User"])
2894 if ([Role_ isEqualToString:@"Hacker"])
2898 if ([Role_ isEqualToString:@"Developer"])
2903 - (NSArray *) tags {
2907 - (BOOL) hasTag:(NSString *)tag {
2908 return tags_ == nil ? NO : [tags_ containsObject:tag];
2911 - (NSString *) primaryPurpose {
2912 for (NSString *tag in (NSArray *) tags_)
2913 if ([tag hasPrefix:@"purpose::"])
2914 return [tag substringFromIndex:9];
2918 - (NSArray *) purposes {
2919 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2920 for (NSString *tag in (NSArray *) tags_)
2921 if ([tag hasPrefix:@"purpose::"])
2922 [purposes addObject:[tag substringFromIndex:9]];
2923 return [purposes count] == 0 ? nil : purposes;
2926 - (bool) isCommercial {
2927 return [self hasTag:@"cydia::commercial"];
2930 - (void) setIndex:(size_t)index {
2931 if (metadata_->index_ != index)
2932 metadata_->index_ = index;
2935 - (CYString &) cyname {
2936 return name_.empty() ? id_ : name_;
2939 - (uint32_t) compareBySection:(NSArray *)sections {
2940 NSString *section([self section]);
2941 for (size_t i(0), e([sections count]); i != e; ++i) {
2942 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2946 return _not(uint32_t);
2950 @synchronized (database_) {
2951 pkgProblemResolver *resolver = [database_ resolver];
2952 resolver->Clear(iterator_);
2954 pkgCacheFile &cache([database_ cache]);
2955 cache->SetReInstall(iterator_, false);
2956 cache->MarkKeep(iterator_, false);
2960 @synchronized (database_) {
2961 pkgProblemResolver *resolver = [database_ resolver];
2962 resolver->Clear(iterator_);
2963 resolver->Protect(iterator_);
2965 pkgCacheFile &cache([database_ cache]);
2966 cache->SetReInstall(iterator_, false);
2967 cache->MarkInstall(iterator_, false);
2969 pkgDepCache::StateCache &state((*cache)[iterator_]);
2970 if (!state.Install())
2971 cache->SetReInstall(iterator_, true);
2975 @synchronized (database_) {
2976 pkgProblemResolver *resolver = [database_ resolver];
2977 resolver->Clear(iterator_);
2978 resolver->Remove(iterator_);
2979 resolver->Protect(iterator_);
2981 pkgCacheFile &cache([database_ cache]);
2982 cache->SetReInstall(iterator_, false);
2983 cache->MarkDelete(iterator_, true);
2986 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2987 _profile(Package$isUnfilteredAndSearchedForBy)
2990 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2991 value &= [self unfiltered];
2994 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2995 value &= [self matches:query];
3002 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3003 if ([search length] == 0)
3006 _profile(Package$isUnfilteredAndSelectedForBy)
3009 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3010 value &= [self unfiltered];
3013 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3014 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3021 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3022 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3025 - (bool) isVisibleInSection:(NSString *)name {
3026 NSString *section([self section]);
3030 section == nil && [name length] == 0 ||
3031 [name isEqualToString:section]
3032 ) && [self visible];
3035 - (bool) isVisibleInSource:(Source *)source {
3036 return [self source] == source && [self visible];
3041 /* Section Class {{{ */
3042 @interface Section : NSObject {
3047 _H<NSString> localized_;
3050 - (NSComparisonResult) compareByLocalized:(Section *)section;
3051 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3052 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3053 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3054 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3055 - (NSString *) name;
3062 - (void) addToCount;
3064 - (void) setCount:(size_t)count;
3065 - (NSString *) localized;
3069 @implementation Section
3071 - (NSComparisonResult) compareByLocalized:(Section *)section {
3072 NSString *lhs(localized_);
3073 NSString *rhs([section localized]);
3075 /*if ([lhs length] != 0 && [rhs length] != 0) {
3076 unichar lhc = [lhs characterAtIndex:0];
3077 unichar rhc = [rhs characterAtIndex:0];
3079 if (isalpha(lhc) && !isalpha(rhc))
3080 return NSOrderedAscending;
3081 else if (!isalpha(lhc) && isalpha(rhc))
3082 return NSOrderedDescending;
3085 return [lhs compare:rhs options:LaxCompareOptions_];
3088 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3089 if ((self = [self initWithName:name localize:NO]) != nil) {
3090 if (localized != nil)
3091 localized_ = localized;
3095 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3096 return [self initWithName:name row:0 localize:localize];
3099 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3100 if ((self = [super init]) != nil) {
3105 localized_ = LocalizeSection(name_);
3109 /* XXX: localize the index thingees */
3110 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3111 if ((self = [super init]) != nil) {
3112 name_ = [NSString stringWithCharacters:&index length:1];
3118 - (NSString *) name {
3138 - (void) addToCount {
3142 - (void) setCount:(size_t)count {
3146 - (NSString *) localized {
3153 class CydiaLogCleaner :
3154 public pkgArchiveCleaner
3157 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3162 /* Database Implementation {{{ */
3163 @implementation Database
3165 + (Database *) sharedInstance {
3166 static _H<Database> instance;
3167 if (instance == nil)
3168 instance = [[[Database alloc] init] autorelease];
3176 - (void) releasePackages {
3177 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3178 CFArrayRemoveAllValues(packages_);
3182 // XXX: actually implement this thing
3184 [self releasePackages];
3185 apr_pool_destroy(pool_);
3186 NSRecycleZone(zone_);
3190 - (void) _readCydia:(NSNumber *)fd {
3191 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3192 std::istream is(&ib);
3195 static Pcre finish_r("^finish:([^:]*)$");
3197 while (std::getline(is, line)) {
3198 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3200 const char *data(line.c_str());
3201 size_t size = line.size();
3202 lprintf("C:%s\n", data);
3204 if (finish_r(data, size)) {
3205 NSString *finish = finish_r[1];
3206 int index = [Finishes_ indexOfObject:finish];
3207 if (index != INT_MAX && index > Finish_)
3217 - (void) _readStatus:(NSNumber *)fd {
3218 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3219 std::istream is(&ib);
3222 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3223 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3225 while (std::getline(is, line)) {
3226 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3228 const char *data(line.c_str());
3229 size_t size(line.size());
3230 lprintf("S:%s\n", data);
3232 if (conffile_r(data, size)) {
3233 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3234 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3235 } else if (strncmp(data, "status: ", 8) == 0) {
3236 // status: <package>: {unpacked,half-configured,installed}
3237 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3238 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3239 } else if (strncmp(data, "processing: ", 12) == 0) {
3240 // processing: configure: config-test
3241 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3242 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3243 } else if (pmstatus_r(data, size)) {
3244 std::string type([pmstatus_r[1] UTF8String]);
3246 NSString *package = pmstatus_r[2];
3247 if ([package isEqualToString:@"dpkg-exec"])
3250 float percent([pmstatus_r[3] floatValue]);
3251 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3253 NSString *string = pmstatus_r[4];
3255 if (type == "pmerror") {
3256 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3257 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3258 } else if (type == "pmstatus") {
3259 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3260 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3261 } else if (type == "pmconffile")
3262 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3264 lprintf("E:unknown pmstatus\n");
3266 lprintf("E:unknown status\n");
3274 - (void) _readOutput:(NSNumber *)fd {
3275 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3276 std::istream is(&ib);
3279 while (std::getline(is, line)) {
3280 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3282 lprintf("O:%s\n", line.c_str());
3284 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3285 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3297 - (Package *) packageWithName:(NSString *)name {
3300 @synchronized (self) {
3301 if (static_cast<pkgDepCache *>(cache_) == NULL)
3303 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3304 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3308 if ((self = [super init]) != nil) {
3315 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3316 apr_pool_create(&pool_, NULL);
3318 size_t capacity(MetaFile_->active_);
3324 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3325 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3329 _assert(pipe(fds) != -1);
3332 _config->Set("APT::Keep-Fds::", cydiafd_);
3333 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3336 detachNewThreadSelector:@selector(_readCydia:)
3338 withObject:[NSNumber numberWithInt:fds[0]]
3341 _assert(pipe(fds) != -1);
3345 detachNewThreadSelector:@selector(_readStatus:)
3347 withObject:[NSNumber numberWithInt:fds[0]]
3350 _assert(pipe(fds) != -1);
3351 _assert(dup2(fds[0], 0) != -1);
3352 _assert(close(fds[0]) != -1);
3354 input_ = fdopen(fds[1], "a");
3356 _assert(pipe(fds) != -1);
3357 _assert(dup2(fds[1], 1) != -1);
3358 _assert(close(fds[1]) != -1);
3361 detachNewThreadSelector:@selector(_readOutput:)
3363 withObject:[NSNumber numberWithInt:fds[0]]
3368 - (pkgCacheFile &) cache {
3372 - (pkgDepCache::Policy *) policy {
3376 - (pkgRecords *) records {
3380 - (pkgProblemResolver *) resolver {
3384 - (pkgAcquire &) fetcher {
3388 - (pkgSourceList &) list {
3392 - (NSArray *) packages {
3393 return (NSArray *) packages_;
3396 - (NSArray *) sources {
3400 - (Source *) sourceWithKey:(NSString *)key {
3401 for (Source *source in [self sources]) {
3402 if ([[source key] isEqualToString:key])
3407 - (bool) popErrorWithTitle:(NSString *)title {
3410 while (!_error->empty()) {
3412 bool warning(!_error->PopMessage(error));
3417 size_t size(error.size());
3418 if (size == 0 || error[size - 1] != '\n')
3420 error.resize(size - 1);
3423 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3425 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3431 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3432 return [self popErrorWithTitle:title] || !success;
3435 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3436 @synchronized (self) {
3439 [self releasePackages];
3442 [sourceList_ removeAllObjects];
3462 apr_pool_clear(pool_);
3464 NSRecycleZone(zone_);
3465 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3467 int chk(creat("/tmp/cydia.chk", 0644));
3471 if (invocation != nil)
3472 [invocation invoke];
3474 NSString *title(UCLocalize("DATABASE"));
3477 OpProgress progress;
3478 while (!cache_.Open(progress, true)) { pop:
3480 bool warning(!_error->PopMessage(error));
3481 lprintf("cache_.Open():[%s]\n", error.c_str());
3483 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3484 [delegate_ repairWithSelector:@selector(configure)];
3485 else if (error == "The package lists or status file could not be parsed or opened.")
3486 [delegate_ repairWithSelector:@selector(update)];
3487 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3488 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3489 // else if (error == "Malformed Status line")
3490 // else if (error == "The list of sources could not be read.")
3492 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3502 unlink("/tmp/cydia.chk");
3504 now_ = [[NSDate date] timeIntervalSince1970];
3506 policy_ = new pkgDepCache::Policy();
3507 records_ = new pkgRecords(cache_);
3508 resolver_ = new pkgProblemResolver(cache_);
3509 fetcher_ = new pkgAcquire(&status_);
3512 list_ = new pkgSourceList();
3513 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3516 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3517 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3521 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3524 if (cache_->BrokenCount() != 0) {
3525 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3528 if (cache_->BrokenCount() != 0) {
3529 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3533 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3537 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3538 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3539 [sourceList_ addObject:object];
3541 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3542 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3543 // XXX: this could be more intelligent
3544 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3545 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3547 sourceMap_[cached->ID] = object;
3552 /*std::vector<Package *> packages;
3553 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3558 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3559 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3560 //packages.push_back(package);
3561 CFArrayAppendValue(packages_, CFRetain(package));
3565 /*if (packages.empty())
3566 packages_ = [[NSArray alloc] init];
3568 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3571 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3572 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3573 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3581 /*if (!packages.empty())
3582 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3583 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3585 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3587 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3589 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3593 size_t count(CFArrayGetCount(packages_));
3594 MetaFile_->active_ = count;
3596 for (size_t index(0); index != count; ++index)
3597 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3604 @synchronized (self) {
3606 resolver_ = new pkgProblemResolver(cache_);
3608 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3609 if (!cache_[iterator].Keep())
3610 cache_->MarkKeep(iterator, false);
3611 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3612 cache_->SetReInstall(iterator, false);
3615 - (void) configure {
3616 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3618 system([dpkg UTF8String]);
3623 // XXX: I don't remember this condition
3628 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3630 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3632 if ([self popErrorWithTitle:title])
3636 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3638 CydiaLogCleaner cleaner;
3639 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3646 fetcher_->Shutdown();
3648 pkgRecords records(cache_);
3650 lock_ = new FileFd();
3651 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3653 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3655 if ([self popErrorWithTitle:title])
3659 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3662 manager_ = (_system->CreatePM(cache_));
3663 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3670 bool substrate(RestartSubstrate_);
3671 RestartSubstrate_ = false;
3673 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3675 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3677 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3679 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3680 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3683 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3685 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3687 [self popErrorWithTitle:title];
3691 bool failed = false;
3692 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3693 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3695 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3701 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3709 RestartSubstrate_ = true;
3712 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3714 if (_error->PendingError()) {
3719 if (result == pkgPackageManager::Failed) {
3724 if (result != pkgPackageManager::Completed) {
3729 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3731 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3733 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3734 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3737 if (![before isEqualToArray:after])
3742 NSString *title(UCLocalize("UPGRADE"));
3743 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3749 [self updateWithStatus:status_];
3752 - (void) updateWithStatus:(Status &)status {
3753 NSString *title(UCLocalize("REFRESHING_DATA"));
3756 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3760 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3761 if ([self popErrorWithTitle:title])
3764 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3766 bool success(ListUpdate(status, list, PulseInterval_));
3767 if (status.WasCancelled())
3770 [self popErrorWithTitle:title forOperation:success];
3771 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3775 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3778 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3779 delegate_ = delegate;
3782 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3783 progress_ = delegate;
3784 status_.setDelegate(delegate);
3787 - (NSObject<ProgressDelegate> *) progressDelegate {
3791 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3792 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3793 return i == sourceMap_.end() ? nil : i->second;
3796 - (NSString *) mappedSectionForPointer:(const char *)section {
3797 _H<NSString> *mapped;
3799 _profile(Database$mappedSectionForPointer$Cache)
3800 mapped = §ions_[section];
3803 if (*mapped == NULL) {
3804 size_t length(strlen(section));
3805 char spaced[length + 1];
3807 _profile(Database$mappedSectionForPointer$Replace)
3808 for (size_t index(0); index != length; ++index)
3809 spaced[index] = section[index] == '_' ? ' ' : section[index];
3810 spaced[length] = '\0';
3815 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3816 string = [NSString stringWithUTF8String:spaced];
3819 _profile(Database$mappedSectionForPointer$Map)
3820 string = [SectionMap_ objectForKey:string] ?: string;
3830 static _H<NSMutableSet> Diversions_;
3832 @interface Diversion : NSObject {
3835 _H<NSString> format_;
3840 @implementation Diversion
3842 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3843 if ((self = [super init]) != nil) {
3844 pattern_ = [from UTF8String];
3850 - (NSString *) divert:(NSString *)url {
3851 return !pattern_(url) ? nil : pattern_->*format_;
3854 + (NSURL *) divertURL:(NSURL *)url {
3856 NSString *href([url absoluteString]);
3858 for (Diversion *diversion in (id) Diversions_)
3859 if (NSString *diverted = [diversion divert:href]) {
3861 NSLog(@"div: %@", diverted);
3863 url = [NSURL URLWithString:diverted];
3870 - (NSString *) key {
3874 - (NSUInteger) hash {
3878 - (BOOL) isEqual:(Diversion *)object {
3879 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3884 @interface CydiaObject : NSObject {
3885 _H<IndirectDelegate> indirect_;
3886 _transient id delegate_;
3889 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3893 @interface CydiaWebViewController : CyteWebViewController {
3894 _H<CydiaObject> cydia_;
3897 + (void) addDiversion:(Diversion *)diversion;
3901 /* Web Scripting {{{ */
3902 @implementation CydiaObject
3904 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3905 if ((self = [super init]) != nil) {
3906 indirect_ = indirect;
3910 - (void) setDelegate:(id)delegate {
3911 delegate_ = delegate;
3914 + (NSArray *) _attributeKeys {
3915 return [NSArray arrayWithObjects:
3932 - (NSArray *) attributeKeys {
3933 return [[self class] _attributeKeys];
3936 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3937 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3940 - (NSString *) version {
3944 - (NSString *) device {
3945 return [[UIDevice currentDevice] uniqueIdentifier];
3948 - (NSString *) firmware {
3949 return [[UIDevice currentDevice] systemVersion];
3952 - (NSString *) hostname {
3953 return [[UIDevice currentDevice] name];
3956 - (NSString *) idiom {
3957 return (id) Idiom_ ?: [NSNull null];
3960 - (NSString *) plmn {
3961 return (id) PLMN_ ?: [NSNull null];
3964 - (NSString *) bbsnum {
3965 return (id) BBSNum_ ?: [NSNull null];
3968 - (NSString *) ecid {
3969 return (id) ChipID_ ?: [NSNull null];
3972 - (NSString *) serial {
3973 return SerialNumber_;
3976 - (NSString *) role {
3977 return (id) Role_ ?: [NSNull null];
3980 - (NSString *) model {
3981 return [NSString stringWithUTF8String:Machine_];
3984 - (NSString *) token {
3985 return (id) Token_ ?: [NSNull null];
3988 + (NSString *) webScriptNameForSelector:(SEL)selector {
3990 else if (selector == @selector(addBridgedHost:))
3991 return @"addBridgedHost";
3992 else if (selector == @selector(addInsecureHost:))
3993 return @"addInsecureHost";
3994 else if (selector == @selector(addInternalRedirect::))
3995 return @"addInternalRedirect";
3996 else if (selector == @selector(addPipelinedHost:scheme:))
3997 return @"addPipelinedHost";
3998 else if (selector == @selector(addSource:::))
3999 return @"addSource";
4000 else if (selector == @selector(addTokenHost:))
4001 return @"addTokenHost";
4002 else if (selector == @selector(addTrivialSource:))
4003 return @"addTrivialSource";
4004 else if (selector == @selector(close))
4006 else if (selector == @selector(du:))
4008 else if (selector == @selector(stringWithFormat:arguments:))
4010 else if (selector == @selector(getAllSources))
4011 return @"getAllSourcs";
4012 else if (selector == @selector(getKernelNumber:))
4013 return @"getKernelNumber";
4014 else if (selector == @selector(getKernelString:))
4015 return @"getKernelString";
4016 else if (selector == @selector(getInstalledPackages))
4017 return @"getInstalledPackages";
4018 else if (selector == @selector(getIORegistryEntry::))
4019 return @"getIORegistryEntry";
4020 else if (selector == @selector(getLocaleIdentifier))
4021 return @"getLocaleIdentifier";
4022 else if (selector == @selector(getPreferredLanguages))
4023 return @"getPreferredLanguages";
4024 else if (selector == @selector(getPackageById:))
4025 return @"getPackageById";
4026 else if (selector == @selector(getMetadataKeys))
4027 return @"getMetadataKeys";
4028 else if (selector == @selector(getMetadataValue:))
4029 return @"getMetadataValue";
4030 else if (selector == @selector(getSessionValue:))
4031 return @"getSessionValue";
4032 else if (selector == @selector(installPackages:))
4033 return @"installPackages";
4034 else if (selector == @selector(localizedStringForKey:value:table:))
4036 else if (selector == @selector(popViewController:))
4037 return @"popViewController";
4038 else if (selector == @selector(refreshSources))
4039 return @"refreshSources";
4040 else if (selector == @selector(removeButton))
4041 return @"removeButton";
4042 else if (selector == @selector(saveConfig))
4043 return @"saveConfig";
4044 else if (selector == @selector(setCydiaSource:))
4045 return @"setCydiaSource";
4046 else if (selector == @selector(setMetadataValue::))
4047 return @"setMetadataValue";
4048 else if (selector == @selector(setSessionValue::))
4049 return @"setSessionValue";
4050 else if (selector == @selector(substitutePackageNames:))
4051 return @"substitutePackageNames";
4052 else if (selector == @selector(scrollToBottom:))
4053 return @"scrollToBottom";
4054 else if (selector == @selector(setAllowsNavigationAction:))
4055 return @"setAllowsNavigationAction";
4056 else if (selector == @selector(setBadgeValue:))
4057 return @"setBadgeValue";
4058 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4059 return @"setButtonImage";
4060 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4061 return @"setButtonTitle";
4062 else if (selector == @selector(setHidesBackButton:))
4063 return @"setHidesBackButton";
4064 else if (selector == @selector(setHidesNavigationBar:))
4065 return @"setHidesNavigationBar";
4066 else if (selector == @selector(setNavigationBarStyle:))
4067 return @"setNavigationBarStyle";
4068 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4069 return @"setNavigationBarTintColor";
4070 else if (selector == @selector(setPasteboardString:))
4071 return @"setPasteboardString";
4072 else if (selector == @selector(setPasteboardURL:))
4073 return @"setPasteboardURL";
4074 else if (selector == @selector(setToken:))
4076 else if (selector == @selector(setViewportWidth:))
4077 return @"setViewportWidth";
4078 else if (selector == @selector(statfs:))
4080 else if (selector == @selector(supports:))
4082 else if (selector == @selector(unload))
4088 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4089 return [self webScriptNameForSelector:selector] == nil;
4092 - (BOOL) supports:(NSString *)feature {
4093 return [feature isEqualToString:@"window.open"];
4097 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4100 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4101 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4104 - (NSNumber *) getKernelNumber:(NSString *)name {
4105 const char *string([name UTF8String]);
4108 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4109 return (id) [NSNull null];
4111 if (size != sizeof(int))
4112 return (id) [NSNull null];
4115 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4116 return (id) [NSNull null];
4118 return [NSNumber numberWithInt:value];
4121 - (NSString *) getKernelString:(NSString *)name {
4122 const char *string([name UTF8String]);
4125 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4126 return (id) [NSNull null];
4128 char value[size + 1];
4129 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4130 return (id) [NSNull null];
4132 // XXX: just in case you request something ludicrous
4135 return [NSString stringWithCString:value];
4138 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4139 NSObject *value(CYIOGetValue([path UTF8String], entry));
4142 if ([value isKindOfClass:[NSData class]])
4143 value = CYHex((NSData *) value);
4148 - (void) _setCydiaSource:(NSString *)source {
4149 @synchronized (HostConfig_) {
4150 CydiaSource_ = source;
4151 [Metadata_ setObject:source forKey:@"CydiaSource"];
4157 - (void) setCydiaSource:(NSString *)source {
4158 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4161 - (NSString *) cydiaSource {
4162 @synchronized (HostConfig_) {
4163 return (id) CydiaSource_ ?: [NSNull null];
4167 - (NSArray *) getMetadataKeys {
4168 @synchronized (Values_) {
4169 return [Values_ allKeys];
4172 - (id) getMetadataValue:(NSString *)key {
4173 @synchronized (Values_) {
4174 return [Values_ objectForKey:key];
4177 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4178 @synchronized (Values_) {
4179 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4180 [Values_ removeObjectForKey:key];
4182 [Values_ setObject:value forKey:key];
4184 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4187 - (id) getSessionValue:(NSString *)key {
4188 @synchronized (SessionData_) {
4189 return [SessionData_ objectForKey:key];
4192 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4193 @synchronized (SessionData_) {
4194 if (value == (id) [WebUndefined undefined])
4195 [SessionData_ removeObjectForKey:key];
4197 [SessionData_ setObject:value forKey:key];
4200 - (void) addBridgedHost:(NSString *)host {
4201 @synchronized (HostConfig_) {
4202 [BridgedHosts_ addObject:host];
4205 - (void) addInsecureHost:(NSString *)host {
4206 @synchronized (HostConfig_) {
4207 [InsecureHosts_ addObject:host];
4210 - (void) addTokenHost:(NSString *)host {
4211 @synchronized (HostConfig_) {
4212 [TokenHosts_ addObject:host];
4215 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4216 @synchronized (HostConfig_) {
4217 if (scheme != (id) [WebUndefined undefined])
4218 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4220 [PipelinedHosts_ addObject:host];
4223 - (void) popViewController:(NSNumber *)value {
4224 if (value == (id) [WebUndefined undefined])
4225 value = [NSNumber numberWithBool:YES];
4226 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4229 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4230 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4232 for (NSString *section in sections)
4233 [array addObject:section];
4235 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4238 distribution, @"Distribution",
4240 nil] waitUntilDone:NO];
4243 - (void) addTrivialSource:(NSString *)href {
4244 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4247 - (void) refreshSources {
4248 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4251 - (void) saveConfig {
4252 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4255 - (NSArray *) getAllSources {
4256 return [[Database sharedInstance] sources];
4259 - (NSArray *) getInstalledPackages {
4260 Database *database([Database sharedInstance]);
4261 @synchronized (database) {
4262 NSArray *packages([database packages]);
4263 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4264 for (Package *package in packages)
4265 if (![package uninstalled])
4266 [installed addObject:package];
4270 - (Package *) getPackageById:(NSString *)id {
4271 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4275 return (Package *) [NSNull null];
4278 - (NSString *) getLocaleIdentifier {
4279 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4282 - (NSArray *) getPreferredLanguages {
4286 - (NSArray *) statfs:(NSString *)path {
4289 if (path == nil || statfs([path UTF8String], &stat) == -1)
4292 return [NSArray arrayWithObjects:
4293 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4294 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4295 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4299 - (NSNumber *) du:(NSString *)path {
4300 NSNumber *value(nil);
4303 _assert(pipe(fds) != -1);
4305 pid_t pid(ExecFork());
4307 _assert(dup2(fds[1], 1) != -1);
4308 _assert(close(fds[0]) != -1);
4309 _assert(close(fds[1]) != -1);
4310 /* XXX: this should probably not use du */
4311 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4316 _assert(close(fds[1]) != -1);
4318 if (FILE *du = fdopen(fds[0], "r")) {
4320 while (fgets(line, sizeof(line), du) != NULL) {
4321 size_t length(strlen(line));
4322 while (length != 0 && line[length - 1] == '\n')
4323 line[--length] = '\0';
4324 if (char *tab = strchr(line, '\t')) {
4326 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4331 } else _assert(close(fds[0]));
4335 if (waitpid(pid, &status, 0) == -1)
4338 else _assert(false);
4344 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4347 - (void) installPackages:(NSArray *)packages {
4348 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4351 - (NSString *) substitutePackageNames:(NSString *)message {
4352 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4353 for (size_t i(0), e([words count]); i != e; ++i) {
4354 NSString *word([words objectAtIndex:i]);
4355 if (Package *package = [[Database sharedInstance] packageWithName:word])
4356 [words replaceObjectAtIndex:i withObject:[package name]];
4359 return [words componentsJoinedByString:@" "];
4362 - (void) removeButton {
4363 [indirect_ removeButton];
4366 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4367 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4370 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4371 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4374 - (void) setBadgeValue:(id)value {
4375 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4378 - (void) setAllowsNavigationAction:(NSString *)value {
4379 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4382 - (void) setHidesBackButton:(NSString *)value {
4383 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4386 - (void) setHidesNavigationBar:(NSString *)value {
4387 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4390 - (void) setNavigationBarStyle:(NSString *)value {
4391 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4394 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4395 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4396 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4397 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4400 - (void) setPasteboardString:(NSString *)value {
4401 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4404 - (void) setPasteboardURL:(NSString *)value {
4405 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4408 - (void) _setToken:(NSString *)token {
4412 [Metadata_ removeObjectForKey:@"Token"];
4414 [Metadata_ setObject:Token_ forKey:@"Token"];
4419 - (void) setToken:(NSString *)token {
4420 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4423 - (void) scrollToBottom:(NSNumber *)animated {
4424 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4427 - (void) setViewportWidth:(float)width {
4428 [indirect_ setViewportWidthOnMainThread:width];
4431 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4432 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4433 unsigned count([arguments count]);
4435 for (unsigned i(0); i != count; ++i)
4436 values[i] = [arguments objectAtIndex:i];
4437 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4440 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4441 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4443 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4445 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4451 @interface NSURL (CydiaSecure)
4454 @implementation NSURL (CydiaSecure)
4456 - (bool) isCydiaSecure {
4457 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4460 @synchronized (HostConfig_) {
4461 if ([InsecureHosts_ containsObject:[self host]])
4470 /* Cydia Browser Controller {{{ */
4471 @implementation CydiaWebViewController
4473 - (NSURL *) navigationURL {
4474 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4477 + (void) initialize {
4478 Diversions_ = [NSMutableSet setWithCapacity:0];
4481 + (void) addDiversion:(Diversion *)diversion {
4482 [Diversions_ addObject:diversion];
4485 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4486 [super webView:view didClearWindowObject:window forFrame:frame];
4488 WebDataSource *source([frame dataSource]);
4489 NSURLResponse *response([source response]);
4490 NSURL *url([response URL]);
4491 NSString *scheme([[url scheme] lowercaseString]);
4493 bool bridged(false);
4495 @synchronized (HostConfig_) {
4496 if ([scheme isEqualToString:@"file"])
4498 else if ([scheme isEqualToString:@"https"])
4499 if ([BridgedHosts_ containsObject:[url host]])
4504 [window setValue:cydia_ forKey:@"cydia"];
4507 - (void) _setupMail:(MFMailComposeViewController *)controller {
4508 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4510 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4511 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4514 - (NSURL *) URLWithURL:(NSURL *)url {
4515 return [Diversion divertURL:url];
4518 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4519 NSURL *url([request URL]);
4520 NSString *host([url host]);
4522 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4524 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4525 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4526 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4527 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4530 @synchronized (HostConfig_) {
4531 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4534 if ([url isCydiaSecure] && token) {
4535 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4536 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4542 - (void) setDelegate:(id)delegate {
4543 [super setDelegate:delegate];
4544 [cydia_ setDelegate:delegate];
4547 - (NSString *) applicationNameForUserAgent {
4548 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4551 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4553 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4554 if (Product_ != nil)
4555 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4561 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4562 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4568 @interface AppCacheController : CydiaWebViewController {
4573 @implementation AppCacheController
4575 - (void) didReceiveMemoryWarning {
4582 @interface NSObject (CydiaScript)
4583 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4586 @implementation NSObject (CydiaScript)
4588 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4594 @implementation NSArray (CydiaScript)
4596 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4597 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4598 for (size_t i(0), e([self count]); i != e; ++i)
4599 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4605 @implementation NSDictionary (CydiaScript)
4607 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4608 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4610 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4617 /* Confirmation Controller {{{ */
4618 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4619 if (!iterator.end())
4620 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4621 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4623 pkgCache::PkgIterator package(dep.TargetPkg());
4626 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4633 @protocol ConfirmationControllerDelegate
4634 - (void) cancelAndClear:(bool)clear;
4635 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4639 @interface ConfirmationController : CydiaWebViewController {
4640 _transient Database *database_;
4642 _H<UIAlertView> essential_;
4644 _H<NSDictionary> changes_;
4645 _H<NSMutableArray> issues_;
4646 _H<NSDictionary> sizes_;
4651 - (id) initWithDatabase:(Database *)database;
4655 @implementation ConfirmationController
4659 RestartSubstrate_ = true;
4660 [delegate_ confirmWithNavigationController:[self navigationController]];
4663 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4664 NSString *context([alert context]);
4666 if ([context isEqualToString:@"remove"]) {
4667 if (button == [alert cancelButtonIndex])
4668 [self dismissModalViewControllerAnimated:YES];
4669 else if (button == [alert firstOtherButtonIndex]) {
4673 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4674 } else if ([context isEqualToString:@"unable"]) {
4675 [self dismissModalViewControllerAnimated:YES];
4676 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4678 [super alertView:alert clickedButtonAtIndex:button];
4682 - (void) _doContinue {
4683 [delegate_ cancelAndClear:NO];
4684 [self dismissModalViewControllerAnimated:YES];
4687 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4688 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4692 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4693 [super webView:view didClearWindowObject:window forFrame:frame];
4695 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4696 (id) changes_, @"changes",
4697 (id) issues_, @"issues",
4698 (id) sizes_, @"sizes",
4700 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4703 - (id) initWithDatabase:(Database *)database {
4704 if ((self = [super init]) != nil) {
4705 database_ = database;
4707 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4708 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4709 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4710 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4711 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4715 pkgCacheFile &cache([database_ cache]);
4716 NSArray *packages([database_ packages]);
4717 pkgDepCache::Policy *policy([database_ policy]);
4719 issues_ = [NSMutableArray arrayWithCapacity:4];
4721 for (Package *package in packages) {
4722 pkgCache::PkgIterator iterator([package iterator]);
4723 NSString *name([package id]);
4725 if ([package broken]) {
4726 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4728 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4730 reasons, @"reasons",
4733 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4737 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4738 pkgCache::DepIterator start;
4739 pkgCache::DepIterator end;
4740 dep.GlobOr(start, end); // ++dep
4742 if (!cache->IsImportantDep(end))
4744 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4747 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4749 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4750 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4751 clauses, @"clauses",
4755 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4757 pkgCache::PkgIterator target(start.TargetPkg());
4758 if (target->ProvidesList != 0)
4759 reason = @"missing";
4761 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4763 reason = @"installed";
4764 installed = [NSString stringWithUTF8String:ver.VerStr()];
4765 } else if (!cache[target].CandidateVerIter(cache).end())
4766 reason = @"uninstalled";
4767 else if (target->ProvidesList == 0)
4768 reason = @"uninstallable";
4770 reason = @"virtual";
4773 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4774 [NSString stringWithUTF8String:start.CompType()], @"operator",
4775 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4778 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4779 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4780 version, @"version",
4782 installed, @"installed",
4785 // yes, seriously. (wtf?)
4793 pkgDepCache::StateCache &state(cache[iterator]);
4795 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4797 if (state.NewInstall())
4798 [installs addObject:name];
4799 // XXX: else if (state.Install())
4800 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4801 [reinstalls addObject:name];
4802 // XXX: move before previous if
4803 else if (state.Upgrade())
4804 [upgrades addObject:name];
4805 else if (state.Downgrade())
4806 [downgrades addObject:name];
4807 else if (!state.Delete())
4808 // XXX: _assert(state.Keep());
4810 else if (special_r(name))
4811 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4812 [NSNull null], @"package",
4813 [NSArray arrayWithObjects:
4814 [NSDictionary dictionaryWithObjectsAndKeys:
4815 @"Conflicts", @"relationship",
4816 [NSArray arrayWithObjects:
4817 [NSDictionary dictionaryWithObjectsAndKeys:
4819 [NSNull null], @"version",
4820 @"installed", @"reason",
4827 if ([package essential])
4829 [removes addObject:name];
4832 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4833 substrate_ |= DepSubstrate(iterator.CurrentVer());
4838 else if (Advanced_) {
4839 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4841 essential_ = [[[UIAlertView alloc]
4842 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4843 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4845 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4847 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4851 [essential_ setContext:@"remove"];
4853 essential_ = [[[UIAlertView alloc]
4854 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4855 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4857 cancelButtonTitle:UCLocalize("OKAY")
4858 otherButtonTitles:nil
4861 [essential_ setContext:@"unable"];
4864 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4865 installs, @"installs",
4866 reinstalls, @"reinstalls",
4867 upgrades, @"upgrades",
4868 downgrades, @"downgrades",
4869 removes, @"removes",
4872 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4873 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4874 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4877 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4881 - (UIBarButtonItem *) leftButton {
4882 return [[[UIBarButtonItem alloc]
4883 initWithTitle:UCLocalize("CANCEL")
4884 style:UIBarButtonItemStylePlain
4886 action:@selector(cancelButtonClicked)
4891 - (void) applyRightButton {
4892 if ([issues_ count] == 0 && ![self isLoading])
4893 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4894 initWithTitle:UCLocalize("CONFIRM")
4895 style:UIBarButtonItemStyleDone
4897 action:@selector(confirmButtonClicked)
4900 [[self navigationItem] setRightBarButtonItem:nil];
4904 - (void) cancelButtonClicked {
4905 [self dismissModalViewControllerAnimated:YES];
4906 [delegate_ cancelAndClear:YES];
4910 - (void) confirmButtonClicked {
4911 if (essential_ != nil)
4921 /* Progress Data {{{ */
4922 @interface CydiaProgressData : NSObject {
4923 _transient id delegate_;
4932 _H<NSMutableArray> events_;
4933 _H<NSString> title_;
4935 _H<NSString> status_;
4936 _H<NSString> finish_;
4941 @implementation CydiaProgressData
4943 + (NSArray *) _attributeKeys {
4944 return [NSArray arrayWithObjects:
4956 - (NSArray *) attributeKeys {
4957 return [[self class] _attributeKeys];
4960 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4961 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4965 if ((self = [super init]) != nil) {
4966 events_ = [NSMutableArray arrayWithCapacity:32];
4970 - (void) setDelegate:(id)delegate {
4971 delegate_ = delegate;
4974 - (void) setPercent:(float)value {
4978 - (NSNumber *) percent {
4979 return [NSNumber numberWithFloat:percent_];
4982 - (void) setCurrent:(float)value {
4986 - (NSNumber *) current {
4987 return [NSNumber numberWithFloat:current_];
4990 - (void) setTotal:(float)value {
4994 - (NSNumber *) total {
4995 return [NSNumber numberWithFloat:total_];
4998 - (void) setSpeed:(float)value {
5002 - (NSNumber *) speed {
5003 return [NSNumber numberWithFloat:speed_];
5006 - (NSArray *) events {
5010 - (void) removeAllEvents {
5011 [events_ removeAllObjects];
5014 - (void) addEvent:(CydiaProgressEvent *)event {
5015 [events_ addObject:event];
5018 - (void) setTitle:(NSString *)text {
5022 - (NSString *) title {
5026 - (void) setFinish:(NSString *)text {
5030 - (NSString *) finish {
5031 return (id) finish_ ?: [NSNull null];
5034 - (void) setRunning:(bool)running {
5038 - (NSNumber *) running {
5039 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5044 /* Progress Controller {{{ */
5045 @interface ProgressController : CydiaWebViewController <
5048 _transient Database *database_;
5049 _H<CydiaProgressData, 1> progress_;
5053 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5055 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5057 - (void) setTitle:(NSString *)title;
5058 - (void) setCancellable:(bool)cancellable;
5062 @implementation ProgressController
5065 [database_ setProgressDelegate:nil];
5069 - (UIBarButtonItem *) leftButton {
5070 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5071 initWithTitle:UCLocalize("CANCEL")
5072 style:UIBarButtonItemStylePlain
5074 action:@selector(cancel)
5075 ] autorelease] : nil;
5078 - (void) updateCancel {
5079 [super applyLeftButton];
5082 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5083 if ((self = [super init]) != nil) {
5084 database_ = database;
5085 delegate_ = delegate;
5087 [database_ setProgressDelegate:self];
5089 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5090 [progress_ setDelegate:self];
5092 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5094 [scroller_ setBackgroundColor:[UIColor blackColor]];
5096 [[self navigationItem] setHidesBackButton:YES];
5098 [self updateCancel];
5102 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5103 [super webView:view didClearWindowObject:window forFrame:frame];
5104 [window setValue:progress_ forKey:@"cydiaProgress"];
5107 - (void) updateProgress {
5108 [self dispatchEvent:@"CydiaProgressUpdate"];
5111 - (void) viewWillAppear:(BOOL)animated {
5112 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5113 [super viewWillAppear:animated];
5117 UpdateExternalStatus(0);
5120 [delegate_ saveState];
5124 [delegate_ returnToCydia];
5128 [delegate_ terminateWithSuccess];
5129 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5130 [delegate_ suspendWithAnimation:YES];
5132 [delegate_ suspend];*/
5144 system("/usr/bin/sbreload");
5150 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5151 SBReboot(SBSSpringBoardServerPort());
5153 reboot2(RB_AUTOBOOT);
5160 - (void) setTitle:(NSString *)title {
5161 [progress_ setTitle:title];
5162 [self updateProgress];
5165 - (UIBarButtonItem *) rightButton {
5166 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5167 initWithTitle:UCLocalize("CLOSE")
5168 style:UIBarButtonItemStylePlain
5170 action:@selector(close)
5174 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5175 UpdateExternalStatus(1);
5177 [progress_ setRunning:true];
5178 [self setTitle:title];
5179 // implicit updateProgress
5181 SHA1SumValue notifyconf; {
5183 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5186 MMap mmap(file, MMap::ReadOnly);
5188 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5189 notifyconf = sha1.Result();
5193 SHA1SumValue springlist; {
5195 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5198 MMap mmap(file, MMap::ReadOnly);
5200 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5201 springlist = sha1.Result();
5205 if (invocation != nil) {
5206 [invocation yieldToSelector:@selector(invoke)];
5207 [self setTitle:@"COMPLETE"];
5212 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5215 MMap mmap(file, MMap::ReadOnly);
5217 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5218 if (!(notifyconf == sha1.Result()))
5225 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5228 MMap mmap(file, MMap::ReadOnly);
5230 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5231 if (!(springlist == sha1.Result()))
5237 if (RestartSubstrate_)
5241 RestartSubstrate_ = false;
5244 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5245 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5246 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5247 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5248 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5252 system("su -c /usr/bin/uicache mobile");
5255 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5257 [progress_ setRunning:false];
5258 [self updateProgress];
5260 [self applyRightButton];
5263 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5264 [progress_ addEvent:event];
5265 [self updateProgress];
5268 - (bool) isProgressCancelled {
5269 return cancel_ == 2;
5274 [self updateCancel];
5277 - (void) setCancellable:(bool)cancellable {
5278 unsigned cancel(cancel_);
5282 else if (cancel_ == 0)
5285 if (cancel != cancel_)
5286 [self updateCancel];
5289 - (void) setProgressCancellable:(NSNumber *)cancellable {
5290 [self setCancellable:[cancellable boolValue]];
5293 - (void) setProgressPercent:(NSNumber *)percent {
5294 [progress_ setPercent:[percent floatValue]];
5295 [self updateProgress];
5298 - (void) setProgressStatus:(NSDictionary *)status {
5299 if (status == nil) {
5300 [progress_ setCurrent:0];
5301 [progress_ setTotal:0];
5302 [progress_ setSpeed:0];
5304 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5306 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5307 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5308 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5311 [self updateProgress];
5317 /* Package Cell {{{ */
5318 @interface PackageCell : CyteTableViewCell <
5319 CyteTableViewCellDelegate
5323 _H<NSString> description_;
5325 _H<NSString> source_;
5327 _H<UIImage> placard_;
5331 - (PackageCell *) init;
5332 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5334 - (void) drawContentRect:(CGRect)rect;
5338 @implementation PackageCell
5340 - (PackageCell *) init {
5341 CGRect frame(CGRectMake(0, 0, 320, 74));
5342 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5343 UIView *content([self contentView]);
5344 CGRect bounds([content bounds]);
5346 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5347 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5348 [content addSubview:content_];
5350 [content_ setDelegate:self];
5351 [content_ setOpaque:YES];
5355 - (NSString *) accessibilityLabel {
5356 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5359 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5360 summarized_ = summary;
5371 Source *source = [package source];
5373 icon_ = [package icon];
5375 if (NSString *name = [package name])
5376 name_ = [NSString stringWithString:name];
5378 NSString *description(nil);
5380 if (description == nil && IsWildcat_)
5381 description = [package longDescription];
5382 if (description == nil)
5383 description = [package shortDescription];
5385 if (description != nil)
5386 description_ = [NSString stringWithString:description];
5388 commercial_ = [package isCommercial];
5390 NSString *label = nil;
5391 bool trusted = false;
5393 if (source != nil) {
5394 label = [source label];
5395 trusted = [source trusted];
5396 } else if ([[package id] isEqualToString:@"firmware"])
5397 label = UCLocalize("APPLE");
5399 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5401 NSString *from(label);
5403 NSString *section = [package simpleSection];
5404 if (section != nil && ![section isEqualToString:label]) {
5405 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5406 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5409 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5411 if (NSString *purpose = [package primaryPurpose])
5412 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5417 if (NSString *mode = [package mode]) {
5418 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5419 color = RemovingColor_;
5420 //placard = @"removing";
5422 color = InstallingColor_;
5423 //placard = @"installing";
5426 // XXX: the removing/installing placards are not @2x
5429 color = [UIColor whiteColor];
5431 if ([package installed] != nil)
5432 placard = @"installed";
5437 [content_ setBackgroundColor:color];
5440 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5442 [self setNeedsDisplay];
5443 [content_ setNeedsDisplay];
5446 - (void) drawSummaryContentRect:(CGRect)rect {
5447 bool highlighted(highlighted_);
5448 float width([self bounds].size.width);
5452 rect.size = [(UIImage *) icon_ size];
5454 rect.size.width /= 4;
5455 rect.size.height /= 4;
5457 rect.origin.x = 14 - rect.size.width / 4;
5458 rect.origin.y = 14 - rect.size.height / 4;
5460 [icon_ drawInRect:rect];
5463 if (badge_ != nil) {
5465 rect.size = [(UIImage *) badge_ size];
5467 rect.size.width /= 4;
5468 rect.size.height /= 4;
5470 rect.origin.x = 20 - rect.size.width / 4;
5471 rect.origin.y = 20 - rect.size.height / 4;
5473 [badge_ drawInRect:rect];
5480 UISetColor(commercial_ ? Purple_ : Black_);
5481 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5483 if (placard_ != nil)
5484 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5487 - (void) drawNormalContentRect:(CGRect)rect {
5488 bool highlighted(highlighted_);
5489 float width([self bounds].size.width);
5493 rect.size = [(UIImage *) icon_ size];
5495 rect.size.width /= 2;
5496 rect.size.height /= 2;
5498 rect.origin.x = 25 - rect.size.width / 2;
5499 rect.origin.y = 25 - rect.size.height / 2;
5501 [icon_ drawInRect:rect];
5504 if (badge_ != nil) {
5506 rect.size = [(UIImage *) badge_ size];
5508 rect.size.width /= 2;
5509 rect.size.height /= 2;
5511 rect.origin.x = 36 - rect.size.width / 2;
5512 rect.origin.y = 36 - rect.size.height / 2;
5514 [badge_ drawInRect:rect];
5521 UISetColor(commercial_ ? Purple_ : Black_);
5522 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5523 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5526 UISetColor(commercial_ ? Purplish_ : Gray_);
5527 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5529 if (placard_ != nil)
5530 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5533 - (void) drawContentRect:(CGRect)rect {
5535 [self drawSummaryContentRect:rect];
5537 [self drawNormalContentRect:rect];
5542 /* Section Cell {{{ */
5543 @interface SectionCell : CyteTableViewCell <
5544 CyteTableViewCellDelegate
5546 _H<NSString> basic_;
5547 _H<NSString> section_;
5549 _H<NSString> count_;
5551 _H<UISwitch> switch_;
5555 - (void) setSection:(Section *)section editing:(BOOL)editing;
5559 @implementation SectionCell
5561 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5562 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5563 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5564 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5565 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5567 UIView *content([self contentView]);
5568 CGRect bounds([content bounds]);
5570 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5571 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5572 [content addSubview:content_];
5573 [content_ setBackgroundColor:[UIColor whiteColor]];
5575 [content_ setDelegate:self];
5579 - (void) onSwitch:(id)sender {
5580 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5581 if (metadata == nil) {
5582 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5583 [Sections_ setObject:metadata forKey:basic_];
5586 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5590 - (void) setSection:(Section *)section editing:(BOOL)editing {
5591 if (editing != editing_) {
5593 [switch_ removeFromSuperview];
5595 [self addSubview:switch_];
5604 if (section == nil) {
5605 name_ = UCLocalize("ALL_PACKAGES");
5608 basic_ = [section name];
5609 section_ = [section localized];
5611 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5612 count_ = [NSString stringWithFormat:@"%d", [section count]];
5615 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5618 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5619 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5621 [content_ setNeedsDisplay];
5624 - (void) setFrame:(CGRect)frame {
5625 [super setFrame:frame];
5627 CGRect rect([switch_ frame]);
5628 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5631 - (NSString *) accessibilityLabel {
5635 - (void) drawContentRect:(CGRect)rect {
5636 bool highlighted(highlighted_ && !editing_);
5638 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5643 float width(rect.size.width);
5649 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5651 CGSize size = [count_ sizeWithFont:Font14_];
5655 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5661 /* File Table {{{ */
5662 @interface FileTable : CyteViewController <
5663 UITableViewDataSource,
5666 _transient Database *database_;
5667 _H<Package> package_;
5669 _H<NSMutableArray> files_;
5670 _H<UITableView, 2> list_;
5673 - (id) initWithDatabase:(Database *)database;
5674 - (void) setPackage:(Package *)package;
5678 @implementation FileTable
5680 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5681 return files_ == nil ? 0 : [files_ count];
5684 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5688 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5689 static NSString *reuseIdentifier = @"Cell";
5691 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5693 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5694 [cell setFont:[UIFont systemFontOfSize:16]];
5696 [cell setText:[files_ objectAtIndex:indexPath.row]];
5697 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5702 - (NSURL *) navigationURL {
5703 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5707 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5709 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5710 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5711 [list_ setRowHeight:24.0f];
5712 [(UITableView *) list_ setDataSource:self];
5713 [list_ setDelegate:self];
5714 [[self view] addSubview:list_];
5717 - (void) viewDidLoad {
5718 [super viewDidLoad];
5720 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5723 - (void) releaseSubviews {
5726 [super releaseSubviews];
5729 - (id) initWithDatabase:(Database *)database {
5730 if ((self = [super init]) != nil) {
5731 database_ = database;
5733 files_ = [NSMutableArray arrayWithCapacity:32];
5737 - (void) setPackage:(Package *)package {
5741 [files_ removeAllObjects];
5743 if (package != nil) {
5745 name_ = [package id];
5747 if (NSArray *files = [package files])
5748 [files_ addObjectsFromArray:files];
5750 if ([files_ count] != 0) {
5751 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5752 [files_ removeObjectAtIndex:0];
5753 [files_ sortUsingSelector:@selector(compareByPath:)];
5755 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5756 [stack addObject:@"/"];
5758 for (int i(0), e([files_ count]); i != e; ++i) {
5759 NSString *file = [files_ objectAtIndex:i];
5760 while (![file hasPrefix:[stack lastObject]])
5761 [stack removeLastObject];
5762 NSString *directory = [stack lastObject];
5763 [stack addObject:[file stringByAppendingString:@"/"]];
5764 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5765 ([stack count] - 2) * 3, "",
5766 [file substringFromIndex:[directory length]]
5775 - (void) reloadData {
5778 [self setPackage:[database_ packageWithName:name_]];
5783 /* Package Controller {{{ */
5784 @interface CYPackageController : CydiaWebViewController <
5785 UIActionSheetDelegate
5787 _transient Database *database_;
5788 _H<Package> package_;
5791 _H<NSMutableArray> buttons_;
5792 _H<UIBarButtonItem> button_;
5795 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5799 @implementation CYPackageController
5801 - (NSURL *) navigationURL {
5802 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5805 /* XXX: this is not safe at all... localization of /fail/ */
5806 - (void) _clickButtonWithName:(NSString *)name {
5807 if ([name isEqualToString:UCLocalize("CLEAR")])
5808 [delegate_ clearPackage:package_];
5809 else if ([name isEqualToString:UCLocalize("INSTALL")])
5810 [delegate_ installPackage:package_];
5811 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5812 [delegate_ installPackage:package_];
5813 else if ([name isEqualToString:UCLocalize("REMOVE")])
5814 [delegate_ removePackage:package_];
5815 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5816 [delegate_ installPackage:package_];
5817 else _assert(false);
5820 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5821 NSString *context([sheet context]);
5823 if ([context isEqualToString:@"modify"]) {
5824 if (button != [sheet cancelButtonIndex]) {
5825 NSString *buttonName = [buttons_ objectAtIndex:button];
5826 [self _clickButtonWithName:buttonName];
5829 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5833 - (bool) _allowJavaScriptPanel {
5838 - (void) _customButtonClicked {
5839 int count([buttons_ count]);
5844 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5846 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5847 [buttons addObjectsFromArray:buttons_];
5849 UIActionSheet *sheet = [[[UIActionSheet alloc]
5852 cancelButtonTitle:nil
5853 destructiveButtonTitle:nil
5854 otherButtonTitles:nil
5857 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5859 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5860 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5862 [sheet setContext:@"modify"];
5864 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5868 // We don't want to allow non-commercial packages to do custom things to the install button,
5869 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5870 - (void) customButtonClicked {
5872 [super customButtonClicked];
5874 [self _customButtonClicked];
5877 - (void) reloadButtonClicked {
5878 // Don't reload a commerical package by tapping the loading button,
5879 // but if it's not an Install button, we should forward it on.
5880 if (![package_ uninstalled])
5881 [self _customButtonClicked];
5884 - (void) applyLoadingTitle {
5885 // Don't show "Loading" as the title. Ever.
5888 - (UIBarButtonItem *) rightButton {
5893 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5894 if ((self = [super init]) != nil) {
5895 database_ = database;
5896 buttons_ = [NSMutableArray arrayWithCapacity:4];
5897 name_ = [NSString stringWithString:name];
5898 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5902 - (void) reloadData {
5905 package_ = [database_ packageWithName:name_];
5907 [buttons_ removeAllObjects];
5909 if (package_ != nil) {
5910 [(Package *) package_ parse];
5912 commercial_ = [package_ isCommercial];
5914 if ([package_ mode] != nil)
5915 [buttons_ addObject:UCLocalize("CLEAR")];
5916 if ([package_ source] == nil);
5917 else if ([package_ upgradableAndEssential:NO])
5918 [buttons_ addObject:UCLocalize("UPGRADE")];
5919 else if ([package_ uninstalled])
5920 [buttons_ addObject:UCLocalize("INSTALL")];
5922 [buttons_ addObject:UCLocalize("REINSTALL")];
5923 if (![package_ uninstalled])
5924 [buttons_ addObject:UCLocalize("REMOVE")];
5928 switch ([buttons_ count]) {
5929 case 0: title = nil; break;
5930 case 1: title = [buttons_ objectAtIndex:0]; break;
5931 default: title = UCLocalize("MODIFY"); break;
5934 button_ = [[[UIBarButtonItem alloc]
5936 style:UIBarButtonItemStylePlain
5938 action:@selector(customButtonClicked)
5942 - (bool) isLoading {
5943 return commercial_ ? [super isLoading] : false;
5949 /* Package List Controller {{{ */
5950 @interface PackageListController : CyteViewController <
5951 UITableViewDataSource,
5954 _transient Database *database_;
5956 _H<NSArray> packages_;
5957 _H<NSMutableArray> sections_;
5958 _H<UITableView, 2> list_;
5959 _H<NSMutableArray> index_;
5960 _H<NSMutableDictionary> indices_;
5961 _H<NSString> title_;
5962 unsigned reloading_;
5965 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5966 - (void) setDelegate:(id)delegate;
5967 - (void) resetCursor;
5972 @implementation PackageListController
5974 - (bool) isSummarized {
5978 - (bool) showsSections {
5982 - (void) deselectWithAnimation:(BOOL)animated {
5983 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5986 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5987 CGRect base = [[self view] bounds];
5988 base.size.height -= bounds.size.height;
5989 base.origin = [list_ frame].origin;
5991 [UIView beginAnimations:nil context:NULL];
5992 [UIView setAnimationBeginsFromCurrentState:YES];
5993 [UIView setAnimationCurve:curve];
5994 [UIView setAnimationDuration:duration];
5995 [list_ setFrame:base];
5996 [UIView commitAnimations];
5999 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6000 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6003 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6004 [self resizeForKeyboardBounds:bounds duration:0];
6007 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6008 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6009 *curve = UIViewAnimationCurveEaseInOut;
6011 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6013 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6016 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6019 - (void) keyboardWillShow:(NSNotification *)notification {
6022 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6023 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6025 NSTimeInterval duration;
6026 UIViewAnimationCurve curve;
6027 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6029 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);
6030 UIViewController *base = self;
6031 while ([base parentViewController] != nil)
6032 base = [base parentViewController];
6033 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6034 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6036 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6037 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6039 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6042 - (void) keyboardWillHide:(NSNotification *)notification {
6043 NSTimeInterval duration;
6044 UIViewAnimationCurve curve;
6045 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6047 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6050 - (void) viewWillAppear:(BOOL)animated {
6051 [super viewWillAppear:animated];
6053 [self resizeForKeyboardBounds:CGRectZero];
6054 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6055 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6058 - (void) viewWillDisappear:(BOOL)animated {
6059 [super viewWillDisappear:animated];
6061 [self resizeForKeyboardBounds:CGRectZero];
6062 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6063 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6066 - (void) viewDidAppear:(BOOL)animated {
6067 [super viewDidAppear:animated];
6068 [self deselectWithAnimation:animated];
6071 - (void) didSelectPackage:(Package *)package {
6072 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6073 [view setDelegate:delegate_];
6074 [[self navigationController] pushViewController:view animated:YES];
6077 #if TryIndexedCollation
6078 + (BOOL) hasIndexedCollation {
6079 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6083 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6084 NSInteger count([sections_ count]);
6085 return count == 0 ? 1 : count;
6088 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6089 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6091 return [[sections_ objectAtIndex:section] name];
6094 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6095 if ([sections_ count] == 0)
6097 return [[sections_ objectAtIndex:section] count];
6100 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6101 @synchronized (database_) {
6102 if ([database_ era] != era_)
6105 Section *section([sections_ objectAtIndex:[path section]]);
6106 NSInteger row([path row]);
6107 Package *package([packages_ objectAtIndex:([section row] + row)]);
6108 return [[package retain] autorelease];
6111 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6112 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6114 cell = [[[PackageCell alloc] init] autorelease];
6116 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6117 [cell setPackage:package asSummary:[self isSummarized]];
6121 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6122 Package *package([self packageAtIndexPath:path]);
6123 package = [database_ packageWithName:[package id]];
6124 [self didSelectPackage:package];
6127 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6128 if (![self showsSections])
6134 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6135 #if TryIndexedCollation
6136 if ([[self class] hasIndexedCollation]) {
6137 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6144 - (void) updateHeight {
6145 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6148 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6149 if ((self = [super init]) != nil) {
6150 database_ = database;
6151 title_ = [title copy];
6152 [[self navigationItem] setTitle:title_];
6154 #if TryIndexedCollation
6155 if ([[self class] hasIndexedCollation])
6156 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6159 index_ = [NSMutableArray arrayWithCapacity:32];
6161 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6163 packages_ = [NSArray array];
6164 sections_ = [NSMutableArray arrayWithCapacity:16];
6169 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6171 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6172 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6173 [[self view] addSubview:list_];
6175 // XXX: is 20 the most optimal number here?
6176 [list_ setSectionIndexMinimumDisplayRowCount:20];
6178 [(UITableView *) list_ setDataSource:self];
6179 [list_ setDelegate:self];
6181 [self updateHeight];
6184 - (void) releaseSubviews {
6187 [super releaseSubviews];
6190 - (void) setDelegate:(id)delegate {
6191 delegate_ = delegate;
6194 - (bool) shouldYield {
6198 - (bool) shouldBlock {
6202 - (NSMutableArray *) _reloadPackages {
6203 @synchronized (database_) {
6204 era_ = [database_ era];
6205 NSArray *packages([database_ packages]);
6207 return [NSMutableArray arrayWithArray:packages];
6210 - (void) _reloadData {
6211 if (reloading_ != 0) {
6218 if ([self shouldYield]) {
6222 if (![self shouldBlock])
6225 hud = [delegate_ addProgressHUD];
6226 [hud setText:UCLocalize("LOADING")];
6230 packages = [self yieldToSelector:@selector(_reloadPackages)];
6233 [delegate_ removeProgressHUD:hud];
6234 } while (reloading_ == 2);
6238 packages = [self _reloadPackages];
6241 packages_ = packages;
6243 [indices_ removeAllObjects];
6244 [sections_ removeAllObjects];
6246 Section *section = nil;
6248 #if TryIndexedCollation
6249 if ([[self class] hasIndexedCollation]) {
6250 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6251 NSArray *titles = [collation sectionIndexTitles];
6254 _profile(PackageTable$reloadData$Section)
6255 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6259 _profile(PackageTable$reloadData$Section$Package)
6260 package = [packages_ objectAtIndex:offset];
6261 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6264 while (secidx < index) {
6267 _profile(PackageTable$reloadData$Section$Allocate)
6268 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6271 _profile(PackageTable$reloadData$Section$Add)
6272 [sections_ addObject:section];
6276 [section addToCount];
6282 [index_ removeAllObjects];
6284 bool sectioned([self showsSections]);
6286 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6287 [sections_ addObject:section];
6290 _profile(PackageTable$reloadData$Section)
6291 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6295 _profile(PackageTable$reloadData$Section$Package)
6296 package = [packages_ objectAtIndex:offset];
6297 index = [package index];
6300 if (sectioned && (section == nil || [section index] != index)) {
6301 _profile(PackageTable$reloadData$Section$Allocate)
6302 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6305 [index_ addObject:[section name]];
6306 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6308 _profile(PackageTable$reloadData$Section$Add)
6309 [sections_ addObject:section];
6313 [section addToCount];
6318 [self updateHeight];
6320 _profile(PackageTable$reloadData$List)
6321 [(UITableView *) list_ setDataSource:self];
6326 - (void) reloadData {
6328 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6331 - (void) resetCursor {
6332 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6335 - (void) clearData {
6336 [self updateHeight];
6338 [list_ setDataSource:nil];
6346 /* Filtered Package List Controller {{{ */
6347 @interface FilteredPackageListController : PackageListController {
6350 _H<NSObject> object_;
6353 - (void) setObject:(id)object;
6354 - (void) setObject:(id)object forFilter:(SEL)filter;
6357 - (void) setFilter:(SEL)filter;
6359 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6363 @implementation FilteredPackageListController
6369 - (void) setFilter:(SEL)filter {
6370 @synchronized (self) {
6373 /* XXX: this is an unsafe optimization of doomy hell */
6374 Method method(class_getInstanceMethod([Package class], filter));
6375 _assert(method != NULL);
6376 imp_ = method_getImplementation(method);
6377 _assert(imp_ != NULL);
6380 - (void) setObject:(id)object {
6381 @synchronized (self) {
6385 - (void) setObject:(id)object forFilter:(SEL)filter {
6386 @synchronized (self) {
6387 [self setFilter:filter];
6388 [self setObject:object];
6391 - (NSMutableArray *) _reloadPackages {
6392 @synchronized (database_) {
6393 era_ = [database_ era];
6394 NSArray *packages([database_ packages]);
6396 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6400 _H<NSObject> object;
6402 @synchronized (self) {
6408 _profile(PackageTable$reloadData$Filter)
6409 for (Package *package in packages)
6410 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6411 [filtered addObject:package];
6417 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6418 if ((self = [super initWithDatabase:database title:title]) != nil) {
6419 [self setFilter:filter];
6420 [self setObject:object];
6427 /* Home Controller {{{ */
6428 @interface HomeController : CydiaWebViewController {
6433 @implementation HomeController
6436 if ((self = [super init]) != nil) {
6437 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6442 - (NSURL *) navigationURL {
6443 return [NSURL URLWithString:@"cydia://home"];
6446 - (void) didReceiveMemoryWarning {
6449 - (void) aboutButtonClicked {
6450 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6452 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6453 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6454 [alert setCancelButtonIndex:0];
6457 @"Copyright \u00a9 2008-2011\n"
6460 "Jay Freeman (saurik)\n"
6461 "saurik@saurik.com\n"
6462 "http://www.saurik.com/"
6468 - (UIBarButtonItem *) leftButton {
6469 return [[[UIBarButtonItem alloc]
6470 initWithTitle:UCLocalize("ABOUT")
6471 style:UIBarButtonItemStylePlain
6473 action:@selector(aboutButtonClicked)
6479 /* Manage Controller {{{ */
6480 @interface ManageController : CydiaWebViewController {
6483 - (void) queueStatusDidChange;
6487 @implementation ManageController
6490 if ((self = [super init]) != nil) {
6491 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6495 - (NSURL *) navigationURL {
6496 return [NSURL URLWithString:@"cydia://manage"];
6499 - (UIBarButtonItem *) leftButton {
6500 return [[[UIBarButtonItem alloc]
6501 initWithTitle:UCLocalize("SETTINGS")
6502 style:UIBarButtonItemStylePlain
6504 action:@selector(settingsButtonClicked)
6508 - (void) settingsButtonClicked {
6509 [delegate_ showSettings];
6512 - (void) queueButtonClicked {
6516 - (UIBarButtonItem *) customButton {
6517 return Queuing_ ? [[[UIBarButtonItem alloc]
6518 initWithTitle:UCLocalize("QUEUE")
6519 style:UIBarButtonItemStyleDone
6521 action:@selector(queueButtonClicked)
6522 ] autorelease] : [super customButton];
6525 - (void) queueStatusDidChange {
6526 [self applyRightButton];
6529 - (bool) isLoading {
6530 return !Queuing_ && [super isLoading];
6536 /* Refresh Bar {{{ */
6537 @interface RefreshBar : UINavigationBar {
6538 _H<UIProgressIndicator> indicator_;
6539 _H<UITextLabel> prompt_;
6540 _H<UIProgressBar> progress_;
6541 _H<UINavigationButton> cancel_;
6546 @implementation RefreshBar
6548 - (void) positionViews {
6549 CGRect frame = [cancel_ frame];
6550 frame.size = [cancel_ sizeThatFits:frame.size];
6551 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6552 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6553 [cancel_ setFrame:frame];
6555 CGSize prgsize = {75, 100};
6557 [self frame].size.width - prgsize.width - 10,
6558 ([self frame].size.height - prgsize.height) / 2
6560 [progress_ setFrame:prgrect];
6562 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6563 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6564 CGRect indrect = {{indoffset, indoffset}, indsize};
6565 [indicator_ setFrame:indrect];
6567 CGSize prmsize = {215, indsize.height + 4};
6569 indoffset * 2 + indsize.width,
6570 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6572 [prompt_ setFrame:prmrect];
6575 - (void) setFrame:(CGRect)frame {
6576 [super setFrame:frame];
6577 [self positionViews];
6580 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6581 if ((self = [super initWithFrame:frame]) != nil) {
6582 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6584 [self setBarStyle:UIBarStyleBlack];
6586 UIBarStyle barstyle([self _barStyle:NO]);
6587 bool ugly(barstyle == UIBarStyleDefault);
6589 UIProgressIndicatorStyle style = ugly ?
6590 UIProgressIndicatorStyleMediumBrown :
6591 UIProgressIndicatorStyleMediumWhite;
6593 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6594 [(UIProgressIndicator *) indicator_ setStyle:style];
6595 [indicator_ startAnimation];
6596 [self addSubview:indicator_];
6598 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6599 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6600 [prompt_ setBackgroundColor:[UIColor clearColor]];
6601 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6602 [self addSubview:prompt_];
6604 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6605 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6606 [(UIProgressBar *) progress_ setStyle:0];
6607 [self addSubview:progress_];
6609 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6610 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6611 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6612 [cancel_ setBarStyle:barstyle];
6614 [self positionViews];
6618 - (void) setCancellable:(bool)cancellable {
6620 [self addSubview:cancel_];
6622 [cancel_ removeFromSuperview];
6626 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6627 [progress_ setProgress:0];
6631 [self setCancellable:NO];
6634 - (void) setPrompt:(NSString *)prompt {
6635 [prompt_ setText:prompt];
6638 - (void) setProgress:(float)progress {
6639 [progress_ setProgress:progress];
6645 /* Cydia Navigation Controller Interface {{{ */
6646 @interface UINavigationController (Cydia)
6648 - (NSArray *) navigationURLCollection;
6649 - (void) unloadData;
6654 /* Cydia Tab Bar Controller {{{ */
6655 @interface CYTabBarController : UITabBarController <
6656 UITabBarControllerDelegate,
6659 _transient Database *database_;
6660 _H<RefreshBar, 1> refreshbar_;
6664 // XXX: ok, "updatedelegate_"?...
6665 _transient NSObject<CydiaDelegate> *updatedelegate_;
6667 _H<UIViewController> remembered_;
6668 _transient UIViewController *transient_;
6671 - (NSArray *) navigationURLCollection;
6672 - (void) dropBar:(BOOL)animated;
6673 - (void) beginUpdate;
6674 - (void) raiseBar:(BOOL)animated;
6676 - (void) unloadData;
6680 @implementation CYTabBarController
6682 - (void) setUnselectedViewController:(UIViewController *)transient {
6683 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6684 if (transient != nil) {
6685 if (transient_ == nil)
6686 remembered_ = [controllers objectAtIndex:0];
6687 transient_ = transient;
6688 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6689 [controllers replaceObjectAtIndex:0 withObject:transient_];
6690 [self setSelectedIndex:0];
6691 [self setViewControllers:controllers];
6692 [self concealTabBarSelection];
6693 } else if (remembered_ != nil) {
6694 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6695 transient_ = transient;
6696 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6698 [self setViewControllers:controllers];
6699 [self revealTabBarSelection];
6703 - (UIViewController *) unselectedViewController {
6707 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6708 if ([self unselectedViewController])
6709 [self setUnselectedViewController:nil];
6712 - (NSArray *) navigationURLCollection {
6713 NSMutableArray *items([NSMutableArray array]);
6715 // XXX: Should this deal with transient view controllers?
6716 for (id navigation in [self viewControllers]) {
6717 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6719 [items addObject:stack];
6725 - (void) unloadData {
6728 for (UINavigationController *controller in [self viewControllers])
6729 [controller unloadData];
6731 if (UIViewController *selected = [self selectedViewController])
6732 [selected reloadData];
6734 if (UIViewController *unselected = [self unselectedViewController]) {
6735 [unselected unloadData];
6736 [unselected reloadData];
6741 [[NSNotificationCenter defaultCenter] removeObserver:self];
6746 - (id) initWithDatabase:(Database *)database {
6747 if ((self = [super init]) != nil) {
6748 database_ = database;
6749 [self setDelegate:self];
6751 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6752 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6754 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6758 - (void) setUpdate:(NSDate *)date {
6762 - (void) beginUpdate {
6763 [(RefreshBar *) refreshbar_ start];
6766 [updatedelegate_ retainNetworkActivityIndicator];
6770 detachNewThreadSelector:@selector(performUpdate)
6776 - (void) performUpdate {
6777 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6780 status.setDelegate(self);
6781 [database_ updateWithStatus:status];
6784 performSelectorOnMainThread:@selector(completeUpdate)
6792 - (void) stopUpdateWithSelector:(SEL)selector {
6794 [updatedelegate_ releaseNetworkActivityIndicator];
6796 [self raiseBar:YES];
6799 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6802 - (void) completeUpdate {
6805 [self stopUpdateWithSelector:@selector(reloadData)];
6808 - (void) cancelUpdate {
6809 [self stopUpdateWithSelector:@selector(updateData)];
6812 - (void) cancelPressed {
6813 [self cancelUpdate];
6820 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6821 [refreshbar_ setPrompt:[event compoundMessage]];
6824 - (bool) isProgressCancelled {
6828 - (void) setProgressCancellable:(NSNumber *)cancellable {
6829 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6832 - (void) setProgressPercent:(NSNumber *)percent {
6833 [refreshbar_ setProgress:[percent floatValue]];
6836 - (void) setProgressStatus:(NSDictionary *)status {
6838 [self setProgressPercent:[status objectForKey:@"Percent"]];
6841 - (void) setUpdateDelegate:(id)delegate {
6842 updatedelegate_ = delegate;
6845 - (UIView *) transitionView {
6846 if ([self respondsToSelector:@selector(_transitionView)])
6847 return [self _transitionView];
6849 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6852 - (void) dropBar:(BOOL)animated {
6857 UIView *transition([self transitionView]);
6858 [[self view] addSubview:refreshbar_];
6860 CGRect barframe([refreshbar_ frame]);
6862 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6863 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6865 barframe.origin.y = 0;
6867 [refreshbar_ setFrame:barframe];
6870 [UIView beginAnimations:nil context:NULL];
6872 CGRect viewframe = [transition frame];
6873 viewframe.origin.y += barframe.size.height;
6874 viewframe.size.height -= barframe.size.height;
6875 [transition setFrame:viewframe];
6878 [UIView commitAnimations];
6880 // Ensure bar has the proper width for our view, it might have changed
6881 barframe.size.width = viewframe.size.width;
6882 [refreshbar_ setFrame:barframe];
6885 - (void) raiseBar:(BOOL)animated {
6890 UIView *transition([self transitionView]);
6891 [refreshbar_ removeFromSuperview];
6893 CGRect barframe([refreshbar_ frame]);
6896 [UIView beginAnimations:nil context:NULL];
6898 CGRect viewframe = [transition frame];
6899 viewframe.origin.y -= barframe.size.height;
6900 viewframe.size.height += barframe.size.height;
6901 [transition setFrame:viewframe];
6904 [UIView commitAnimations];
6907 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6908 bool dropped(dropped_);
6913 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6919 - (void) statusBarFrameChanged:(NSNotification *)notification {
6929 /* Cydia Navigation Controller Implementation {{{ */
6930 @implementation UINavigationController (Cydia)
6932 - (NSArray *) navigationURLCollection {
6933 NSMutableArray *stack([NSMutableArray array]);
6935 for (CyteViewController *controller in [self viewControllers]) {
6936 NSString *url = [[controller navigationURL] absoluteString];
6938 [stack addObject:url];
6944 - (void) reloadData {
6947 UIViewController *visible([self visibleViewController]);
6949 [visible reloadData];
6951 // on the iPad, this view controller is ALSO visible. :(
6953 if (UIViewController *top = [self topViewController])
6958 - (void) unloadData {
6959 for (CyteViewController *page in [self viewControllers])
6968 /* Cydia:// Protocol {{{ */
6969 @interface CydiaURLProtocol : NSURLProtocol {
6974 @implementation CydiaURLProtocol
6976 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6977 NSURL *url([request URL]);
6981 NSString *scheme([[url scheme] lowercaseString]);
6982 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6984 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6990 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6994 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6995 id<NSURLProtocolClient> client([self client]);
6997 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6999 NSData *data(UIImagePNGRepresentation(icon));
7001 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7002 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7003 [client URLProtocol:self didLoadData:data];
7004 [client URLProtocolDidFinishLoading:self];
7008 - (void) startLoading {
7009 id<NSURLProtocolClient> client([self client]);
7010 NSURLRequest *request([self request]);
7012 NSURL *url([request URL]);
7013 NSString *href([url absoluteString]);
7014 NSString *scheme([[url scheme] lowercaseString]);
7018 if ([scheme isEqualToString:@"cydia"])
7019 path = [href substringFromIndex:8];
7020 else if ([scheme isEqualToString:@"about"])
7021 path = [href substringFromIndex:12];
7022 else _assert(false);
7024 NSRange slash([path rangeOfString:@"/"]);
7027 if (slash.location == NSNotFound) {
7031 command = [path substringToIndex:slash.location];
7032 path = [path substringFromIndex:(slash.location + 1)];
7035 Database *database([Database sharedInstance]);
7037 if ([command isEqualToString:@"package-icon"]) {
7040 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7041 Package *package([database packageWithName:path]);
7045 UIImage *icon([package icon]);
7046 [self _returnPNGWithImage:icon forRequest:request];
7047 } else if ([command isEqualToString:@"source-icon"]) {
7050 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7051 NSString *source(Simplify(path));
7052 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7054 icon = [UIImage applicationImageNamed:@"unknown.png"];
7055 [self _returnPNGWithImage:icon forRequest:request];
7056 } else if ([command isEqualToString:@"uikit-image"]) {
7059 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7060 UIImage *icon(_UIImageWithName(path));
7061 [self _returnPNGWithImage:icon forRequest:request];
7062 } else if ([command isEqualToString:@"section-icon"]) {
7065 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7066 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7068 icon = [UIImage applicationImageNamed:@"unknown.png"];
7069 [self _returnPNGWithImage:icon forRequest:request];
7071 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7075 - (void) stopLoading {
7081 /* Section Controller {{{ */
7082 @interface SectionController : FilteredPackageListController {
7083 _H<NSString> section_;
7086 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7090 @implementation SectionController
7092 - (NSURL *) navigationURL {
7093 NSString *name = section_;
7097 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7100 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7103 title = UCLocalize("ALL_PACKAGES");
7104 else if (![name isEqual:@""])
7105 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7107 title = UCLocalize("NO_SECTION");
7109 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7116 /* Sections Controller {{{ */
7117 @interface SectionsController : CyteViewController <
7118 UITableViewDataSource,
7121 _transient Database *database_;
7122 _H<NSMutableArray> sections_;
7123 _H<NSMutableArray> filtered_;
7124 _H<UITableView, 2> list_;
7127 - (id) initWithDatabase:(Database *)database;
7128 - (void) editButtonClicked;
7132 @implementation SectionsController
7134 - (NSURL *) navigationURL {
7135 return [NSURL URLWithString:@"cydia://sections"];
7138 - (void) updateNavigationItem {
7139 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7140 if ([sections_ count] == 0) {
7141 [[self navigationItem] setRightBarButtonItem:nil];
7143 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7144 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7146 action:@selector(editButtonClicked)
7147 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7151 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7152 [super setEditing:editing animated:animated];
7157 [delegate_ updateData];
7159 [self updateNavigationItem];
7162 - (void) viewDidAppear:(BOOL)animated {
7163 [super viewDidAppear:animated];
7164 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7167 - (void) viewWillDisappear:(BOOL)animated {
7168 [super viewWillDisappear:animated];
7169 if ([self isEditing]) [self setEditing:NO];
7172 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7173 Section *section = nil;
7174 int index = [indexPath row];
7175 if (![self isEditing]) {
7178 section = [filtered_ objectAtIndex:index];
7180 section = [sections_ objectAtIndex:index];
7185 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7186 if ([self isEditing])
7187 return [sections_ count];
7189 return [filtered_ count] + 1;
7192 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7196 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7197 static NSString *reuseIdentifier = @"SectionCell";
7199 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7201 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7203 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7208 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7209 if ([self isEditing])
7212 Section *section = [self sectionAtIndexPath:indexPath];
7214 SectionController *controller = [[[SectionController alloc]
7215 initWithDatabase:database_
7216 section:[section name]
7218 [controller setDelegate:delegate_];
7220 [[self navigationController] pushViewController:controller animated:YES];
7224 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7226 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7227 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7228 [list_ setRowHeight:45.0f];
7229 [(UITableView *) list_ setDataSource:self];
7230 [list_ setDelegate:self];
7231 [[self view] addSubview:list_];
7234 - (void) viewDidLoad {
7235 [super viewDidLoad];
7237 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7240 - (void) releaseSubviews {
7243 [super releaseSubviews];
7246 - (id) initWithDatabase:(Database *)database {
7247 if ((self = [super init]) != nil) {
7248 database_ = database;
7250 sections_ = [NSMutableArray arrayWithCapacity:16];
7251 filtered_ = [NSMutableArray arrayWithCapacity:16];
7255 - (void) reloadData {
7258 NSArray *packages = [database_ packages];
7260 [sections_ removeAllObjects];
7261 [filtered_ removeAllObjects];
7263 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7266 for (Package *package in packages) {
7267 NSString *name([package section]);
7268 NSString *key(name == nil ? @"" : name);
7272 _profile(SectionsView$reloadData$Section)
7273 section = [sections objectForKey:key];
7274 if (section == nil) {
7275 _profile(SectionsView$reloadData$Section$Allocate)
7276 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7277 [sections setObject:section forKey:key];
7282 [section addToCount];
7284 _profile(SectionsView$reloadData$Filter)
7285 if (![package valid] || ![package visible])
7293 [sections_ addObjectsFromArray:[sections allValues]];
7295 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7297 for (Section *section in (id) sections_) {
7298 size_t count([section row]);
7302 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7303 [section setCount:count];
7304 [filtered_ addObject:section];
7307 [self updateNavigationItem];
7312 - (void) editButtonClicked {
7313 [self setEditing:![self isEditing] animated:YES];
7319 /* Changes Controller {{{ */
7320 @interface ChangesController : CyteViewController <
7321 UITableViewDataSource,
7324 _transient Database *database_;
7326 _H<NSArray> packages_;
7327 _H<NSMutableArray> sections_;
7328 _H<UITableView, 2> list_;
7332 - (id) initWithDatabase:(Database *)database;
7336 @implementation ChangesController
7338 - (NSURL *) navigationURL {
7339 return [NSURL URLWithString:@"cydia://changes"];
7342 - (void) viewDidAppear:(BOOL)animated {
7343 [super viewDidAppear:animated];
7344 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7347 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7348 NSInteger count([sections_ count]);
7349 return count == 0 ? 1 : count;
7352 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7353 if ([sections_ count] == 0)
7355 return [[sections_ objectAtIndex:section] name];
7358 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7359 if ([sections_ count] == 0)
7361 return [[sections_ objectAtIndex:section] count];
7364 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7365 @synchronized (database_) {
7366 if ([database_ era] != era_)
7369 NSUInteger sectionIndex([path section]);
7370 if (sectionIndex >= [sections_ count])
7372 Section *section([sections_ objectAtIndex:sectionIndex]);
7373 NSInteger row([path row]);
7374 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7377 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7378 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7380 cell = [[[PackageCell alloc] init] autorelease];
7382 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7383 [cell setPackage:package asSummary:false];
7387 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7388 Package *package([self packageAtIndexPath:path]);
7389 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7390 [view setDelegate:delegate_];
7391 [[self navigationController] pushViewController:view animated:YES];
7395 - (void) refreshButtonClicked {
7396 [delegate_ beginUpdate];
7397 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7400 - (void) upgradeButtonClicked {
7401 [delegate_ distUpgrade];
7402 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7406 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7408 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7409 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7410 [list_ setRowHeight:73];
7411 [(UITableView *) list_ setDataSource:self];
7412 [list_ setDelegate:self];
7413 [[self view] addSubview:list_];
7416 - (void) viewDidLoad {
7417 [super viewDidLoad];
7419 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7422 - (void) releaseSubviews {
7425 [super releaseSubviews];
7428 - (id) initWithDatabase:(Database *)database {
7429 if ((self = [super init]) != nil) {
7430 database_ = database;
7432 packages_ = [NSArray array];
7433 sections_ = [NSMutableArray arrayWithCapacity:16];
7437 - (NSMutableArray *) _reloadPackages {
7438 @synchronized (database_) {
7439 era_ = [database_ era];
7440 NSArray *packages([database_ packages]);
7442 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7445 _profile(ChangesController$_reloadPackages$Filter)
7446 for (Package *package in packages)
7447 if ([package upgradableAndEssential:YES] || [package visible])
7448 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7451 _profile(ChangesController$_reloadPackages$radixSort)
7452 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7459 - (void) _reloadData {
7464 UIProgressHUD *hud([delegate_ addProgressHUD]);
7465 [hud setText:UCLocalize("LOADING")];
7466 //NSLog(@"HUD:%@::%@", delegate_, hud);
7467 packages = [self yieldToSelector:@selector(_reloadPackages)];
7468 [delegate_ removeProgressHUD:hud];
7470 packages = [self _reloadPackages];
7473 @synchronized (database_) {
7474 if (era_ != [database_ era])
7477 packages_ = packages;
7478 [sections_ removeAllObjects];
7480 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7481 Section *ignored = nil;
7482 Section *section = nil;
7486 bool unseens = false;
7488 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7490 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7491 Package *package = [packages_ objectAtIndex:offset];
7493 BOOL uae = [package upgradableAndEssential:YES];
7497 time_t seen([package seen]);
7499 if (section == nil || last != seen) {
7503 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7506 _profile(ChangesController$reloadData$Allocate)
7507 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7508 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7509 [sections_ addObject:section];
7513 [section addToCount];
7514 } else if ([package ignored]) {
7515 if (ignored == nil) {
7516 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7518 [ignored addToCount];
7521 [upgradable addToCount];
7526 CFRelease(formatter);
7529 Section *last = [sections_ lastObject];
7530 size_t count = [last count];
7531 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7532 [sections_ removeLastObject];
7535 if ([ignored count] != 0)
7536 [sections_ insertObject:ignored atIndex:0];
7538 [sections_ insertObject:upgradable atIndex:0];
7542 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7543 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7544 style:UIBarButtonItemStylePlain
7546 action:@selector(upgradeButtonClicked)
7547 ] autorelease]) animated:YES];
7549 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7550 initWithTitle:UCLocalize("REFRESH")
7551 style:UIBarButtonItemStylePlain
7553 action:@selector(refreshButtonClicked)
7554 ] autorelease]) animated:YES];
7559 - (void) reloadData {
7561 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7566 /* Search Controller {{{ */
7567 @interface SearchController : FilteredPackageListController <
7570 _H<UISearchBar, 1> search_;
7574 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7575 - (void) reloadData;
7579 @implementation SearchController
7581 - (NSURL *) navigationURL {
7582 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7583 return [NSURL URLWithString:@"cydia://search"];
7585 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7588 - (void) useSearch {
7589 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7594 - (void) viewWillAppear:(BOOL)animated {
7595 [super viewWillAppear:animated];
7597 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7601 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7602 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7607 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7608 [search_ resignFirstResponder];
7612 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7613 [search_ setText:@""];
7614 [self searchBarButtonClicked:searchBar];
7617 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7618 [self searchBarButtonClicked:searchBar];
7621 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7622 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7626 - (bool) shouldYield {
7630 - (bool) shouldBlock {
7631 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7634 - (bool) isSummarized {
7635 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7638 - (bool) showsSections {
7642 - (NSMutableArray *) _reloadPackages {
7643 NSMutableArray *packages([super _reloadPackages]);
7644 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7645 [packages radixSortUsingSelector:@selector(rank)];
7649 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7650 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7651 search_ = [[[UISearchBar alloc] init] autorelease];
7652 [search_ setDelegate:self];
7655 [search_ setText:query];
7659 - (void) viewDidAppear:(BOOL)animated {
7660 [super viewDidAppear:animated];
7662 if (!searchloaded_) {
7663 searchloaded_ = YES;
7664 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7665 [search_ layoutSubviews];
7666 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7668 UITextField *textField;
7669 if ([search_ respondsToSelector:@selector(searchField)])
7670 textField = [search_ searchField];
7672 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7674 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7675 [textField setEnablesReturnKeyAutomatically:NO];
7676 [[self navigationItem] setTitleView:textField];
7680 - (void) reloadData {
7681 id object([search_ text]);
7682 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7683 object = [object componentsSeparatedByString:@" "];
7685 [self setObject:object];
7691 - (void) didSelectPackage:(Package *)package {
7692 [search_ resignFirstResponder];
7693 [super didSelectPackage:package];
7698 /* Package Settings Controller {{{ */
7699 @interface PackageSettingsController : CyteViewController <
7700 UITableViewDataSource,
7703 _transient Database *database_;
7705 _H<Package> package_;
7706 _H<UITableView, 2> table_;
7707 _H<UISwitch> subscribedSwitch_;
7708 _H<UISwitch> ignoredSwitch_;
7709 _H<UITableViewCell> subscribedCell_;
7710 _H<UITableViewCell> ignoredCell_;
7713 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7717 @implementation PackageSettingsController
7719 - (NSURL *) navigationURL {
7720 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7723 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7724 if (package_ == nil)
7727 if ([package_ installed] == nil)
7733 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7734 if (package_ == nil)
7737 // both sections contain just one item right now.
7741 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7745 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7747 return UCLocalize("SHOW_ALL_CHANGES_EX");
7749 return UCLocalize("IGNORE_UPGRADES_EX");
7752 - (void) onSubscribed:(id)control {
7753 bool value([control isOn]);
7754 if (package_ == nil)
7756 if ([package_ setSubscribed:value])
7757 [delegate_ updateData];
7760 - (void) _updateIgnored {
7761 const char *package([name_ UTF8String]);
7762 bool on([ignoredSwitch_ isOn]);
7764 pid_t pid(ExecFork());
7766 FILE *dpkg(popen("dpkg --set-selections", "w"));
7767 fwrite(package, strlen(package), 1, dpkg);
7770 fwrite(" hold\n", 6, 1, dpkg);
7772 fwrite(" install\n", 9, 1, dpkg);
7782 int result(waitpid(pid, &status, 0));
7785 _assert(result == pid);
7791 - (void) onIgnored:(id)control {
7792 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7793 [invocation setTarget:self];
7794 [invocation setSelector:@selector(_updateIgnored)];
7796 [delegate_ reloadDataWithInvocation:invocation];
7799 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7800 if (package_ == nil)
7803 switch ([indexPath section]) {
7804 case 0: return subscribedCell_;
7805 case 1: return ignoredCell_;
7814 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7816 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7817 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7818 [(UITableView *) table_ setDataSource:self];
7819 [table_ setDelegate:self];
7820 [[self view] addSubview:table_];
7822 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7823 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7824 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7826 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7827 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7828 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7830 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7831 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7832 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7833 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7835 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7836 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7837 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7838 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7841 - (void) viewDidLoad {
7842 [super viewDidLoad];
7844 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7847 - (void) releaseSubviews {
7849 subscribedCell_ = nil;
7851 ignoredSwitch_ = nil;
7852 subscribedSwitch_ = nil;
7854 [super releaseSubviews];
7857 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7858 if ((self = [super init]) != nil) {
7859 database_ = database;
7864 - (void) reloadData {
7867 package_ = [database_ packageWithName:name_];
7869 if (package_ != nil) {
7870 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7871 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7872 } // XXX: what now, G?
7874 [table_ reloadData];
7880 /* Installed Controller {{{ */
7881 @interface InstalledController : FilteredPackageListController {
7885 - (id) initWithDatabase:(Database *)database;
7887 - (void) updateRoleButton;
7888 - (void) queueStatusDidChange;
7892 @implementation InstalledController
7894 - (NSURL *) navigationURL {
7895 return [NSURL URLWithString:@"cydia://installed"];
7898 - (id) initWithDatabase:(Database *)database {
7899 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7900 [self updateRoleButton];
7901 [self queueStatusDidChange];
7906 - (void) queueButtonClicked {
7911 - (void) queueStatusDidChange {
7915 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7916 initWithTitle:UCLocalize("QUEUE")
7917 style:UIBarButtonItemStyleDone
7919 action:@selector(queueButtonClicked)
7922 [[self navigationItem] setLeftBarButtonItem:nil];
7928 - (void) updateRoleButton {
7929 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7930 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7931 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7932 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7934 action:@selector(roleButtonClicked)
7938 - (void) roleButtonClicked {
7939 [self setObject:[NSNumber numberWithBool:expert_]];
7943 [self updateRoleButton];
7949 /* Source Cell {{{ */
7950 @interface SourceCell : CyteTableViewCell <
7951 CyteTableViewCellDelegate
7954 _H<NSString> origin_;
7955 _H<NSString> label_;
7958 - (void) setSource:(Source *)source;
7962 @implementation SourceCell
7964 - (void) _setImage:(UIImage *)image {
7966 [content_ setNeedsDisplay];
7969 - (void) _setSource:(Source *)source {
7970 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7972 if (NSString *base = [source base])
7973 if ([base length] != 0) {
7974 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7976 if (NSData *data = [NSURLConnection
7977 sendSynchronousRequest:[NSURLRequest
7979 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7983 returningResponse:NULL
7986 if (UIImage *image = [UIImage imageWithData:data])
7987 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7993 - (void) setSource:(Source *)source {
7994 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7996 origin_ = [source name];
7997 label_ = [source uri];
7999 [content_ setNeedsDisplay];
8001 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
8004 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8005 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8006 UIView *content([self contentView]);
8007 CGRect bounds([content bounds]);
8009 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8010 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8011 [content_ setBackgroundColor:[UIColor whiteColor]];
8012 [content addSubview:content_];
8014 [content_ setDelegate:self];
8015 [content_ setOpaque:YES];
8019 - (NSString *) accessibilityLabel {
8023 - (void) drawContentRect:(CGRect)rect {
8024 bool highlighted(highlighted_);
8025 float width(rect.size.width);
8028 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8035 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8039 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8044 /* Source Controller {{{ */
8045 @interface SourceController : FilteredPackageListController {
8046 _transient Source *source_;
8050 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8054 @implementation SourceController
8056 - (NSURL *) navigationURL {
8057 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8060 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8061 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8063 key_ = [source key];
8067 - (void) reloadData {
8068 source_ = [database_ sourceWithKey:key_];
8069 key_ = [source_ key];
8070 [self setObject:source_];
8072 [[self navigationItem] setTitle:[source_ label]];
8079 /* Sources Controller {{{ */
8080 @interface SourcesController : CyteViewController <
8081 UITableViewDataSource,
8084 _transient Database *database_;
8085 _H<UITableView, 2> list_;
8086 _H<NSMutableArray> sources_;
8090 _H<UIProgressHUD> hud_;
8093 //NSURLConnection *installer_;
8094 NSURLConnection *trivial_;
8095 NSURLConnection *trivial_bz2_;
8096 NSURLConnection *trivial_gz_;
8097 //NSURLConnection *automatic_;
8102 - (id) initWithDatabase:(Database *)database;
8103 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8107 @implementation SourcesController
8109 - (void) _releaseConnection:(NSURLConnection *)connection {
8110 if (connection != nil) {
8111 [connection cancel];
8112 //[connection setDelegate:nil];
8113 [connection release];
8118 //[self _releaseConnection:installer_];
8119 [self _releaseConnection:trivial_];
8120 [self _releaseConnection:trivial_gz_];
8121 [self _releaseConnection:trivial_bz2_];
8122 //[self _releaseConnection:automatic_];
8127 - (NSURL *) navigationURL {
8128 return [NSURL URLWithString:@"cydia://sources"];
8131 - (void) viewDidAppear:(BOOL)animated {
8132 [super viewDidAppear:animated];
8133 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8136 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8137 return offset_ == 0 ? 1 : 2;
8140 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8141 switch (section + (offset_ == 0 ? 1 : 0)) {
8142 case 0: return UCLocalize("ENTERED_BY_USER");
8143 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8149 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8150 int count = [sources_ count];
8152 case 0: return (offset_ == 0 ? count : offset_);
8153 case 1: return count - offset_;
8159 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8161 switch (indexPath.section) {
8162 case 0: idx = indexPath.row; break;
8163 case 1: idx = indexPath.row + offset_; break;
8167 return [sources_ objectAtIndex:idx];
8170 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8171 static NSString *cellIdentifier = @"SourceCell";
8173 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8174 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8175 [cell setSource:[self sourceAtIndexPath:indexPath]];
8176 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8181 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8182 Source *source = [self sourceAtIndexPath:indexPath];
8184 SourceController *controller = [[[SourceController alloc]
8185 initWithDatabase:database_
8189 [controller setDelegate:delegate_];
8191 [[self navigationController] pushViewController:controller animated:YES];
8194 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8195 Source *source = [self sourceAtIndexPath:indexPath];
8196 return [source record] != nil;
8199 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8200 if (editingStyle == UITableViewCellEditingStyleDelete) {
8201 Source *source = [self sourceAtIndexPath:indexPath];
8202 [Sources_ removeObjectForKey:[source key]];
8203 [delegate_ syncData];
8208 [delegate_ addTrivialSource:href_];
8209 [delegate_ syncData];
8212 - (NSString *) getWarning {
8213 NSString *href(href_);
8214 NSRange colon([href rangeOfString:@"://"]);
8215 if (colon.location != NSNotFound)
8216 href = [href substringFromIndex:(colon.location + 3)];
8217 href = [href stringByAddingPercentEscapes];
8218 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8219 href = [href stringByCachingURLWithCurrentCDN];
8221 NSURL *url([NSURL URLWithString:href]);
8223 NSStringEncoding encoding;
8224 NSError *error(nil);
8226 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8227 return [warning length] == 0 ? nil : warning;
8231 - (void) _endConnection:(NSURLConnection *)connection {
8232 // XXX: the memory management in this method is horribly awkward
8234 NSURLConnection **field = NULL;
8235 if (connection == trivial_)
8237 else if (connection == trivial_bz2_)
8238 field = &trivial_bz2_;
8239 else if (connection == trivial_gz_)
8240 field = &trivial_gz_;
8241 _assert(field != NULL);
8242 [connection release];
8247 trivial_bz2_ == nil &&
8250 [delegate_ releaseNetworkActivityIndicator];
8252 [delegate_ removeProgressHUD:hud_];
8258 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8261 UIAlertView *alert = [[[UIAlertView alloc]
8262 initWithTitle:UCLocalize("SOURCE_WARNING")
8265 cancelButtonTitle:UCLocalize("CANCEL")
8267 UCLocalize("ADD_ANYWAY"),
8271 [alert setContext:@"warning"];
8272 [alert setNumberOfRows:1];
8276 } else if (error_ != nil) {
8277 UIAlertView *alert = [[[UIAlertView alloc]
8278 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8279 message:[error_ localizedDescription]
8281 cancelButtonTitle:UCLocalize("OK")
8282 otherButtonTitles:nil
8285 [alert setContext:@"urlerror"];
8288 UIAlertView *alert = [[[UIAlertView alloc]
8289 initWithTitle:UCLocalize("NOT_REPOSITORY")
8290 message:UCLocalize("NOT_REPOSITORY_EX")
8292 cancelButtonTitle:UCLocalize("OK")
8293 otherButtonTitles:nil
8296 [alert setContext:@"trivial"];
8305 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8306 switch ([response statusCode]) {
8312 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8313 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8315 [self _endConnection:connection];
8318 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8319 [self _endConnection:connection];
8322 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8323 NSURL *url([NSURL URLWithString:href]);
8325 NSMutableURLRequest *request = [NSMutableURLRequest
8327 cachePolicy:NSURLRequestUseProtocolCachePolicy
8328 timeoutInterval:120.0
8331 [request setHTTPMethod:method];
8333 if (Machine_ != NULL)
8334 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8336 if ([url isCydiaSecure]) {
8337 if (UniqueID_ != nil)
8338 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8341 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8344 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8345 NSString *context([alert context]);
8347 if ([context isEqualToString:@"source"]) {
8350 NSString *href = [[alert textField] text];
8352 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8354 if (![href hasSuffix:@"/"])
8355 href_ = [href stringByAppendingString:@"/"];
8359 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8360 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8361 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8362 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8366 // XXX: this is stupid
8367 hud_ = [delegate_ addProgressHUD];
8368 [hud_ setText:UCLocalize("VERIFYING_URL")];
8369 [delegate_ retainNetworkActivityIndicator];
8378 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8379 } else if ([context isEqualToString:@"trivial"])
8380 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8381 else if ([context isEqualToString:@"urlerror"])
8382 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8383 else if ([context isEqualToString:@"warning"]) {
8397 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8402 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8404 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8405 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8406 [list_ setRowHeight:56];
8407 [(UITableView *) list_ setDataSource:self];
8408 [list_ setDelegate:self];
8409 [[self view] addSubview:list_];
8412 - (void) viewDidLoad {
8413 [super viewDidLoad];
8415 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8416 [self updateButtonsForEditingStatus:NO animated:NO];
8419 - (void) releaseSubviews {
8422 [super releaseSubviews];
8425 - (id) initWithDatabase:(Database *)database {
8426 if ((self = [super init]) != nil) {
8427 database_ = database;
8428 sources_ = [NSMutableArray arrayWithCapacity:16];
8432 - (void) reloadData {
8436 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8439 [sources_ removeAllObjects];
8440 [sources_ addObjectsFromArray:[database_ sources]];
8442 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8445 int count([sources_ count]);
8447 for (int i = 0; i != count; i++) {
8448 if ([[sources_ objectAtIndex:i] record] == nil)
8453 [list_ setEditing:NO];
8454 [self updateButtonsForEditingStatus:NO animated:NO];
8458 - (void) showAddSourcePrompt {
8459 UIAlertView *alert = [[[UIAlertView alloc]
8460 initWithTitle:UCLocalize("ENTER_APT_URL")
8463 cancelButtonTitle:UCLocalize("CANCEL")
8465 UCLocalize("ADD_SOURCE"),
8469 [alert setContext:@"source"];
8471 [alert setNumberOfRows:1];
8472 [alert addTextFieldWithValue:@"http://" label:@""];
8474 UITextInputTraits *traits = [[alert textField] textInputTraits];
8475 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8476 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8477 [traits setKeyboardType:UIKeyboardTypeURL];
8478 // XXX: UIReturnKeyDone
8479 [traits setReturnKeyType:UIReturnKeyNext];
8484 - (void) addButtonClicked {
8485 [self showAddSourcePrompt];
8488 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8489 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8490 initWithTitle:UCLocalize("ADD")
8491 style:UIBarButtonItemStylePlain
8493 action:@selector(addButtonClicked)
8494 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8496 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8497 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8498 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8500 action:@selector(editButtonClicked)
8501 ] autorelease] animated:animated];
8503 if (IsWildcat_ && !editing)
8504 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8505 initWithTitle:UCLocalize("SETTINGS")
8506 style:UIBarButtonItemStylePlain
8508 action:@selector(settingsButtonClicked)
8512 - (void) settingsButtonClicked {
8513 [delegate_ showSettings];
8516 - (void) editButtonClicked {
8517 [list_ setEditing:![list_ isEditing] animated:YES];
8519 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8525 /* Settings Controller {{{ */
8526 @interface SettingsController : CyteViewController <
8527 UITableViewDataSource,
8530 _transient Database *database_;
8531 // XXX: ok, "roledelegate_"?...
8532 _transient id roledelegate_;
8533 _H<UITableView, 2> table_;
8534 _H<UISegmentedControl> segment_;
8535 _H<UIView> container_;
8538 - (void) showDoneButton;
8539 - (void) resizeSegmentedControl;
8543 @implementation SettingsController
8546 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8548 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8549 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8550 [table_ setDelegate:self];
8551 [(UITableView *) table_ setDataSource:self];
8552 [[self view] addSubview:table_];
8554 NSArray *items = [NSArray arrayWithObjects:
8556 UCLocalize("HACKER"),
8557 UCLocalize("DEVELOPER"),
8559 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8560 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8561 [container_ addSubview:segment_];
8564 - (void) viewDidLoad {
8565 [super viewDidLoad];
8567 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8570 if ([Role_ isEqualToString:@"User"]) index = 0;
8571 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8572 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8574 [segment_ setSelectedSegmentIndex:index];
8575 [self showDoneButton];
8578 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8579 [self resizeSegmentedControl];
8582 - (void) releaseSubviews {
8587 [super releaseSubviews];
8590 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8591 if ((self = [super init]) != nil) {
8592 database_ = database;
8593 roledelegate_ = delegate;
8597 - (void) resizeSegmentedControl {
8598 CGFloat width = [[self view] frame].size.width;
8599 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8602 - (void) viewWillAppear:(BOOL)animated {
8603 [super viewWillAppear:animated];
8605 [self resizeSegmentedControl];
8608 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8609 [self resizeSegmentedControl];
8612 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8613 [self resizeSegmentedControl];
8617 NSString *role(nil);
8619 switch ([segment_ selectedSegmentIndex]) {
8620 case 0: role = @"User"; break;
8621 case 1: role = @"Hacker"; break;
8622 case 2: role = @"Developer"; break;
8627 if (![role isEqualToString:Role_]) {
8628 bool rolling(Role_ == nil);
8631 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8635 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8639 [roledelegate_ loadData];
8641 [roledelegate_ updateData];
8645 - (void) segmentChanged:(UISegmentedControl *)control {
8646 [self showDoneButton];
8649 - (void) saveAndClose {
8652 [[self navigationItem] setRightBarButtonItem:nil];
8653 [[self navigationController] dismissModalViewControllerAnimated:YES];
8656 - (void) doneButtonClicked {
8657 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8658 [spinner startAnimating];
8659 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8660 [[self navigationItem] setRightBarButtonItem:spinItem];
8662 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8665 - (void) showDoneButton {
8666 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8667 initWithTitle:UCLocalize("DONE")
8668 style:UIBarButtonItemStyleDone
8670 action:@selector(doneButtonClicked)
8671 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8674 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8675 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8679 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8683 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8684 return nil; // This method is required by the protocol.
8687 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8689 return UCLocalize("ROLE_EX");
8691 return [NSString stringWithFormat:
8692 @"%@: %@\n%@: %@\n%@: %@",
8693 UCLocalize("USER"), UCLocalize("USER_EX"),
8694 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8695 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8700 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8701 return section == 3 ? 44.0f : 0;
8704 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8705 return section == 3 ? container_ : nil;
8708 - (void) reloadData {
8711 [table_ reloadData];
8716 /* Stash Controller {{{ */
8717 @interface StashController : CyteViewController {
8718 _H<UIActivityIndicatorView> spinner_;
8719 _H<UILabel> status_;
8720 _H<UILabel> caption_;
8725 @implementation StashController
8728 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8729 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8731 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8732 CGRect spinrect = [spinner_ frame];
8733 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8734 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8735 [spinner_ setFrame:spinrect];
8736 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8737 [[self view] addSubview:spinner_];
8738 [spinner_ startAnimating];
8741 captrect.size.width = [[self view] frame].size.width;
8742 captrect.size.height = 40.0f;
8743 captrect.origin.x = 0;
8744 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8745 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8746 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8747 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8748 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8749 [caption_ setTextColor:[UIColor whiteColor]];
8750 [caption_ setBackgroundColor:[UIColor clearColor]];
8751 [caption_ setShadowColor:[UIColor blackColor]];
8752 [caption_ setTextAlignment:UITextAlignmentCenter];
8753 [[self view] addSubview:caption_];
8756 statusrect.size.width = [[self view] frame].size.width;
8757 statusrect.size.height = 30.0f;
8758 statusrect.origin.x = 0;
8759 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8760 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8761 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8762 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8763 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8764 [status_ setTextColor:[UIColor whiteColor]];
8765 [status_ setBackgroundColor:[UIColor clearColor]];
8766 [status_ setShadowColor:[UIColor blackColor]];
8767 [status_ setTextAlignment:UITextAlignmentCenter];
8768 [[self view] addSubview:status_];
8771 - (void) releaseSubviews {
8776 [super releaseSubviews];
8782 @interface CYURLCache : SDURLCache {
8787 @implementation CYURLCache
8789 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8792 else if ([event isEqualToString:@"no-cache"])
8794 else if ([event isEqualToString:@"store"])
8796 else if ([event isEqualToString:@"invalid"])
8798 else if ([event isEqualToString:@"memory"])
8800 else if ([event isEqualToString:@"disk"])
8802 else if ([event isEqualToString:@"miss"])
8805 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8809 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8810 if (NSURLResponse *response = [cached response])
8811 if (NSString *mime = [response MIMEType])
8812 if ([mime isEqualToString:@"text/cache-manifest"]) {
8813 NSURL *url([response URL]);
8816 NSLog(@"###: %@", [url absoluteString]);
8819 @synchronized (HostConfig_) {
8820 [CachedURLs_ addObject:url];
8824 [super storeCachedResponse:cached forRequest:request];
8829 @interface Cydia : UIApplication <
8830 ConfirmationControllerDelegate,
8833 UINavigationControllerDelegate,
8834 UITabBarControllerDelegate
8836 _H<UIWindow> window_;
8837 _H<CYTabBarController> tabbar_;
8838 _H<CydiaLoadingViewController> emulated_;
8840 _H<NSMutableArray> essential_;
8841 _H<NSMutableArray> broken_;
8843 Database *database_;
8845 _H<NSURL> starturl_;
8850 _H<StashController> stash_;
8859 @implementation Cydia
8861 - (void) beginUpdate {
8862 [tabbar_ beginUpdate];
8866 return [tabbar_ updating];
8870 if ([broken_ count] != 0) {
8871 int count = [broken_ count];
8873 UIAlertView *alert = [[[UIAlertView alloc]
8874 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8875 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8877 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8879 UCLocalize("TEMPORARY_IGNORE"),
8883 [alert setContext:@"fixhalf"];
8884 [alert setNumberOfRows:2];
8886 } else if (!Ignored_ && [essential_ count] != 0) {
8887 int count = [essential_ count];
8889 UIAlertView *alert = [[[UIAlertView alloc]
8890 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8891 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8893 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8895 UCLocalize("UPGRADE_ESSENTIAL"),
8896 UCLocalize("COMPLETE_UPGRADE"),
8900 [alert setContext:@"upgrade"];
8905 - (void) returnToCydia {
8909 - (void) _saveConfig {
8915 NSString *error(nil);
8917 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8919 NSError *error(nil);
8920 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8921 NSLog(@"failure to save metadata data: %@", error);
8926 NSLog(@"failure to serialize metadata: %@", error);
8933 // Navigation controller for the queuing badge.
8934 - (UINavigationController *) queueNavigationController {
8935 NSArray *controllers = [tabbar_ viewControllers];
8936 return [controllers objectAtIndex:3];
8939 - (void) unloadData {
8940 [tabbar_ unloadData];
8943 - (void) _updateData {
8947 UINavigationController *navigation = [self queueNavigationController];
8949 id queuedelegate = nil;
8950 if ([[navigation viewControllers] count] > 0)
8951 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8953 [queuedelegate queueStatusDidChange];
8954 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8957 - (void) _refreshIfPossible:(NSDate *)update {
8958 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8960 bool recently = false;
8961 if (update != nil) {
8962 NSTimeInterval interval([update timeIntervalSinceNow]);
8963 if (interval <= 0 && interval > -(15*60))
8967 // Don't automatic refresh if:
8968 // - We already refreshed recently.
8969 // - We already auto-refreshed this launch.
8970 // - Auto-refresh is disabled.
8971 if (recently || loaded_ || ManualRefresh) {
8972 // If we are cancelling, we need to make sure it knows it's already loaded.
8975 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8977 // We are going to load, so remember that.
8980 SCNetworkReachabilityFlags flags; {
8981 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8982 SCNetworkReachabilityGetFlags(reachability, &flags);
8983 CFRelease(reachability);
8986 // XXX: this elaborate mess is what Apple is using to determine this? :(
8987 // XXX: do we care if the user has to intervene? maybe that's ok?
8989 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8990 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8991 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8992 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8993 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8994 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8998 // If we can reach the server, auto-refresh!
9000 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9006 - (void) refreshIfPossible {
9007 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9010 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9011 @synchronized (self) {
9012 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9013 [hud setText:UCLocalize("RELOADING_DATA")];
9015 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9018 [self removeProgressHUD:hud];
9022 [essential_ removeAllObjects];
9023 [broken_ removeAllObjects];
9025 NSArray *packages([database_ packages]);
9026 for (Package *package in packages) {
9028 [broken_ addObject:package];
9029 if ([package upgradableAndEssential:NO]) {
9030 if ([package essential])
9031 [essential_ addObject:package];
9036 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9039 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9040 [changesItem setBadgeValue:badge];
9041 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9042 [self setApplicationIconBadgeNumber:changes];
9045 [changesItem setBadgeValue:nil];
9046 [changesItem setAnimatedBadge:NO];
9047 [self setApplicationIconBadgeNumber:0];
9053 - (void) updateData {
9059 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9062 - (void) disemulate {
9063 if (emulated_ == nil)
9066 [window_ addSubview:[tabbar_ view]];
9067 [[emulated_ view] removeFromSuperview];
9069 [window_ setUserInteractionEnabled:YES];
9072 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9073 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9075 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9077 UIViewController *parent;
9078 if (emulated_ == nil)
9087 [parent presentModalViewController:navigation animated:YES];
9090 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9091 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9093 if (navigation != nil)
9094 [navigation pushViewController:progress animated:YES];
9096 [self presentModalViewController:progress force:YES];
9098 [progress invoke:invocation withTitle:title];
9102 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9103 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9106 - (void) repairWithInvocation:(NSInvocation *)invocation {
9108 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9112 - (void) repairWithSelector:(SEL)selector {
9113 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9116 - (void) reloadData {
9117 [self reloadDataWithInvocation:nil];
9118 if ([database_ progressDelegate] == nil)
9124 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9127 - (void) addSource:(NSDictionary *) source {
9131 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9132 AddSource(href, distribution, sections);
9135 - (void) addTrivialSource:(NSString *)href {
9136 AddSource(href, @"./");
9139 - (void) updateValues {
9144 pkgProblemResolver *resolver = [database_ resolver];
9146 resolver->InstallProtect();
9147 if (!resolver->Resolve(true))
9152 // XXX: this is a really crappy way of doing this.
9153 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9154 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9155 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9156 if ([tabbar_ updating])
9157 [tabbar_ cancelUpdate];
9159 if (![database_ prepare])
9162 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9163 [page setDelegate:self];
9164 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9167 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9168 [tabbar_ presentModalViewController:confirm_ animated:YES];
9174 @synchronized (self) {
9179 - (void) clearPackage:(Package *)package {
9180 @synchronized (self) {
9187 - (void) installPackages:(NSArray *)packages {
9188 @synchronized (self) {
9189 for (Package *package in packages)
9196 - (void) installPackage:(Package *)package {
9197 @synchronized (self) {
9204 - (void) removePackage:(Package *)package {
9205 @synchronized (self) {
9212 - (void) distUpgrade {
9213 @synchronized (self) {
9214 if (![database_ upgrade])
9221 [database_ perform];
9222 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9225 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9228 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9230 [self refreshIfPossible];
9233 - (void) showSettings {
9234 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9237 - (void) retainNetworkActivityIndicator {
9238 if (activity_++ == 0)
9239 [self setNetworkActivityIndicatorVisible:YES];
9242 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9246 - (void) releaseNetworkActivityIndicator {
9247 if (--activity_ == 0)
9248 [self setNetworkActivityIndicatorVisible:NO];
9251 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9256 - (void) cancelAndClear:(bool)clear {
9257 @synchronized (self) {
9269 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9270 NSString *context([alert context]);
9272 if ([context isEqualToString:@"conffile"]) {
9273 FILE *input = [database_ input];
9274 if (button == [alert cancelButtonIndex])
9275 fprintf(input, "N\n");
9276 else if (button == [alert firstOtherButtonIndex])
9277 fprintf(input, "Y\n");
9280 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9281 } else if ([context isEqualToString:@"fixhalf"]) {
9282 if (button == [alert cancelButtonIndex]) {
9283 @synchronized (self) {
9284 for (Package *broken in (id) broken_) {
9287 NSString *id = [broken id];
9288 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9289 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9290 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9291 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9297 } else if (button == [alert firstOtherButtonIndex]) {
9298 [broken_ removeAllObjects];
9302 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9303 } else if ([context isEqualToString:@"upgrade"]) {
9304 if (button == [alert firstOtherButtonIndex]) {
9305 @synchronized (self) {
9306 for (Package *essential in (id) essential_)
9307 [essential install];
9312 } else if (button == [alert firstOtherButtonIndex] + 1) {
9314 } else if (button == [alert cancelButtonIndex]) {
9318 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9322 - (void) system:(NSString *)command {
9323 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9326 system([command UTF8String]);
9332 - (void) applicationWillSuspend {
9334 [super applicationWillSuspend];
9337 - (BOOL) isSafeToSuspend {
9340 NSLog(@"isSafeToSuspend: locked_ != 0");
9345 // Use external process status API internally.
9346 // This is probably a really bad idea.
9347 // XXX: what is the point of this? does this solve anything at all?
9348 uint64_t status = 0;
9350 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9351 notify_get_state(notify_token, &status);
9352 notify_cancel(notify_token);
9357 NSLog(@"isSafeToSuspend: status != 0");
9363 NSLog(@"isSafeToSuspend: -> true");
9368 - (void) applicationSuspend:(__GSEvent *)event {
9369 if ([self isSafeToSuspend])
9370 [super applicationSuspend:event];
9373 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9374 if ([self isSafeToSuspend])
9375 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9378 - (void) _setSuspended:(BOOL)value {
9379 if ([self isSafeToSuspend])
9380 [super _setSuspended:value];
9383 - (UIProgressHUD *) addProgressHUD {
9384 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9385 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9387 [window_ setUserInteractionEnabled:NO];
9389 UIViewController *target(tabbar_);
9390 if (UIViewController *modal = [target modalViewController])
9393 UIView *view([target view]);
9394 [view addSubview:hud];
9396 [hud showInView:[tabbar_ view]];
9402 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9405 [hud removeFromSuperview];
9406 [window_ setUserInteractionEnabled:YES];
9409 - (CyteViewController *) pageForPackage:(NSString *)name {
9410 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9413 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9414 NSString *scheme([[url scheme] lowercaseString]);
9415 if ([[url absoluteString] length] <= [scheme length] + 3)
9417 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9418 NSArray *components([path pathComponents]);
9420 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9421 return [self pageForPackage:[components objectAtIndex:1]];
9423 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9426 NSString *base([components objectAtIndex:0]);
9428 CyteViewController *controller = nil;
9430 if ([base isEqualToString:@"url"]) {
9431 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9432 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9433 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9434 } else if (!external && [components count] == 1) {
9435 if ([base isEqualToString:@"manage"]) {
9436 controller = [[[ManageController alloc] init] autorelease];
9439 if ([base isEqualToString:@"sources"]) {
9440 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9443 if ([base isEqualToString:@"home"]) {
9444 controller = [[[HomeController alloc] init] autorelease];
9447 if ([base isEqualToString:@"sections"]) {
9448 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9451 if ([base isEqualToString:@"search"]) {
9452 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9455 if ([base isEqualToString:@"changes"]) {
9456 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9459 if ([base isEqualToString:@"installed"]) {
9460 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9462 } else if ([components count] == 2) {
9463 NSString *argument = [components objectAtIndex:1];
9465 if ([base isEqualToString:@"package"]) {
9466 controller = [self pageForPackage:argument];
9469 if (!external && [base isEqualToString:@"search"]) {
9470 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9473 if (!external && [base isEqualToString:@"sections"]) {
9474 if ([argument isEqualToString:@"all"])
9476 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9479 if (!external && [base isEqualToString:@"sources"]) {
9480 if ([argument isEqualToString:@"add"]) {
9481 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9482 [(SourcesController *)controller showAddSourcePrompt];
9484 Source *source = [database_ sourceWithKey:argument];
9485 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9489 if (!external && [base isEqualToString:@"launch"]) {
9490 [self launchApplicationWithIdentifier:argument suspended:NO];
9493 } else if (!external && [components count] == 3) {
9494 NSString *arg1 = [components objectAtIndex:1];
9495 NSString *arg2 = [components objectAtIndex:2];
9497 if ([base isEqualToString:@"package"]) {
9498 if ([arg2 isEqualToString:@"settings"]) {
9499 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9500 } else if ([arg2 isEqualToString:@"files"]) {
9501 if (Package *package = [database_ packageWithName:arg1]) {
9502 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9503 [(FileTable *)controller setPackage:package];
9509 [controller setDelegate:self];
9513 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9514 CyteViewController *page([self pageForURL:url forExternal:external]);
9517 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9518 [nav setViewControllers:[NSArray arrayWithObject:page]];
9519 [tabbar_ setUnselectedViewController:nav];
9525 - (void) applicationOpenURL:(NSURL *)url {
9526 [super applicationOpenURL:url];
9531 [self openCydiaURL:url forExternal:YES];
9534 - (void) applicationWillResignActive:(UIApplication *)application {
9535 // Stop refreshing if you get a phone call or lock the device.
9536 if ([tabbar_ updating])
9537 [tabbar_ cancelUpdate];
9539 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9540 [super applicationWillResignActive:application];
9543 - (void) saveState {
9544 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9545 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9546 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9552 - (void) applicationWillTerminate:(UIApplication *)application {
9556 - (void) setConfigurationData:(NSString *)data {
9557 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9559 if (!conffile_r(data)) {
9560 lprintf("E:invalid conffile\n");
9564 NSString *ofile = conffile_r[1];
9565 //NSString *nfile = conffile_r[2];
9567 UIAlertView *alert = [[[UIAlertView alloc]
9568 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9569 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9571 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9573 UCLocalize("ACCEPT_NEW_COPY"),
9574 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9578 [alert setContext:@"conffile"];
9579 [alert setNumberOfRows:2];
9583 - (void) addStashController {
9585 stash_ = [[[StashController alloc] init] autorelease];
9586 [window_ addSubview:[stash_ view]];
9589 - (void) removeStashController {
9590 [[stash_ view] removeFromSuperview];
9596 [self setIdleTimerDisabled:YES];
9598 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9599 UpdateExternalStatus(1);
9600 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9601 UpdateExternalStatus(0);
9603 [self removeStashController];
9605 if (ExecFork() == 0) {
9606 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9607 perror("launchctl stop");
9611 - (void) setupViewControllers {
9612 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9614 NSMutableArray *items([NSMutableArray arrayWithObjects:
9615 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9616 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9617 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9618 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9622 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9623 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9625 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9628 NSMutableArray *controllers([NSMutableArray array]);
9629 for (UITabBarItem *item in items) {
9630 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9631 [controller setTabBarItem:item];
9632 [controllers addObject:controller];
9634 [tabbar_ setViewControllers:controllers];
9636 [tabbar_ setUpdateDelegate:self];
9639 - (void) _sendMemoryWarningNotification {
9640 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9643 - (void) _sendMemoryWarningNotifications {
9645 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9650 - (void) applicationDidFinishLaunching:(id)unused {
9651 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9654 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9655 [self setApplicationSupportsShakeToEdit:NO];
9657 @synchronized (HostConfig_) {
9658 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9661 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9662 initWithMemoryCapacity:524288
9663 diskCapacity:10485760
9664 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9667 [CydiaWebViewController _initialize];
9669 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9671 // this would disallow http{,s} URLs from accessing this data
9672 //[WebView registerURLSchemeAsLocal:@"cydia"];
9674 Font12_ = [UIFont systemFontOfSize:12];
9675 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9676 Font14_ = [UIFont systemFontOfSize:14];
9677 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9678 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9680 essential_ = [NSMutableArray arrayWithCapacity:4];
9681 broken_ = [NSMutableArray arrayWithCapacity:4];
9683 // XXX: I really need this thing... like, seriously... I'm sorry
9684 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9686 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9687 [window_ orderFront:self];
9688 [window_ makeKey:self];
9689 [window_ setHidden:NO];
9692 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9693 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9694 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9695 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9696 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9697 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9698 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9699 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9700 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9703 [self addStashController];
9704 // XXX: this would be much cleaner as a yieldToSelector:
9705 // that way the removeStashController could happen right here inline
9706 // we also could no longer require the useless stash_ field anymore
9707 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9711 database_ = [Database sharedInstance];
9712 [database_ setDelegate:self];
9714 [window_ setUserInteractionEnabled:NO];
9715 [self setupViewControllers];
9717 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9718 [window_ addSubview:[emulated_ view]];
9720 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9724 - (NSArray *) defaultStartPages {
9725 NSMutableArray *standard = [NSMutableArray array];
9726 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9727 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9728 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9730 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9732 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9733 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9735 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9742 [window_ setUserInteractionEnabled:YES];
9743 [self showSettings];
9746 if ([emulated_ modalViewController] != nil)
9747 [emulated_ dismissModalViewControllerAnimated:YES];
9748 [window_ setUserInteractionEnabled:NO];
9751 [self reloadDataWithInvocation:nil];
9752 [self refreshIfPossible];
9757 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9758 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9759 int standardIndex = 0;
9760 NSArray *standard = [self defaultStartPages];
9767 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9768 if (valid && closed != nil) {
9769 NSTimeInterval interval([closed timeIntervalSinceNow]);
9770 // XXX: Is 15 minutes the optimal time here?
9771 if (interval > 0 && interval <= -(15*60))
9775 if (valid && [saved count] != [standard count])
9779 for (unsigned int i = 0; i < [standard count]; i++) {
9780 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9781 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9782 // but it's good enough for now.
9783 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9790 NSArray *items = nil;
9792 [tabbar_ setSelectedIndex:savedIndex];
9795 [tabbar_ setSelectedIndex:standardIndex];
9799 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9800 NSArray *stack = [items objectAtIndex:tab];
9801 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9802 NSMutableArray *current = [NSMutableArray array];
9804 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9805 NSString *addr = [stack objectAtIndex:nav];
9806 NSURL *url = [NSURL URLWithString:addr];
9807 CyteViewController *page = [self pageForURL:url forExternal:NO];
9809 [current addObject:page];
9812 [navigation setViewControllers:current];
9815 // (Try to) show the startup URL.
9816 if (starturl_ != nil) {
9817 [self openCydiaURL:starturl_ forExternal:NO];
9822 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9823 if (item != nil && IsWildcat_) {
9824 [sheet showFromBarButtonItem:item animated:YES];
9826 [sheet showInView:window_];
9830 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9831 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9832 [progress setTitle:task];
9833 [progress addProgressEvent:event];
9836 - (void) addProgressEventForTask:(NSArray *)data {
9837 CydiaProgressEvent *event([data objectAtIndex:0]);
9838 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9839 [self addProgressEvent:event forTask:task];
9842 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9843 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9849 id Alloc_(id self, SEL selector) {
9850 id object = alloc_(self, selector);
9851 lprintf("[%s]A-%p\n", self->isa->name, object);
9856 id Dealloc_(id self, SEL selector) {
9857 id object = dealloc_(self, selector);
9858 lprintf("[%s]D-%p\n", self->isa->name, object);
9862 Class $WebDefaultUIKitDelegate;
9864 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9865 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9866 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9867 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9870 static NSSet *MobilizedFiles_;
9872 static NSURL *MobilizeURL(NSURL *url) {
9873 NSString *path([url path]);
9874 if ([path hasPrefix:@"/var/root/"]) {
9875 NSString *file([path substringFromIndex:10]);
9876 if ([MobilizedFiles_ containsObject:file])
9877 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9883 Class $CFXPreferencesPropertyListSource;
9884 @class CFXPreferencesPropertyListSource;
9886 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9887 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9888 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9889 url = MobilizeURL(url);
9890 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9891 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9897 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9898 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9899 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9900 url = MobilizeURL(url);
9901 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9902 //NSLog(@"%@ %@", [url absoluteString], value);
9908 Class $NSURLConnection;
9910 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9911 NSMutableURLRequest *copy([request mutableCopy]);
9913 NSURL *url([copy URL]);
9915 NSString *href([url absoluteString]);
9916 NSString *host([url host]);
9917 NSString *scheme([[url scheme] lowercaseString]);
9919 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9921 @synchronized (HostConfig_) {
9922 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9923 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9924 [copy setHTTPShouldUsePipelining:YES];
9926 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9927 if ([control isEqualToString:@"max-age=0"])
9928 if ([CachedURLs_ containsObject:href]) {
9930 NSLog(@"~~~: %@", href);
9933 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9935 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9936 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9937 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9941 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9945 int main(int argc, char *argv[]) {
9946 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9950 UpdateExternalStatus(0);
9952 if (Class $UIDevice = objc_getClass("UIDevice")) {
9953 UIDevice *device([$UIDevice currentDevice]);
9954 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9958 UIScreen *screen([UIScreen mainScreen]);
9959 if ([screen respondsToSelector:@selector(scale)])
9960 ScreenScale_ = [screen scale];
9964 UIDevice *device([UIDevice currentDevice]);
9965 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9968 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9969 if (idiom == UIUserInterfaceIdiomPhone)
9971 else if (idiom == UIUserInterfaceIdiomPad)
9974 NSLog(@"unknown UIUserInterfaceIdiom!");
9977 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9979 HostConfig_ = [[[NSObject alloc] init] autorelease];
9980 @synchronized (HostConfig_) {
9981 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9982 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9983 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9984 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9985 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9988 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9990 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9992 MobilizedFiles_ = [NSMutableSet setWithObjects:
9993 @"Library/Preferences/com.apple.Accessibility.plist",
9994 @"Library/Preferences/com.apple.preferences.sounds.plist",
9997 /* Library Hacks {{{ */
9998 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10000 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10002 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10003 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10004 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10005 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10008 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10009 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10010 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10011 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10014 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10015 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10016 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10017 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10018 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10021 $NSURLConnection = objc_getClass("NSURLConnection");
10022 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10023 if (NSURLConnection$init$ != NULL) {
10024 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10025 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10028 /* Set Locale {{{ */
10029 Locale_ = CFLocaleCopyCurrent();
10030 Languages_ = [NSLocale preferredLanguages];
10032 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10033 //NSLog(@"%@", [Languages_ description]);
10036 if (Locale_ != NULL)
10037 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10038 else if (Languages_ != nil && [Languages_ count] != 0)
10039 lang = [[Languages_ objectAtIndex:0] UTF8String];
10041 // XXX: consider just setting to C and then falling through?
10044 if (lang != NULL) {
10045 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10046 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10049 NSLog(@"Setting Language: %s", lang);
10051 if (lang != NULL) {
10052 setenv("LANG", lang, true);
10053 std::setlocale(LC_ALL, lang);
10057 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10059 /* Parse Arguments {{{ */
10060 bool substrate(false);
10066 for (int argi(1); argi != argc; ++argi)
10067 if (strcmp(argv[argi], "--") == 0) {
10069 argv[argi] = argv[0];
10075 for (int argi(1); argi != arge; ++argi)
10076 if (strcmp(args[argi], "--substrate") == 0)
10079 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10083 App_ = [[NSBundle mainBundle] bundlePath];
10089 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10090 alloc_ = alloc->method_imp;
10091 alloc->method_imp = (IMP) &Alloc_;*/
10093 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10094 dealloc_ = dealloc->method_imp;
10095 dealloc->method_imp = (IMP) &Dealloc_;*/
10097 /* System Information {{{ */
10101 size = sizeof(maxproc);
10102 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10103 perror("sysctlbyname(\"kern.maxproc\", ?)");
10104 else if (maxproc < 64) {
10106 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10107 perror("sysctlbyname(\"kern.maxproc\", #)");
10110 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10111 char *osversion = new char[size];
10112 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10113 perror("sysctlbyname(\"kern.osversion\", ?)");
10115 System_ = [NSString stringWithUTF8String:osversion];
10117 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10118 char *machine = new char[size];
10119 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10120 perror("sysctlbyname(\"hw.machine\", ?)");
10122 Machine_ = machine;
10124 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10125 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10126 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10128 UniqueID_ = [device uniqueIdentifier];
10130 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10131 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10132 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10134 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10135 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10136 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10138 if (mcc != NULL && mnc != NULL)
10139 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10146 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10147 Build_ = [system objectForKey:@"ProductBuildVersion"];
10148 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10149 Product_ = [info objectForKey:@"SafariProductVersion"];
10150 Safari_ = [info objectForKey:@"CFBundleVersion"];
10153 /* Load Database {{{ */
10155 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10157 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10159 if (Metadata_ == NULL)
10160 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10162 Settings_ = [Metadata_ objectForKey:@"Settings"];
10164 Packages_ = [Metadata_ objectForKey:@"Packages"];
10166 Values_ = [Metadata_ objectForKey:@"Values"];
10167 Sections_ = [Metadata_ objectForKey:@"Sections"];
10168 Sources_ = [Metadata_ objectForKey:@"Sources"];
10170 Token_ = [Metadata_ objectForKey:@"Token"];
10172 Version_ = [Metadata_ objectForKey:@"Version"];
10174 @synchronized (HostConfig_) {
10175 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10179 if (Settings_ != nil)
10180 Role_ = [Settings_ objectForKey:@"Role"];
10182 if (Values_ == nil) {
10183 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10184 [Metadata_ setObject:Values_ forKey:@"Values"];
10187 if (Sections_ == nil) {
10188 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10189 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10192 if (Sources_ == nil) {
10193 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10194 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10197 if (Version_ == nil) {
10198 Version_ = [NSNumber numberWithUnsignedInt:0];
10199 [Metadata_ setObject:Version_ forKey:@"Version"];
10202 @synchronized (HostConfig_) {
10203 if (CydiaSource_ == nil) {
10204 CydiaSource_ = @"apt.saurik.com";
10205 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10209 if ([Version_ unsignedIntValue] == 0) {
10210 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10211 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10212 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10213 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10215 Version_ = [NSNumber numberWithUnsignedInt:1];
10216 [Metadata_ setObject:Version_ forKey:@"Version"];
10225 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10228 if (Packages_ != nil) {
10230 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10234 [Metadata_ removeObjectForKey:@"Packages"];
10240 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10242 #define MobileSubstrate_(name) \
10243 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10244 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10245 if (handle == NULL) \
10246 NSLog(@"%s", dlerror()); \
10249 MobileSubstrate_(Activator)
10250 MobileSubstrate_(libstatusbar)
10251 MobileSubstrate_(SimulatedKeyEvents)
10252 MobileSubstrate_(WinterBoard)
10254 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10255 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10257 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10259 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10260 unlink("/tmp/.cydia.fw");
10262 } else if (access("/User", F_OK) != 0 || version < 4) {
10265 system("/usr/libexec/cydia/firmware.sh");
10269 _assert([[NSFileManager defaultManager]
10270 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10271 withIntermediateDirectories:YES
10276 if (access("/tmp/cydia.chk", F_OK) == 0) {
10277 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10278 _assert(errno == ENOENT);
10279 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10280 _assert(errno == ENOENT);
10283 /* APT Initialization {{{ */
10284 _assert(pkgInitConfig(*_config));
10285 _assert(pkgInitSystem(*_config, _system));
10288 _config->Set("APT::Acquire::Translation", lang);
10290 // XXX: this timeout might be important :(
10291 //_config->Set("Acquire::http::Timeout", 15);
10293 _config->Set("Acquire::http::MaxParallel", 3);
10295 /* Color Choices {{{ */
10296 space_ = CGColorSpaceCreateDeviceRGB();
10298 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10299 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10300 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10301 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10302 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10303 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10304 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10305 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10306 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10308 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10309 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10311 /* UIKit Configuration {{{ */
10312 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10313 if ($GSFontSetUseLegacyFontMetrics != NULL)
10314 $GSFontSetUseLegacyFontMetrics(YES);
10316 // XXX: I have a feeling this was important
10317 //UIKeyboardDisableAutomaticAppearance();
10320 Colon_ = UCLocalize("COLON_DELIMITED");
10321 Elision_ = UCLocalize("ELISION");
10322 Error_ = UCLocalize("ERROR");
10323 Warning_ = UCLocalize("WARNING");
10326 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10328 CGColorSpaceRelease(space_);
10329 CFRelease(Locale_);