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 "Menes/Menes.h"
125 #include "CyteKit/PerlCompatibleRegEx.hpp"
126 #include "CyteKit/WebScriptObject-Cyte.h"
127 #include "CyteKit/WebViewController.h"
128 #include "CyteKit/stringWithUTF8Bytes.h"
130 #include "Cydia/ProgressEvent.h"
132 #include "SDURLCache/SDURLCache.h"
134 #include <CydiaSubstrate/CydiaSubstrate.h>
141 #define _timestamp ({ \
143 gettimeofday(&tv, NULL); \
144 tv.tv_sec * 1000000 + tv.tv_usec; \
147 typedef std::vector<class ProfileTime *> TimeList;
157 ProfileTime(const char *name) :
161 times_.push_back(this);
164 void AddTime(uint64_t time) {
171 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
183 ProfileTimer(ProfileTime &time) :
190 time_.AddTime(_timestamp - start_);
195 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
197 std::cerr << "========" << std::endl;
200 #define _profile(name) { \
201 static ProfileTime name(#name); \
202 ProfileTimer _ ## name(name);
207 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
209 #define CYPoolStart() \
210 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
212 #define CYPoolEnd() \
216 #define Cydia_ CYDIA_VERSION
218 #define lprintf(args...) fprintf(stderr, args)
221 #define TraceLogging (1 && !ForRelease)
222 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
223 #define ProfileTimes (0 && !ForRelease)
224 #define ForSaurik (0 && !ForRelease)
225 #define LogBrowser (0 && !ForRelease)
226 #define TrackResize (0 && !ForRelease)
227 #define ManualRefresh (1 && !ForRelease)
228 #define ShowInternals (0 && !ForRelease)
229 #define AlwaysReload (0 && !ForRelease)
230 #define TryIndexedCollation (0 && !ForRelease)
234 #define _trace(args...)
239 #define _profile(name) {
242 #define PrintTimes() do {} while (false)
245 // Hash Functions/Structures {{{
246 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
254 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
256 static _finline NSString *CydiaURL(NSString *path) {
258 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
259 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
260 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
261 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
262 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
264 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
267 static _finline void UpdateExternalStatus(uint64_t newStatus) {
269 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
270 notify_set_state(notify_token, newStatus);
271 notify_cancel(notify_token);
273 notify_post("com.saurik.Cydia.status");
276 /* NSForcedOrderingSearch doesn't work on the iPhone */
277 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
278 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
279 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
282 typedef uint32_t (*SKRadixFunction)(id, void *);
284 @interface NSMutableArray (Radix)
285 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
293 @implementation NSMutableArray (Radix)
295 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
296 size_t count([self count]);
297 struct RadixItem_ *swap(new RadixItem_[count * 2]);
299 for (size_t i(0); i != count; ++i) {
300 RadixItem_ &item(swap[i]);
303 id object([self objectAtIndex:i]);
304 item.key = function(object, argument);
307 struct RadixItem_ *lhs(swap), *rhs(swap + count);
309 static const size_t width = 32;
310 static const size_t bits = 11;
311 static const size_t slots = 1 << bits;
312 static const size_t passes = (width + (bits - 1)) / bits;
314 size_t *hist(new size_t[slots]);
316 for (size_t pass(0); pass != passes; ++pass) {
317 memset(hist, 0, sizeof(size_t) * slots);
319 for (size_t i(0); i != count; ++i) {
320 uint32_t key(lhs[i].key);
322 key &= _not(uint32_t) >> width - bits;
327 for (size_t i(0); i != slots; ++i) {
328 size_t local(offset);
333 for (size_t i(0); i != count; ++i) {
334 uint32_t key(lhs[i].key);
336 key &= _not(uint32_t) >> width - bits;
337 rhs[hist[key]++] = lhs[i];
340 RadixItem_ *tmp(lhs);
347 const void **values(new const void *[count]);
348 for (size_t i(0); i != count; ++i)
349 values[i] = [self objectAtIndex:lhs[i].index];
350 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
358 /* Insertion Sort {{{ */
360 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
361 const char *ptr = (const char *)list;
363 CFIndex half = count / 2;
364 const char *probe = ptr + elementSize * half;
365 CFComparisonResult cr = comparator(element, probe, context);
366 if (0 == cr) return (probe - (const char *)list) / elementSize;
367 ptr = (cr < 0) ? ptr : probe + elementSize;
368 count = (cr < 0) ? half : (half + (count & 1) - 1);
370 return (ptr - (const char *)list) / elementSize;
373 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
374 const char *ptr = (const char *)list;
376 CFIndex half = count / 2;
377 const char *probe = ptr + elementSize * half;
378 CFComparisonResult cr = comparator(element, probe, context);
379 if (0 == cr) return (probe - (const char *)list) / elementSize;
380 ptr = (cr < 0) ? ptr : probe + elementSize;
381 count = (cr < 0) ? half : (half + (count & 1) - 1);
383 return (ptr - (const char *)list) / elementSize;
386 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
387 if (range.length == 0)
389 const void **values(new const void *[range.length]);
390 CFArrayGetValues(array, range, values);
392 #if HistogramInsertionSort > 0
393 uint32_t total(0), *offsets(new uint32_t[range.length]);
396 for (CFIndex index(1); index != range.length; ++index) {
397 const void *value(values[index]);
398 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
399 CFIndex correct(index);
400 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
401 #if HistogramInsertionSort > 1
402 NSLog(@"%@ < %@", value, values[correct - 1]);
407 if (correct != index) {
408 size_t offset(index - correct);
409 #if HistogramInsertionSort
413 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
415 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
416 values[correct] = value;
420 CFArrayReplaceValues(array, range, values, range.length);
423 #if HistogramInsertionSort > 0
424 for (CFIndex index(0); index != range.length; ++index)
425 if (offsets[index] != 0)
426 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
427 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
434 /* Apple Bug Fixes {{{ */
435 @implementation UIWebDocumentView (Cydia)
437 - (void) _setScrollerOffset:(CGPoint)offset {
438 UIScroller *scroller([self _scroller]);
440 CGSize size([scroller contentSize]);
441 CGSize bounds([scroller bounds].size);
444 max.x = size.width - bounds.width;
445 max.y = size.height - bounds.height;
453 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
454 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
456 [scroller setOffset:offset];
462 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
463 size_t length([self length] - state->state);
466 else if (length > count)
468 for (size_t i(0); i != length; ++i)
469 objects[i] = [self item:state->state++];
470 state->itemsPtr = objects;
471 state->mutationsPtr = (unsigned long *) self;
475 /* Cydia NSString Additions {{{ */
476 @interface NSString (Cydia)
477 - (NSComparisonResult) compareByPath:(NSString *)other;
478 - (NSString *) stringByCachingURLWithCurrentCDN;
479 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
482 @implementation NSString (Cydia)
484 - (NSComparisonResult) compareByPath:(NSString *)other {
485 NSString *prefix = [self commonPrefixWithString:other options:0];
486 size_t length = [prefix length];
488 NSRange lrange = NSMakeRange(length, [self length] - length);
489 NSRange rrange = NSMakeRange(length, [other length] - length);
491 lrange = [self rangeOfString:@"/" options:0 range:lrange];
492 rrange = [other rangeOfString:@"/" options:0 range:rrange];
494 NSComparisonResult value;
496 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
497 value = NSOrderedSame;
498 else if (lrange.location == NSNotFound)
499 value = NSOrderedAscending;
500 else if (rrange.location == NSNotFound)
501 value = NSOrderedDescending;
503 value = NSOrderedSame;
505 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
506 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
507 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
508 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
510 NSComparisonResult result = [lpath compare:rpath];
511 return result == NSOrderedSame ? value : result;
514 - (NSString *) stringByCachingURLWithCurrentCDN {
516 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
517 withString:@"://cache.cydia.saurik.com/"
521 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
522 return [(id)CFURLCreateStringByAddingPercentEscapes(
527 kCFStringEncodingUTF8
534 /* C++ NSString Wrapper Cache {{{ */
535 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
536 return size == 0 ? NULL :
537 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
538 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
541 static _finline CFStringRef CYStringCreate(const char *data) {
542 return CYStringCreate(data, strlen(data));
551 _finline void clear_() {
552 if (cache_ != NULL) {
559 _finline bool empty() const {
563 _finline size_t size() const {
567 _finline char *data() const {
571 _finline void clear() {
576 _finline CYString() :
583 _finline ~CYString() {
587 void operator =(const CYString &rhs) {
591 if (rhs.cache_ == nil)
594 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
597 void copy(apr_pool_t *pool) {
598 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
599 memcpy(temp, data_, size_);
604 void set(apr_pool_t *pool, const char *data, size_t size) {
610 data_ = const_cast<char *>(data);
618 _finline void set(apr_pool_t *pool, const char *data) {
619 set(pool, data, data == NULL ? 0 : strlen(data));
622 _finline void set(apr_pool_t *pool, const std::string &rhs) {
623 set(pool, rhs.data(), rhs.size());
626 bool operator ==(const CYString &rhs) const {
627 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
630 _finline operator CFStringRef() {
632 cache_ = CYStringCreate(data_, size_);
636 _finline operator id() {
637 return (NSString *) static_cast<CFStringRef>(*this);
640 _finline operator const char *() {
641 return reinterpret_cast<const char *>(data_);
645 /* C++ NSString Algorithm Adapters {{{ */
647 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
650 struct NSStringMapHash :
651 std::unary_function<NSString *, size_t>
653 _finline size_t operator ()(NSString *value) const {
654 return CFStringHashNSString((CFStringRef) value);
658 struct NSStringMapLess :
659 std::binary_function<NSString *, NSString *, bool>
661 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
662 return [lhs compare:rhs] == NSOrderedAscending;
666 struct NSStringMapEqual :
667 std::binary_function<NSString *, NSString *, bool>
669 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
670 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
671 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
672 //[lhs isEqualToString:rhs];
677 /* Mime Addresses {{{ */
678 @interface Address : NSObject {
680 _H<NSString> address_;
684 - (NSString *) address;
686 - (void) setAddress:(NSString *)address;
688 + (Address *) addressWithString:(NSString *)string;
689 - (Address *) initWithString:(NSString *)string;
693 @implementation Address
695 - (NSString *) name {
699 - (NSString *) address {
703 - (void) setAddress:(NSString *)address {
707 + (Address *) addressWithString:(NSString *)string {
708 return [[[Address alloc] initWithString:string] autorelease];
711 + (NSArray *) _attributeKeys {
712 return [NSArray arrayWithObjects:
718 - (NSArray *) attributeKeys {
719 return [[self class] _attributeKeys];
722 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
723 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
726 - (Address *) initWithString:(NSString *)string {
727 if ((self = [super init]) != nil) {
728 const char *data = [string UTF8String];
729 size_t size = [string length];
731 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
733 if (address_r(data, size)) {
734 name_ = address_r[1];
735 address_ = address_r[2];
745 /* CoreGraphics Primitives {{{ */
750 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
751 CGFloat color[] = {red, green, blue, alpha};
752 return CGColorCreate(space, color);
761 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
762 color_(Create_(space, red, green, blue, alpha))
764 Set(space, red, green, blue, alpha);
769 CGColorRelease(color_);
776 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
778 color_ = Create_(space, red, green, blue, alpha);
781 operator CGColorRef() {
787 /* Random Global Variables {{{ */
788 static const int PulseInterval_ = 50000;
790 static const NSString *UI_;
793 static bool RestartSubstrate_;
794 static NSArray *Finishes_;
796 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
797 #define NotifyConfig_ "/etc/notify.conf"
799 static bool Queuing_;
801 static CYColor Blue_;
802 static CYColor Blueish_;
803 static CYColor Black_;
805 static CYColor White_;
806 static CYColor Gray_;
807 static CYColor Green_;
808 static CYColor Purple_;
809 static CYColor Purplish_;
811 static UIColor *InstallingColor_;
812 static UIColor *RemovingColor_;
814 static NSString *App_;
816 static BOOL Advanced_;
817 static BOOL Ignored_;
819 static _H<UIFont> Font12_;
820 static _H<UIFont> Font12Bold_;
821 static _H<UIFont> Font14_;
822 static _H<UIFont> Font18Bold_;
823 static _H<UIFont> Font22Bold_;
825 static const char *Machine_ = NULL;
826 static NSString *System_ = nil;
827 static NSString *SerialNumber_ = nil;
828 static NSString *ChipID_ = nil;
829 static NSString *BBSNum_ = nil;
830 static _H<NSString> Token_;
831 static NSString *UniqueID_ = nil;
832 static NSString *PLMN_ = nil;
833 static NSString *Build_ = nil;
834 static NSString *Product_ = nil;
835 static NSString *Safari_ = nil;
837 static CFLocaleRef Locale_;
838 static NSArray *Languages_;
839 static CGColorSpaceRef space_;
841 static NSDictionary *SectionMap_;
842 static NSMutableDictionary *Metadata_;
843 static _transient NSMutableDictionary *Settings_;
844 static _transient NSString *Role_;
845 static _transient NSMutableDictionary *Packages_;
846 static _transient NSMutableDictionary *Sections_;
847 static _transient NSMutableDictionary *Sources_;
848 static bool Changed_;
852 static CGFloat ScreenScale_;
853 static NSString *Idiom_;
855 static _H<NSMutableDictionary> SessionData_;
856 static _H<NSObject> HostConfig_;
857 static _H<NSMutableSet> BridgedHosts_;
858 static _H<NSMutableSet> PipelinedHosts_;
860 static NSString *kCydiaProgressEventTypeError = @"Error";
861 static NSString *kCydiaProgressEventTypeInformation = @"Information";
862 static NSString *kCydiaProgressEventTypeStatus = @"Status";
863 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
866 /* Display Helpers {{{ */
867 inline float Interpolate(float begin, float end, float fraction) {
868 return (end - begin) * fraction + begin;
871 static _finline const char *StripVersion_(const char *version) {
872 const char *colon(strchr(version, ':'));
873 return colon == NULL ? version : colon + 1;
876 NSString *LocalizeSection(NSString *section) {
877 static Pcre title_r("^(.*?) \\((.*)\\)$");
878 if (title_r(section)) {
879 NSString *parent(title_r[1]);
880 NSString *child(title_r[2]);
882 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
883 LocalizeSection(parent),
884 LocalizeSection(child)
888 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
891 NSString *Simplify(NSString *title) {
892 const char *data = [title UTF8String];
893 size_t size = [title length];
895 static Pcre square_r("^\\[(.*)\\]$");
896 if (square_r(data, size))
897 return Simplify(square_r[1]);
899 static Pcre paren_r("^\\((.*)\\)$");
900 if (paren_r(data, size))
901 return Simplify(paren_r[1]);
903 static Pcre title_r("^(.*?) \\((.*)\\)$");
904 if (title_r(data, size))
905 return Simplify(title_r[1]);
911 NSString *GetLastUpdate() {
912 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
915 return UCLocalize("NEVER_OR_UNKNOWN");
917 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
918 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
920 CFRelease(formatter);
922 return [(NSString *) formatted autorelease];
925 bool isSectionVisible(NSString *section) {
926 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
927 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
928 return hidden == nil || ![hidden boolValue];
931 static id CYIOGetValue(const char *path, NSString *property) {
932 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
933 if (entry == MACH_PORT_NULL)
936 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
937 IOObjectRelease(entry);
941 return [(id) value autorelease];
944 static NSString *CYHex(NSData *data, bool reverse, bool capital) {
948 size_t length([data length]);
949 uint8_t bytes[length];
950 [data getBytes:bytes];
952 char string[length * 2 + 1];
953 for (size_t i(0); i != length; ++i)
954 sprintf(string + i * 2, capital ? "%.2X" : "%.2x", bytes[reverse ? length - i - 1 : i]);
956 return [NSString stringWithUTF8String:string];
961 /* Delegate Prototypes {{{ */
964 @class CydiaProgressEvent;
966 @protocol DatabaseDelegate
967 - (void) repairWithSelector:(SEL)selector;
968 - (void) setConfigurationData:(NSString *)data;
969 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
972 @class CYPackageController;
974 @protocol CydiaDelegate
975 - (void) retainNetworkActivityIndicator;
976 - (void) releaseNetworkActivityIndicator;
977 - (void) clearPackage:(Package *)package;
978 - (void) installPackage:(Package *)package;
979 - (void) installPackages:(NSArray *)packages;
980 - (void) removePackage:(Package *)package;
981 - (void) beginUpdate;
983 - (void) distUpgrade;
987 - (void) addTrivialSource:(NSString *)href;
988 - (void) showSettings;
989 - (UIProgressHUD *) addProgressHUD;
990 - (void) removeProgressHUD:(UIProgressHUD *)hud;
991 - (CyteViewController *) pageForPackage:(NSString *)name;
992 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
993 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
997 /* Status Delegation {{{ */
999 public pkgAcquireStatus
1002 _transient NSObject<ProgressDelegate> *delegate_;
1012 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1013 delegate_ = delegate;
1016 NSObject<ProgressDelegate> *getDelegate() const {
1020 virtual bool MediaChange(std::string media, std::string drive) {
1024 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1027 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1028 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1029 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1030 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1033 virtual void Done(pkgAcquire::ItemDesc &item) {
1036 virtual void Fail(pkgAcquire::ItemDesc &item) {
1038 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1039 item.Owner->Status == pkgAcquire::Item::StatDone
1043 std::string &error(item.Owner->ErrorText);
1047 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1048 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1051 virtual bool Pulse(pkgAcquire *Owner) {
1052 bool value = pkgAcquireStatus::Pulse(Owner);
1055 double(CurrentBytes + CurrentItems) /
1056 double(TotalBytes + TotalItems)
1059 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1060 [NSNumber numberWithDouble:percent], @"Percent",
1062 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1063 [NSNumber numberWithDouble:TotalBytes], @"Total",
1064 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1065 nil] waitUntilDone:YES];
1067 if (value && ![delegate_ isProgressCancelled])
1075 _finline bool WasCancelled() const {
1079 virtual void Start() {
1080 pkgAcquireStatus::Start();
1081 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1084 virtual void Stop() {
1085 pkgAcquireStatus::Stop();
1086 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1087 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1091 /* Database Interface {{{ */
1092 typedef std::map< unsigned long, _H<Source> > SourceMap;
1094 @interface Database : NSObject {
1100 pkgCacheFile cache_;
1101 pkgDepCache::Policy *policy_;
1102 pkgRecords *records_;
1103 pkgProblemResolver *resolver_;
1104 pkgAcquire *fetcher_;
1106 SPtr<pkgPackageManager> manager_;
1107 pkgSourceList *list_;
1109 SourceMap sourceMap_;
1110 _H<NSMutableArray> sourceList_;
1112 CFMutableArrayRef packages_;
1114 _transient NSObject<DatabaseDelegate> *delegate_;
1115 _transient NSObject<ProgressDelegate> *progress_;
1123 std::map<const char *, _H<NSString> > sections_;
1126 + (Database *) sharedInstance;
1129 - (void) _readCydia:(NSNumber *)fd;
1130 - (void) _readStatus:(NSNumber *)fd;
1131 - (void) _readOutput:(NSNumber *)fd;
1135 - (Package *) packageWithName:(NSString *)name;
1137 - (pkgCacheFile &) cache;
1138 - (pkgDepCache::Policy *) policy;
1139 - (pkgRecords *) records;
1140 - (pkgProblemResolver *) resolver;
1141 - (pkgAcquire &) fetcher;
1142 - (pkgSourceList &) list;
1143 - (NSArray *) packages;
1144 - (NSArray *) sources;
1145 - (Source *) sourceWithKey:(NSString *)key;
1146 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1154 - (void) updateWithStatus:(Status &)status;
1156 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1158 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1159 - (NSObject<ProgressDelegate> *) progressDelegate;
1161 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1163 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1167 /* ProgressEvent Implementation {{{ */
1168 @implementation CydiaProgressEvent
1170 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1171 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1174 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1175 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1176 [event setPackage:package];
1180 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1181 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1183 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1184 NSArray *fields([description componentsSeparatedByString:@" "]);
1185 [event setItem:fields];
1187 if ([fields count] > 3) {
1188 [event setPackage:[fields objectAtIndex:2]];
1189 [event setVersion:[fields objectAtIndex:3]];
1192 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1197 + (NSArray *) _attributeKeys {
1198 return [NSArray arrayWithObjects:
1208 - (NSArray *) attributeKeys {
1209 return [[self class] _attributeKeys];
1212 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1213 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1216 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1217 if ((self = [super init]) != nil) {
1223 - (NSString *) message {
1227 - (NSString *) type {
1231 - (NSArray *) item {
1232 return (id) item_ ?: [NSNull null];
1235 - (void) setItem:(NSArray *)item {
1239 - (NSString *) package {
1240 return (id) package_ ?: [NSNull null];
1243 - (void) setPackage:(NSString *)package {
1247 - (NSString *) url {
1248 return (id) url_ ?: [NSNull null];
1251 - (void) setURL:(NSString *)url {
1255 - (void) setVersion:(NSString *)version {
1259 - (NSString *) version {
1260 return (id) version_ ?: [NSNull null];
1263 - (NSString *) compound:(NSString *)value {
1265 NSString *mode(nil); {
1266 NSString *type([self type]);
1267 if ([type isEqualToString:kCydiaProgressEventTypeError])
1268 mode = UCLocalize("ERROR");
1269 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1270 mode = UCLocalize("WARNING");
1274 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1280 - (NSString *) compoundMessage {
1281 return [self compound:[self message]];
1284 - (NSString *) compoundTitle {
1287 if (package_ == nil)
1289 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1290 title = [package name];
1294 return [self compound:title];
1300 // Cytore Definitions {{{
1301 struct PackageValue :
1304 Cytore::Offset<PackageValue> next_;
1306 uint32_t index_ : 23;
1307 uint32_t subscribed_ : 1;
1324 Cytore::Offset<PackageValue> packages_[1 << 16];
1327 static Cytore::File<MetaValue> MetaFile_;
1329 // Cytore Helper Functions {{{
1330 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1331 SplitHash nhash = { hashlittle(name, length) };
1333 PackageValue *metadata;
1335 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1336 offset: if (offset->IsNull()) {
1337 *offset = MetaFile_.New<PackageValue>(length + 1);
1338 metadata = &MetaFile_.Get(*offset);
1340 if (metadata == NULL) {
1344 metadata = new PackageValue();
1345 memset(metadata, 0, sizeof(*metadata));
1348 memcpy(metadata->name_, name, length + 1);
1349 metadata->nhash_ = nhash.u16[1];
1351 metadata = &MetaFile_.Get(*offset);
1353 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1354 offset = &metadata->next_;
1362 static void PackageImport(const void *key, const void *value, void *context) {
1363 bool &fail(*reinterpret_cast<bool *>(context));
1366 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1367 NSLog(@"failed to import package %@", key);
1371 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1372 NSDictionary *package((NSDictionary *) value);
1374 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1375 if ([subscribed boolValue] && !metadata->subscribed_)
1376 metadata->subscribed_ = true;
1378 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1379 time_t time([date timeIntervalSince1970]);
1380 if (metadata->first_ > time || metadata->first_ == 0)
1381 metadata->first_ = time;
1384 NSDate *date([package objectForKey:@"LastSeen"]);
1385 NSString *version([package objectForKey:@"LastVersion"]);
1387 if (date != nil && version != nil) {
1388 time_t time([date timeIntervalSince1970]);
1389 if (metadata->last_ < time || metadata->last_ == 0)
1390 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1391 size_t length(strlen(buffer));
1392 uint16_t vhash(hashlittle(buffer, length));
1394 size_t capped(std::min<size_t>(8, length));
1395 char *latest(buffer + length - capped);
1397 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1398 metadata->vhash_ = vhash;
1400 metadata->last_ = time;
1406 /* Source Class {{{ */
1407 @interface Source : NSObject {
1408 CYString depiction_;
1409 CYString description_;
1415 CYString distribution_;
1420 _H<NSString> authority_;
1422 CYString defaultIcon_;
1424 _H<NSDictionary> record_;
1428 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1430 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1432 - (NSString *) depictionForPackage:(NSString *)package;
1433 - (NSString *) supportForPackage:(NSString *)package;
1435 - (NSDictionary *) record;
1439 - (NSString *) distribution;
1440 - (NSString *) type;
1442 - (NSString *) host;
1444 - (NSString *) name;
1445 - (NSString *) shortDescription;
1446 - (NSString *) label;
1447 - (NSString *) origin;
1448 - (NSString *) version;
1450 - (NSString *) defaultIcon;
1454 @implementation Source
1458 distribution_.clear();
1461 description_.clear();
1467 defaultIcon_.clear();
1474 + (NSArray *) _attributeKeys {
1475 return [NSArray arrayWithObjects:
1482 @"shortDescription",
1490 - (NSArray *) attributeKeys {
1491 return [[self class] _attributeKeys];
1494 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1495 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1498 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1501 trusted_ = index->IsTrusted();
1503 uri_.set(pool, index->GetURI());
1504 distribution_.set(pool, index->GetDist());
1505 type_.set(pool, index->GetType());
1507 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1508 if (dindex != NULL) {
1510 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1513 pkgTagFile tags(&fd);
1515 pkgTagSection section;
1522 {"default-icon", &defaultIcon_},
1523 {"depiction", &depiction_},
1524 {"description", &description_},
1526 {"origin", &origin_},
1527 {"support", &support_},
1528 {"version", &version_},
1531 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1532 const char *start, *end;
1534 if (section.Find(names[i].name_, start, end)) {
1535 CYString &value(*names[i].value_);
1536 value.set(pool, start, end - start);
1542 record_ = [Sources_ objectForKey:[self key]];
1544 NSURL *url([NSURL URLWithString:uri_]);
1548 host_ = [host_ lowercaseString];
1551 // XXX: this is due to a bug in _H<>
1552 authority_ = (id) host_;
1554 authority_ = [url path];
1557 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1558 if ((self = [super init]) != nil) {
1559 [self setMetaIndex:index inPool:pool];
1563 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1564 NSDictionary *lhr = [self record];
1565 NSDictionary *rhr = [source record];
1568 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1570 NSString *lhs = [self name];
1571 NSString *rhs = [source name];
1573 if ([lhs length] != 0 && [rhs length] != 0) {
1574 unichar lhc = [lhs characterAtIndex:0];
1575 unichar rhc = [rhs characterAtIndex:0];
1577 if (isalpha(lhc) && !isalpha(rhc))
1578 return NSOrderedAscending;
1579 else if (!isalpha(lhc) && isalpha(rhc))
1580 return NSOrderedDescending;
1583 return [lhs compare:rhs options:LaxCompareOptions_];
1586 - (NSString *) depictionForPackage:(NSString *)package {
1587 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1590 - (NSString *) supportForPackage:(NSString *)package {
1591 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1594 - (NSDictionary *) record {
1602 - (NSString *) uri {
1606 - (NSString *) distribution {
1607 return distribution_;
1610 - (NSString *) type {
1614 - (NSString *) key {
1615 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1618 - (NSString *) host {
1622 - (NSString *) name {
1623 return origin_.empty() ? (id) authority_ : origin_;
1626 - (NSString *) shortDescription {
1627 return description_;
1630 - (NSString *) label {
1631 return label_.empty() ? (id) authority_ : label_;
1634 - (NSString *) origin {
1638 - (NSString *) version {
1642 - (NSString *) defaultIcon {
1643 return defaultIcon_;
1648 /* CydiaOperation Class {{{ */
1649 @interface CydiaOperation : NSObject {
1650 _H<NSString> operator_;
1651 _H<NSString> value_;
1654 - (NSString *) operator;
1655 - (NSString *) value;
1659 @implementation CydiaOperation
1661 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1662 if ((self = [super init]) != nil) {
1663 operator_ = [NSString stringWithUTF8String:_operator];
1664 value_ = [NSString stringWithUTF8String:value];
1668 + (NSArray *) _attributeKeys {
1669 return [NSArray arrayWithObjects:
1675 - (NSArray *) attributeKeys {
1676 return [[self class] _attributeKeys];
1679 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1680 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1683 - (NSString *) operator {
1687 - (NSString *) value {
1693 /* CydiaClause Class {{{ */
1694 @interface CydiaClause : NSObject {
1695 _H<NSString> package_;
1696 _H<CydiaOperation> version_;
1699 - (NSString *) package;
1700 - (CydiaOperation *) version;
1704 @implementation CydiaClause
1706 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1707 if ((self = [super init]) != nil) {
1708 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1710 if (const char *version = dep.TargetVer())
1711 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1713 version_ = (id) [NSNull null];
1717 + (NSArray *) _attributeKeys {
1718 return [NSArray arrayWithObjects:
1724 - (NSArray *) attributeKeys {
1725 return [[self class] _attributeKeys];
1728 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1729 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1732 - (NSString *) package {
1736 - (CydiaOperation *) version {
1742 /* CydiaRelation Class {{{ */
1743 @interface CydiaRelation : NSObject {
1744 _H<NSString> relationship_;
1745 _H<NSMutableArray> clauses_;
1748 - (NSString *) relationship;
1749 - (NSArray *) clauses;
1753 @implementation CydiaRelation
1755 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1756 if ((self = [super init]) != nil) {
1757 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1758 clauses_ = [NSMutableArray arrayWithCapacity:8];
1760 pkgCache::DepIterator start;
1761 pkgCache::DepIterator end;
1762 dep.GlobOr(start, end); // ++dep
1765 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1767 // yes, seriously. (wtf?)
1775 + (NSArray *) _attributeKeys {
1776 return [NSArray arrayWithObjects:
1782 - (NSArray *) attributeKeys {
1783 return [[self class] _attributeKeys];
1786 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1787 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1790 - (NSString *) relationship {
1791 return relationship_;
1794 - (NSArray *) clauses {
1798 - (void) addClause:(CydiaClause *)clause {
1799 [clauses_ addObject:clause];
1804 /* Package Class {{{ */
1805 struct ParsedPackage {
1810 CYString depiction_;
1820 @interface Package : NSObject {
1823 uint32_t essential_ : 1;
1824 uint32_t obsolete_ : 1;
1825 uint32_t ignored_ : 1;
1829 _transient Database *database_;
1831 pkgCache::VerIterator version_;
1832 pkgCache::PkgIterator iterator_;
1833 pkgCache::VerFileIterator file_;
1839 CYString installed_;
1841 const char *section_;
1842 _transient NSString *section$_;
1846 PackageValue *metadata_;
1847 ParsedPackage *parsed_;
1849 _H<NSMutableArray> tags_;
1852 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1853 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1855 - (pkgCache::PkgIterator) iterator;
1858 - (NSString *) section;
1859 - (NSString *) simpleSection;
1861 - (NSString *) longSection;
1862 - (NSString *) shortSection;
1866 - (Address *) maintainer;
1868 - (NSString *) longDescription;
1869 - (NSString *) shortDescription;
1872 - (PackageValue *) metadata;
1875 - (bool) subscribed;
1876 - (bool) setSubscribed:(bool)subscribed;
1880 - (NSString *) latest;
1881 - (NSString *) installed;
1882 - (BOOL) uninstalled;
1885 - (BOOL) upgradableAndEssential:(BOOL)essential;
1888 - (BOOL) unfiltered;
1892 - (BOOL) halfConfigured;
1893 - (BOOL) halfInstalled;
1895 - (NSString *) mode;
1898 - (NSString *) name;
1900 - (NSString *) homepage;
1901 - (NSString *) depiction;
1902 - (Address *) author;
1904 - (NSString *) support;
1906 - (NSArray *) files;
1907 - (NSArray *) warnings;
1908 - (NSArray *) applications;
1910 - (Source *) source;
1912 - (BOOL) matches:(NSString *)text;
1914 - (bool) hasSupportingRole;
1915 - (BOOL) hasTag:(NSString *)tag;
1916 - (NSString *) primaryPurpose;
1917 - (NSArray *) purposes;
1918 - (bool) isCommercial;
1920 - (void) setIndex:(size_t)index;
1922 - (CYString &) cyname;
1924 - (uint32_t) compareBySection:(NSArray *)sections;
1929 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1930 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1931 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1932 - (bool) isVisibleInSection:(NSString *)section;
1933 - (bool) isVisibleInSource:(Source *)source;
1937 uint32_t PackageChangesRadix(Package *self, void *) {
1942 uint32_t timestamp : 30;
1943 uint32_t ignored : 1;
1944 uint32_t upgradable : 1;
1948 bool upgradable([self upgradableAndEssential:YES]);
1949 value.bits.upgradable = upgradable ? 1 : 0;
1952 value.bits.timestamp = 0;
1953 value.bits.ignored = [self ignored] ? 0 : 1;
1954 value.bits.upgradable = 1;
1956 value.bits.timestamp = [self seen] >> 2;
1957 value.bits.ignored = 0;
1958 value.bits.upgradable = 0;
1961 return _not(uint32_t) - value.key;
1964 uint32_t PackagePrefixRadix(Package *self, void *context) {
1965 size_t offset(reinterpret_cast<size_t>(context));
1966 CYString &name([self cyname]);
1968 size_t size(name.size());
1971 char *text(name.data());
1974 if (!isdigit(text[0]))
1978 while (size != digits && isdigit(text[digits]))
1986 if (offset == 0 && zeros != 0) {
1987 memset(data, '0', zeros);
1988 memcpy(data + zeros, text, 4 - zeros);
1990 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1991 if (size <= offset - zeros)
1994 text += offset - zeros;
1995 size -= offset - zeros;
1998 memcpy(data, text, 4);
2000 memcpy(data, text, size);
2001 memset(data + size, 0, 4 - size);
2004 for (size_t i(0); i != 4; ++i)
2005 if (isalpha(data[i]))
2013 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2015 /* XXX: ntohl may be more honest */
2016 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2019 CYString &(*PackageName)(Package *self, SEL sel);
2021 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2022 _profile(PackageNameCompare)
2023 CYString &lhi(PackageName(lhs, @selector(cyname)));
2024 CYString &rhi(PackageName(rhs, @selector(cyname)));
2025 CFStringRef lhn(lhi), rhn(rhi);
2028 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2029 else if (rhn == NULL)
2030 return NSOrderedDescending;
2032 _profile(PackageNameCompare$NumbersLast)
2033 if (!lhi.empty() && !rhi.empty()) {
2034 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2035 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2036 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2037 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2038 return lha ? NSOrderedAscending : NSOrderedDescending;
2042 CFIndex length = CFStringGetLength(lhn);
2044 _profile(PackageNameCompare$Compare)
2045 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2050 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2051 return PackageNameCompare(*lhs, *rhs, context);
2054 struct PackageNameOrdering :
2055 std::binary_function<Package *, Package *, bool>
2057 _finline bool operator ()(Package *lhs, Package *rhs) const {
2058 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2062 @implementation Package
2064 - (NSString *) description {
2065 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2069 if (parsed_ != NULL)
2074 + (NSString *) webScriptNameForSelector:(SEL)selector {
2076 else if (selector == @selector(clear))
2078 else if (selector == @selector(getField:))
2080 else if (selector == @selector(hasTag:))
2082 else if (selector == @selector(install))
2084 else if (selector == @selector(remove))
2090 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2091 return [self webScriptNameForSelector:selector] == nil;
2094 + (NSArray *) _attributeKeys {
2095 return [NSArray arrayWithObjects:
2114 @"shortDescription",
2127 - (NSArray *) attributeKeys {
2128 return [[self class] _attributeKeys];
2131 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2132 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2135 - (NSArray *) relations {
2136 @synchronized (database_) {
2137 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2138 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2139 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2143 - (NSString *) getField:(NSString *)name {
2144 @synchronized (database_) {
2145 if ([database_ era] != era_ || file_.end())
2148 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2150 const char *start, *end;
2151 if (!parser.Find([name UTF8String], start, end))
2152 return (NSString *) [NSNull null];
2154 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2158 if (parsed_ != NULL)
2160 @synchronized (database_) {
2161 if ([database_ era] != era_ || file_.end())
2164 ParsedPackage *parsed(new ParsedPackage);
2167 _profile(Package$parse)
2168 pkgRecords::Parser *parser;
2170 _profile(Package$parse$Lookup)
2171 parser = &[database_ records]->Lookup(file_);
2176 _profile(Package$parse$Find)
2181 {"icon", &parsed->icon_},
2182 {"depiction", &parsed->depiction_},
2183 {"homepage", &parsed->homepage_},
2184 {"website", &website},
2185 {"bugs", &parsed->bugs_},
2186 {"support", &parsed->support_},
2187 {"sponsor", &parsed->sponsor_},
2188 {"author", &parsed->author_},
2191 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2192 const char *start, *end;
2194 if (parser->Find(names[i].name_, start, end)) {
2195 CYString &value(*names[i].value_);
2196 _profile(Package$parse$Value)
2197 value.set(pool_, start, end - start);
2203 _profile(Package$parse$Tagline)
2204 const char *start, *end;
2205 if (parser->ShortDesc(start, end)) {
2206 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2209 while (stop != start && stop[-1] == '\r')
2211 parsed->tagline_.set(pool_, start, stop - start);
2215 _profile(Package$parse$Retain)
2216 if (parsed->homepage_.empty())
2217 parsed->homepage_ = website;
2218 if (parsed->homepage_ == parsed->depiction_)
2219 parsed->homepage_.clear();
2224 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2225 if ((self = [super init]) != nil) {
2226 _profile(Package$initWithVersion)
2229 database_ = database;
2230 era_ = [database era];
2234 pkgCache::PkgIterator iterator(version.ParentPkg());
2235 iterator_ = iterator;
2237 _profile(Package$initWithVersion$Version)
2238 if (!version_.end())
2239 file_ = version_.FileList();
2241 pkgCache &cache([database_ cache]);
2242 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2246 _profile(Package$initWithVersion$Cache)
2247 name_.set(NULL, iterator.Display());
2249 latest_.set(NULL, StripVersion_(version_.VerStr()));
2251 pkgCache::VerIterator current(iterator.CurrentVer());
2253 installed_.set(NULL, StripVersion_(current.VerStr()));
2256 _profile(Package$initWithVersion$Tags)
2257 pkgCache::TagIterator tag(iterator.TagList());
2259 tags_ = [NSMutableArray arrayWithCapacity:8];
2261 const char *name(tag.Name());
2262 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2264 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2265 if (strcmp(name + 6, "enduser") == 0)
2267 else if (strcmp(name + 6, "hacker") == 0)
2269 else if (strcmp(name + 6, "developer") == 0)
2271 else if (strcmp(name + 6, "cydia") == 0)
2277 if (strncmp(name, "cydia::", 7) == 0) {
2278 if (strcmp(name + 7, "essential") == 0)
2280 else if (strcmp(name + 7, "obsolete") == 0)
2285 } while (!tag.end());
2289 _profile(Package$initWithVersion$Metadata)
2290 const char *mixed(iterator.Name());
2291 size_t size(strlen(mixed));
2292 char lower[size + 1];
2294 for (size_t i(0); i != size; ++i)
2295 lower[i] = mixed[i] | 0x20;
2298 PackageValue *metadata(PackageFind(lower, size));
2299 metadata_ = metadata;
2301 id_.set(NULL, metadata->name_, size);
2303 const char *latest(version_.VerStr());
2304 size_t length(strlen(latest));
2306 uint16_t vhash(hashlittle(latest, length));
2308 size_t capped(std::min<size_t>(8, length));
2309 latest = latest + length - capped;
2311 if (metadata->first_ == 0)
2312 metadata->first_ = now_;
2314 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2315 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2316 metadata->vhash_ = vhash;
2317 metadata->last_ = now_;
2318 } else if (metadata->last_ == 0)
2319 metadata->last_ = metadata->first_;
2322 _profile(Package$initWithVersion$Section)
2323 section_ = iterator.Section();
2326 _profile(Package$initWithVersion$Flags)
2327 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2328 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2333 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2334 pkgCache::VerIterator version;
2336 _profile(Package$packageWithIterator$GetCandidateVer)
2337 version = [database policy]->GetCandidateVer(iterator);
2345 _profile(Package$packageWithIterator$Allocate)
2346 package = [Package allocWithZone:zone];
2349 _profile(Package$packageWithIterator$Initialize)
2351 initWithVersion:version
2358 _profile(Package$packageWithIterator$Autorelease)
2359 package = [package autorelease];
2365 - (pkgCache::PkgIterator) iterator {
2369 - (NSString *) section {
2370 if (section$_ == nil) {
2371 if (section_ == NULL)
2374 _profile(Package$section$mappedSectionForPointer)
2375 section$_ = [database_ mappedSectionForPointer:section_];
2380 - (NSString *) simpleSection {
2381 if (NSString *section = [self section])
2382 return Simplify(section);
2387 - (NSString *) longSection {
2388 return LocalizeSection([self section]);
2391 - (NSString *) shortSection {
2392 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2395 - (NSString *) uri {
2398 pkgIndexFile *index;
2399 pkgCache::PkgFileIterator file(file_.File());
2400 if (![database_ list].FindIndex(file, index))
2402 return [NSString stringWithUTF8String:iterator_->Path];
2403 //return [NSString stringWithUTF8String:file.Site()];
2404 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2408 - (Address *) maintainer {
2409 @synchronized (database_) {
2410 if ([database_ era] != era_ || file_.end())
2413 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2414 const std::string &maintainer(parser->Maintainer());
2415 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2419 @synchronized (database_) {
2420 if ([database_ era] != era_ || version_.end())
2423 return version_->InstalledSize;
2426 - (NSString *) longDescription {
2427 @synchronized (database_) {
2428 if ([database_ era] != era_ || file_.end())
2431 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2432 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2434 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2435 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2436 if ([lines count] < 2)
2439 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2440 for (size_t i(1), e([lines count]); i != e; ++i) {
2441 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2442 [trimmed addObject:trim];
2445 return [trimmed componentsJoinedByString:@"\n"];
2448 - (NSString *) shortDescription {
2449 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2453 _profile(Package$index)
2454 CFStringRef name((CFStringRef) [self name]);
2455 if (CFStringGetLength(name) == 0)
2457 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2458 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2460 return toupper(character);
2464 - (PackageValue *) metadata {
2469 PackageValue *metadata([self metadata]);
2470 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2473 - (bool) subscribed {
2474 return [self metadata]->subscribed_;
2477 - (bool) setSubscribed:(bool)subscribed {
2478 PackageValue *metadata([self metadata]);
2479 if (metadata->subscribed_ == subscribed)
2481 metadata->subscribed_ = subscribed;
2489 - (NSString *) latest {
2493 - (NSString *) installed {
2497 - (BOOL) uninstalled {
2498 return installed_.empty();
2502 return !version_.end();
2505 - (BOOL) upgradableAndEssential:(BOOL)essential {
2506 _profile(Package$upgradableAndEssential)
2507 pkgCache::VerIterator current(iterator_.CurrentVer());
2509 return essential && essential_;
2511 return !version_.end() && version_ != current;
2515 - (BOOL) essential {
2520 return [database_ cache][iterator_].InstBroken();
2523 - (BOOL) unfiltered {
2524 _profile(Package$unfiltered$obsolete)
2525 if (_unlikely(obsolete_))
2529 _profile(Package$unfiltered$hasSupportingRole)
2530 if (_unlikely(![self hasSupportingRole]))
2538 if (![self unfiltered])
2543 _profile(Package$visible$section)
2544 section = [self section];
2547 _profile(Package$visible$isSectionVisible)
2548 if (!isSectionVisible(section))
2556 unsigned char current(iterator_->CurrentState);
2557 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2560 - (BOOL) halfConfigured {
2561 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2564 - (BOOL) halfInstalled {
2565 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2569 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2570 return state.Mode != pkgDepCache::ModeKeep;
2573 - (NSString *) mode {
2574 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2576 switch (state.Mode) {
2577 case pkgDepCache::ModeDelete:
2578 if ((state.iFlags & pkgDepCache::Purge) != 0)
2582 case pkgDepCache::ModeKeep:
2583 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2584 return @"REINSTALL";
2585 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2589 case pkgDepCache::ModeInstall:
2590 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2591 return @"REINSTALL";
2592 else*/ switch (state.Status) {
2594 return @"DOWNGRADE";
2600 return @"NEW_INSTALL";
2611 - (NSString *) name {
2612 return name_.empty() ? id_ : name_;
2615 - (UIImage *) icon {
2616 NSString *section = [self simpleSection];
2619 if (parsed_ != NULL)
2620 if (NSString *href = parsed_->icon_)
2621 if ([href hasPrefix:@"file:///"])
2622 // XXX: correct escaping
2623 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2624 if (icon == nil) if (section != nil)
2625 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2626 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2627 if ([dicon hasPrefix:@"file:///"])
2628 // XXX: correct escaping
2629 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2631 icon = [UIImage applicationImageNamed:@"unknown.png"];
2635 - (NSString *) homepage {
2636 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2639 - (NSString *) depiction {
2640 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2643 - (Address *) sponsor {
2644 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2647 - (Address *) author {
2648 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2651 - (NSString *) support {
2652 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2655 - (NSArray *) files {
2656 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2657 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2660 fin.open([path UTF8String]);
2665 while (std::getline(fin, line))
2666 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2671 - (NSString *) state {
2672 @synchronized (database_) {
2673 if ([database_ era] != era_ || file_.end())
2676 switch (iterator_->CurrentState) {
2677 case pkgCache::State::NotInstalled:
2678 return @"NotInstalled";
2679 case pkgCache::State::UnPacked:
2681 case pkgCache::State::HalfConfigured:
2682 return @"HalfConfigured";
2683 case pkgCache::State::HalfInstalled:
2684 return @"HalfInstalled";
2685 case pkgCache::State::ConfigFiles:
2686 return @"ConfigFiles";
2687 case pkgCache::State::Installed:
2688 return @"Installed";
2689 case pkgCache::State::TriggersAwaited:
2690 return @"TriggersAwaited";
2691 case pkgCache::State::TriggersPending:
2692 return @"TriggersPending";
2695 return (NSString *) [NSNull null];
2698 - (NSString *) selection {
2699 @synchronized (database_) {
2700 if ([database_ era] != era_ || file_.end())
2703 switch (iterator_->SelectedState) {
2704 case pkgCache::State::Unknown:
2706 case pkgCache::State::Install:
2708 case pkgCache::State::Hold:
2710 case pkgCache::State::DeInstall:
2711 return @"DeInstall";
2712 case pkgCache::State::Purge:
2716 return (NSString *) [NSNull null];
2719 - (NSArray *) warnings {
2720 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2721 const char *name(iterator_.Name());
2723 size_t length(strlen(name));
2724 if (length < 2) invalid:
2725 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2726 else for (size_t i(0); i != length; ++i)
2728 /* XXX: technically this is not allowed */
2729 (name[i] < 'A' || name[i] > 'Z') &&
2730 (name[i] < 'a' || name[i] > 'z') &&
2731 (name[i] < '0' || name[i] > '9') &&
2732 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2735 if (strcmp(name, "cydia") != 0) {
2738 bool _private = false;
2741 bool repository = [[self section] isEqualToString:@"Repositories"];
2743 if (NSArray *files = [self files])
2744 for (NSString *file in files)
2745 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2747 else if (!user && [file isEqualToString:@"/User"])
2749 else if (!_private && [file isEqualToString:@"/private"])
2751 else if (!stash && [file isEqualToString:@"/var/stash"])
2754 /* XXX: this is not sensitive enough. only some folders are valid. */
2755 if (cydia && !repository)
2756 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2758 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2760 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2762 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2765 return [warnings count] == 0 ? nil : warnings;
2768 - (NSArray *) applications {
2769 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2771 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2773 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2774 if (NSArray *files = [self files])
2775 for (NSString *file in files)
2776 if (application_r(file)) {
2777 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2778 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2779 if ([id isEqualToString:me])
2782 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2784 display = application_r[1];
2786 NSString *bundle([file stringByDeletingLastPathComponent]);
2787 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2788 if (icon == nil || [icon length] == 0)
2790 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2792 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2793 [applications addObject:application];
2795 [application addObject:id];
2796 [application addObject:display];
2797 [application addObject:url];
2800 return [applications count] == 0 ? nil : applications;
2803 - (Source *) source {
2804 if (source_ == nil) {
2805 @synchronized (database_) {
2806 if ([database_ era] != era_ || file_.end())
2807 source_ = (Source *) [NSNull null];
2809 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2813 return source_ == (Source *) [NSNull null] ? nil : source_;
2816 - (BOOL) matches:(NSString *)text {
2822 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2823 if (range.location != NSNotFound)
2826 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2827 if (range.location != NSNotFound)
2832 NSString *description([self shortDescription]);
2833 NSUInteger length([description length]);
2835 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2836 if (range.location != NSNotFound)
2842 - (bool) hasSupportingRole {
2847 if ([Role_ isEqualToString:@"User"])
2851 if ([Role_ isEqualToString:@"Hacker"])
2855 if ([Role_ isEqualToString:@"Developer"])
2860 - (NSArray *) tags {
2864 - (BOOL) hasTag:(NSString *)tag {
2865 return tags_ == nil ? NO : [tags_ containsObject:tag];
2868 - (NSString *) primaryPurpose {
2869 for (NSString *tag in (NSArray *) tags_)
2870 if ([tag hasPrefix:@"purpose::"])
2871 return [tag substringFromIndex:9];
2875 - (NSArray *) purposes {
2876 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2877 for (NSString *tag in (NSArray *) tags_)
2878 if ([tag hasPrefix:@"purpose::"])
2879 [purposes addObject:[tag substringFromIndex:9]];
2880 return [purposes count] == 0 ? nil : purposes;
2883 - (bool) isCommercial {
2884 return [self hasTag:@"cydia::commercial"];
2887 - (void) setIndex:(size_t)index {
2888 if (metadata_->index_ != index)
2889 metadata_->index_ = index;
2892 - (CYString &) cyname {
2893 return name_.empty() ? id_ : name_;
2896 - (uint32_t) compareBySection:(NSArray *)sections {
2897 NSString *section([self section]);
2898 for (size_t i(0), e([sections count]); i != e; ++i) {
2899 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2903 return _not(uint32_t);
2907 @synchronized (database_) {
2908 pkgProblemResolver *resolver = [database_ resolver];
2909 resolver->Clear(iterator_);
2911 pkgCacheFile &cache([database_ cache]);
2912 cache->SetReInstall(iterator_, false);
2913 cache->MarkKeep(iterator_, false);
2917 @synchronized (database_) {
2918 pkgProblemResolver *resolver = [database_ resolver];
2919 resolver->Clear(iterator_);
2920 resolver->Protect(iterator_);
2922 pkgCacheFile &cache([database_ cache]);
2923 cache->SetReInstall(iterator_, false);
2924 cache->MarkInstall(iterator_, false);
2926 pkgDepCache::StateCache &state((*cache)[iterator_]);
2927 if (!state.Install())
2928 cache->SetReInstall(iterator_, true);
2932 @synchronized (database_) {
2933 pkgProblemResolver *resolver = [database_ resolver];
2934 resolver->Clear(iterator_);
2935 resolver->Remove(iterator_);
2936 resolver->Protect(iterator_);
2938 pkgCacheFile &cache([database_ cache]);
2939 cache->SetReInstall(iterator_, false);
2940 cache->MarkDelete(iterator_, true);
2943 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2944 _profile(Package$isUnfilteredAndSearchedForBy)
2947 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2948 value &= [self unfiltered];
2951 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2952 value &= [self matches:search];
2959 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2960 if ([search length] == 0)
2963 _profile(Package$isUnfilteredAndSelectedForBy)
2966 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2967 value &= [self unfiltered];
2970 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2971 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2978 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2979 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2982 - (bool) isVisibleInSection:(NSString *)name {
2983 NSString *section([self section]);
2987 section == nil && [name length] == 0 ||
2988 [name isEqualToString:section]
2989 ) && [self visible];
2992 - (bool) isVisibleInSource:(Source *)source {
2993 return [self source] == source && [self visible];
2998 /* Section Class {{{ */
2999 @interface Section : NSObject {
3004 _H<NSString> localized_;
3007 - (NSComparisonResult) compareByLocalized:(Section *)section;
3008 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3009 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3010 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3011 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3012 - (NSString *) name;
3019 - (void) addToCount;
3021 - (void) setCount:(size_t)count;
3022 - (NSString *) localized;
3026 @implementation Section
3028 - (NSComparisonResult) compareByLocalized:(Section *)section {
3029 NSString *lhs(localized_);
3030 NSString *rhs([section localized]);
3032 /*if ([lhs length] != 0 && [rhs length] != 0) {
3033 unichar lhc = [lhs characterAtIndex:0];
3034 unichar rhc = [rhs characterAtIndex:0];
3036 if (isalpha(lhc) && !isalpha(rhc))
3037 return NSOrderedAscending;
3038 else if (!isalpha(lhc) && isalpha(rhc))
3039 return NSOrderedDescending;
3042 return [lhs compare:rhs options:LaxCompareOptions_];
3045 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3046 if ((self = [self initWithName:name localize:NO]) != nil) {
3047 if (localized != nil)
3048 localized_ = localized;
3052 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3053 return [self initWithName:name row:0 localize:localize];
3056 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3057 if ((self = [super init]) != nil) {
3062 localized_ = LocalizeSection(name_);
3066 /* XXX: localize the index thingees */
3067 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3068 if ((self = [super init]) != nil) {
3069 name_ = [NSString stringWithCharacters:&index length:1];
3075 - (NSString *) name {
3095 - (void) addToCount {
3099 - (void) setCount:(size_t)count {
3103 - (NSString *) localized {
3110 static NSString *Colon_;
3111 static NSString *Elision_;
3112 static NSString *Error_;
3113 static NSString *Warning_;
3115 /* Database Implementation {{{ */
3116 @implementation Database
3118 + (Database *) sharedInstance {
3119 static _H<Database> instance;
3120 if (instance == nil)
3121 instance = [[[Database alloc] init] autorelease];
3129 - (void) releasePackages {
3130 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3131 CFArrayRemoveAllValues(packages_);
3135 // XXX: actually implement this thing
3137 [self releasePackages];
3138 apr_pool_destroy(pool_);
3139 NSRecycleZone(zone_);
3143 - (void) _readCydia:(NSNumber *)fd { _pooled
3144 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3145 std::istream is(&ib);
3148 static Pcre finish_r("^finish:([^:]*)$");
3150 while (std::getline(is, line)) {
3151 const char *data(line.c_str());
3152 size_t size = line.size();
3153 lprintf("C:%s\n", data);
3155 if (finish_r(data, size)) {
3156 NSString *finish = finish_r[1];
3157 int index = [Finishes_ indexOfObject:finish];
3158 if (index != INT_MAX && index > Finish_)
3166 - (void) _readStatus:(NSNumber *)fd { _pooled
3167 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3168 std::istream is(&ib);
3171 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3172 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3174 while (std::getline(is, line)) {
3175 const char *data(line.c_str());
3176 size_t size(line.size());
3177 lprintf("S:%s\n", data);
3179 if (conffile_r(data, size)) {
3180 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3181 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3182 } else if (strncmp(data, "status: ", 8) == 0) {
3183 // status: <package>: {unpacked,half-configured,installed}
3184 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3185 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3186 } else if (strncmp(data, "processing: ", 12) == 0) {
3187 // processing: configure: config-test
3188 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3189 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3190 } else if (pmstatus_r(data, size)) {
3191 std::string type([pmstatus_r[1] UTF8String]);
3193 NSString *package = pmstatus_r[2];
3194 if ([package isEqualToString:@"dpkg-exec"])
3197 float percent([pmstatus_r[3] floatValue]);
3198 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3200 NSString *string = pmstatus_r[4];
3202 if (type == "pmerror") {
3203 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3204 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3205 } else if (type == "pmstatus") {
3206 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3207 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3208 } else if (type == "pmconffile")
3209 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3211 lprintf("E:unknown pmstatus\n");
3213 lprintf("E:unknown status\n");
3219 - (void) _readOutput:(NSNumber *)fd { _pooled
3220 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3221 std::istream is(&ib);
3224 while (std::getline(is, line)) {
3225 lprintf("O:%s\n", line.c_str());
3227 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3228 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3238 - (Package *) packageWithName:(NSString *)name {
3239 @synchronized (self) {
3240 if (static_cast<pkgDepCache *>(cache_) == NULL)
3242 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3243 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3247 if ((self = [super init]) != nil) {
3254 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3255 apr_pool_create(&pool_, NULL);
3257 size_t capacity(MetaFile_->active_);
3263 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3264 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3268 _assert(pipe(fds) != -1);
3271 _config->Set("APT::Keep-Fds::", cydiafd_);
3272 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3275 detachNewThreadSelector:@selector(_readCydia:)
3277 withObject:[NSNumber numberWithInt:fds[0]]
3280 _assert(pipe(fds) != -1);
3284 detachNewThreadSelector:@selector(_readStatus:)
3286 withObject:[NSNumber numberWithInt:fds[0]]
3289 _assert(pipe(fds) != -1);
3290 _assert(dup2(fds[0], 0) != -1);
3291 _assert(close(fds[0]) != -1);
3293 input_ = fdopen(fds[1], "a");
3295 _assert(pipe(fds) != -1);
3296 _assert(dup2(fds[1], 1) != -1);
3297 _assert(close(fds[1]) != -1);
3300 detachNewThreadSelector:@selector(_readOutput:)
3302 withObject:[NSNumber numberWithInt:fds[0]]
3307 - (pkgCacheFile &) cache {
3311 - (pkgDepCache::Policy *) policy {
3315 - (pkgRecords *) records {
3319 - (pkgProblemResolver *) resolver {
3323 - (pkgAcquire &) fetcher {
3327 - (pkgSourceList &) list {
3331 - (NSArray *) packages {
3332 return (NSArray *) packages_;
3335 - (NSArray *) sources {
3339 - (Source *) sourceWithKey:(NSString *)key {
3340 for (Source *source in [self sources]) {
3341 if ([[source key] isEqualToString:key])
3346 - (bool) popErrorWithTitle:(NSString *)title {
3349 while (!_error->empty()) {
3351 bool warning(!_error->PopMessage(error));
3356 size_t size(error.size());
3357 if (size == 0 || error[size - 1] != '\n')
3359 error.resize(size - 1);
3362 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3364 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3370 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3371 return [self popErrorWithTitle:title] || !success;
3374 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3375 @synchronized (self) {
3378 [self releasePackages];
3381 [sourceList_ removeAllObjects];
3401 apr_pool_clear(pool_);
3403 NSRecycleZone(zone_);
3404 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3406 int chk(creat("/tmp/cydia.chk", 0644));
3410 if (invocation != nil)
3411 [invocation invoke];
3413 NSString *title(UCLocalize("DATABASE"));
3416 OpProgress progress;
3417 while (!cache_.Open(progress, true)) { pop:
3419 bool warning(!_error->PopMessage(error));
3420 lprintf("cache_.Open():[%s]\n", error.c_str());
3422 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3423 [delegate_ repairWithSelector:@selector(configure)];
3424 else if (error == "The package lists or status file could not be parsed or opened.")
3425 [delegate_ repairWithSelector:@selector(update)];
3426 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3427 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3428 // else if (error == "Malformed Status line")
3429 // else if (error == "The list of sources could not be read.")
3431 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3441 unlink("/tmp/cydia.chk");
3443 now_ = [[NSDate date] timeIntervalSince1970];
3445 policy_ = new pkgDepCache::Policy();
3446 records_ = new pkgRecords(cache_);
3447 resolver_ = new pkgProblemResolver(cache_);
3448 fetcher_ = new pkgAcquire(&status_);
3451 list_ = new pkgSourceList();
3452 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3455 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3456 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3460 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3463 if (cache_->BrokenCount() != 0) {
3464 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3467 if (cache_->BrokenCount() != 0) {
3468 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3472 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3476 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3477 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3478 [sourceList_ addObject:object];
3480 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3481 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3482 // XXX: this could be more intelligent
3483 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3484 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3486 sourceMap_[cached->ID] = object;
3491 /*std::vector<Package *> packages;
3492 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3497 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3498 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3499 //packages.push_back(package);
3500 CFArrayAppendValue(packages_, CFRetain(package));
3504 /*if (packages.empty())
3505 packages_ = [[NSArray alloc] init];
3507 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3510 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3511 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3512 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3520 /*if (!packages.empty())
3521 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3522 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3524 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3526 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3528 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3532 size_t count(CFArrayGetCount(packages_));
3533 MetaFile_->active_ = count;
3535 for (size_t index(0); index != count; ++index)
3536 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3540 } } CYPoolEnd() _trace(); }
3543 @synchronized (self) {
3545 resolver_ = new pkgProblemResolver(cache_);
3547 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3548 if (!cache_[iterator].Keep())
3549 cache_->MarkKeep(iterator, false);
3550 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3551 cache_->SetReInstall(iterator, false);
3554 - (void) configure {
3555 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3557 system([dpkg UTF8String]);
3562 // XXX: I don't remember this condition
3567 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3569 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3571 if ([self popErrorWithTitle:title])
3575 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3578 public pkgArchiveCleaner
3581 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3586 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3593 fetcher_->Shutdown();
3595 pkgRecords records(cache_);
3597 lock_ = new FileFd();
3598 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3600 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3602 if ([self popErrorWithTitle:title])
3606 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3609 manager_ = (_system->CreatePM(cache_));
3610 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3617 bool substrate(RestartSubstrate_);
3618 RestartSubstrate_ = false;
3620 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3622 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3624 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3626 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3627 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3630 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3632 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3634 [self popErrorWithTitle:title];
3638 bool failed = false;
3639 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3640 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3642 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3648 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3656 RestartSubstrate_ = true;
3659 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3661 if (_error->PendingError()) {
3666 if (result == pkgPackageManager::Failed) {
3671 if (result != pkgPackageManager::Completed) {
3676 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3678 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3680 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3681 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3684 if (![before isEqualToArray:after])
3689 NSString *title(UCLocalize("UPGRADE"));
3690 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3696 [self updateWithStatus:status_];
3699 - (void) updateWithStatus:(Status &)status {
3700 NSString *title(UCLocalize("REFRESHING_DATA"));
3703 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3707 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3708 if ([self popErrorWithTitle:title])
3711 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3713 bool success(ListUpdate(status, list, PulseInterval_));
3714 if (status.WasCancelled())
3717 [self popErrorWithTitle:title forOperation:success];
3719 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3721 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3725 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3726 delegate_ = delegate;
3729 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3730 progress_ = delegate;
3731 status_.setDelegate(delegate);
3734 - (NSObject<ProgressDelegate> *) progressDelegate {
3738 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3739 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3740 return i == sourceMap_.end() ? nil : i->second;
3743 - (NSString *) mappedSectionForPointer:(const char *)section {
3744 _H<NSString> *mapped;
3746 _profile(Database$mappedSectionForPointer$Cache)
3747 mapped = §ions_[section];
3750 if (*mapped == NULL) {
3751 size_t length(strlen(section));
3752 char spaced[length + 1];
3754 _profile(Database$mappedSectionForPointer$Replace)
3755 for (size_t index(0); index != length; ++index)
3756 spaced[index] = section[index] == '_' ? ' ' : section[index];
3757 spaced[length] = '\0';
3762 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3763 string = [NSString stringWithUTF8String:spaced];
3766 _profile(Database$mappedSectionForPointer$Map)
3767 string = [SectionMap_ objectForKey:string] ?: string;
3777 static _H<NSMutableSet> Diversions_;
3779 @interface Diversion : NSObject {
3782 _H<NSString> format_;
3787 @implementation Diversion
3789 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3790 if ((self = [super init]) != nil) {
3791 pattern_ = [from UTF8String];
3797 - (NSString *) divert:(NSString *)url {
3798 return !pattern_(url) ? nil : pattern_->*format_;
3801 + (NSURL *) divertURL:(NSURL *)url {
3803 NSString *href([url absoluteString]);
3805 for (Diversion *diversion in (id) Diversions_)
3806 if (NSString *diverted = [diversion divert:href]) {
3808 NSLog(@"div: %@", diverted);
3810 url = [NSURL URLWithString:diverted];
3817 - (NSString *) key {
3821 - (NSUInteger) hash {
3825 - (BOOL) isEqual:(Diversion *)object {
3826 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3831 @interface CydiaObject : NSObject {
3832 _H<IndirectDelegate> indirect_;
3833 _transient id delegate_;
3836 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3840 @interface CydiaWebViewController : CyteWebViewController {
3841 _H<CydiaObject> cydia_;
3844 + (void) addDiversion:(Diversion *)diversion;
3848 /* Web Scripting {{{ */
3849 @implementation CydiaObject
3851 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3852 if ((self = [super init]) != nil) {
3853 indirect_ = indirect;
3857 - (void) setDelegate:(id)delegate {
3858 delegate_ = delegate;
3861 + (NSArray *) _attributeKeys {
3862 return [NSArray arrayWithObjects:
3878 - (NSArray *) attributeKeys {
3879 return [[self class] _attributeKeys];
3882 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3883 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3886 - (NSString *) version {
3890 - (NSString *) device {
3891 return [[UIDevice currentDevice] uniqueIdentifier];
3894 - (NSString *) firmware {
3895 return [[UIDevice currentDevice] systemVersion];
3898 - (NSString *) hostname {
3899 return [[UIDevice currentDevice] name];
3902 - (NSString *) idiom {
3903 return (id) Idiom_ ?: [NSNull null];
3906 - (NSString *) plmn {
3907 return (id) PLMN_ ?: [NSNull null];
3910 - (NSString *) bbsnum {
3911 return (id) BBSNum_ ?: [NSNull null];
3914 - (NSString *) ecid {
3915 return (id) ChipID_ ?: [NSNull null];
3918 - (NSString *) serial {
3919 return SerialNumber_;
3922 - (NSString *) role {
3923 return (id) Role_ ?: [NSNull null];
3926 - (NSString *) model {
3927 return [NSString stringWithUTF8String:Machine_];
3930 - (NSString *) token {
3931 return (id) Token_ ?: [NSNull null];
3934 + (NSString *) webScriptNameForSelector:(SEL)selector {
3936 else if (selector == @selector(addBridgedHost:))
3937 return @"addBridgedHost";
3938 else if (selector == @selector(addInternalRedirect::))
3939 return @"addInternalRedirect";
3940 else if (selector == @selector(addPipelinedHost:scheme:))
3941 return @"addPipelinedHost";
3942 else if (selector == @selector(addTrivialSource:))
3943 return @"addTrivialSource";
3944 else if (selector == @selector(close))
3946 else if (selector == @selector(du:))
3948 else if (selector == @selector(stringWithFormat:arguments:))
3950 else if (selector == @selector(getAllSources))
3951 return @"getAllSourcs";
3952 else if (selector == @selector(getKernelNumber:))
3953 return @"getKernelNumber";
3954 else if (selector == @selector(getKernelString:))
3955 return @"getKernelString";
3956 else if (selector == @selector(getInstalledPackages))
3957 return @"getInstalledPackages";
3958 else if (selector == @selector(getLocaleIdentifier))
3959 return @"getLocaleIdentifier";
3960 else if (selector == @selector(getPreferredLanguages))
3961 return @"getPreferredLanguages";
3962 else if (selector == @selector(getPackageById:))
3963 return @"getPackageById";
3964 else if (selector == @selector(getSessionValue:))
3965 return @"getSessionValue";
3966 else if (selector == @selector(installPackages:))
3967 return @"installPackages";
3968 else if (selector == @selector(localizedStringForKey:value:table:))
3970 else if (selector == @selector(popViewController:))
3971 return @"popViewController";
3972 else if (selector == @selector(refreshSources))
3973 return @"refreshSources";
3974 else if (selector == @selector(removeButton))
3975 return @"removeButton";
3976 else if (selector == @selector(setSessionValue::))
3977 return @"setSessionValue";
3978 else if (selector == @selector(substitutePackageNames:))
3979 return @"substitutePackageNames";
3980 else if (selector == @selector(scrollToBottom:))
3981 return @"scrollToBottom";
3982 else if (selector == @selector(setAllowsNavigationAction:))
3983 return @"setAllowsNavigationAction";
3984 else if (selector == @selector(setBadgeValue:))
3985 return @"setBadgeValue";
3986 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3987 return @"setButtonImage";
3988 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3989 return @"setButtonTitle";
3990 else if (selector == @selector(setHidesBackButton:))
3991 return @"setHidesBackButton";
3992 else if (selector == @selector(setHidesNavigationBar:))
3993 return @"setHidesNavigationBar";
3994 else if (selector == @selector(setNavigationBarStyle:))
3995 return @"setNavigationBarStyle";
3996 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3997 return @"setNavigationBarTintColor";
3998 else if (selector == @selector(setPasteboardString:))
3999 return @"setPasteboardString";
4000 else if (selector == @selector(setPasteboardURL:))
4001 return @"setPasteboardURL";
4002 else if (selector == @selector(setToken:))
4004 else if (selector == @selector(setViewportWidth:))
4005 return @"setViewportWidth";
4006 else if (selector == @selector(statfs:))
4008 else if (selector == @selector(supports:))
4014 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4015 return [self webScriptNameForSelector:selector] == nil;
4018 - (BOOL) supports:(NSString *)feature {
4019 return [feature isEqualToString:@"window.open"];
4022 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4023 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4026 - (NSNumber *) getKernelNumber:(NSString *)name {
4027 const char *string([name UTF8String]);
4030 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4031 return (id) [NSNull null];
4033 if (size != sizeof(int))
4034 return (id) [NSNull null];
4037 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4038 return (id) [NSNull null];
4040 return [NSNumber numberWithInt:value];
4043 - (NSString *) getKernelString:(NSString *)name {
4044 const char *string([name UTF8String]);
4047 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4048 return (id) [NSNull null];
4050 char value[size + 1];
4051 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4052 return (id) [NSNull null];
4054 // XXX: just in case you request something ludicrous
4057 return [NSString stringWithCString:value];
4060 - (id) getSessionValue:(NSString *)key {
4061 @synchronized (SessionData_) {
4062 return [SessionData_ objectForKey:key];
4065 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4066 @synchronized (SessionData_) {
4067 if (value == (id) [WebUndefined undefined])
4068 [SessionData_ removeObjectForKey:key];
4070 [SessionData_ setObject:value forKey:key];
4073 - (void) addBridgedHost:(NSString *)host {
4074 @synchronized (HostConfig_) {
4075 [BridgedHosts_ addObject:host];
4078 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4079 @synchronized (HostConfig_) {
4080 if (scheme != (id) [WebUndefined undefined])
4081 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4083 [PipelinedHosts_ addObject:host];
4086 - (void) popViewController:(NSNumber *)value {
4087 if (value == (id) [WebUndefined undefined])
4088 value = [NSNumber numberWithBool:YES];
4089 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4092 - (void) addTrivialSource:(NSString *)href {
4093 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4096 - (void) refreshSources {
4097 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4100 - (NSArray *) getAllSources {
4101 return [[Database sharedInstance] sources];
4104 - (NSArray *) getInstalledPackages {
4105 Database *database([Database sharedInstance]);
4106 @synchronized (database) {
4107 NSArray *packages([database packages]);
4108 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4109 for (Package *package in packages)
4110 if (![package uninstalled])
4111 [installed addObject:package];
4115 - (Package *) getPackageById:(NSString *)id {
4116 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4120 return (Package *) [NSNull null];
4123 - (NSString *) getLocaleIdentifier {
4124 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4127 - (NSArray *) getPreferredLanguages {
4131 - (NSArray *) statfs:(NSString *)path {
4134 if (path == nil || statfs([path UTF8String], &stat) == -1)
4137 return [NSArray arrayWithObjects:
4138 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4139 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4140 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4144 - (NSNumber *) du:(NSString *)path {
4145 NSNumber *value(nil);
4148 _assert(pipe(fds) != -1);
4150 pid_t pid(ExecFork());
4152 _assert(dup2(fds[1], 1) != -1);
4153 _assert(close(fds[0]) != -1);
4154 _assert(close(fds[1]) != -1);
4155 /* XXX: this should probably not use du */
4156 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4161 _assert(close(fds[1]) != -1);
4163 if (FILE *du = fdopen(fds[0], "r")) {
4165 while (fgets(line, sizeof(line), du) != NULL) {
4166 size_t length(strlen(line));
4167 while (length != 0 && line[length - 1] == '\n')
4168 line[--length] = '\0';
4169 if (char *tab = strchr(line, '\t')) {
4171 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4176 } else _assert(close(fds[0]));
4180 if (waitpid(pid, &status, 0) == -1)
4183 else _assert(false);
4189 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4192 - (void) installPackages:(NSArray *)packages {
4193 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4196 - (NSString *) substitutePackageNames:(NSString *)message {
4197 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4198 for (size_t i(0), e([words count]); i != e; ++i) {
4199 NSString *word([words objectAtIndex:i]);
4200 if (Package *package = [[Database sharedInstance] packageWithName:word])
4201 [words replaceObjectAtIndex:i withObject:[package name]];
4204 return [words componentsJoinedByString:@" "];
4207 - (void) removeButton {
4208 [indirect_ removeButton];
4211 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4212 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4215 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4216 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4219 - (void) setBadgeValue:(id)value {
4220 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4223 - (void) setAllowsNavigationAction:(NSString *)value {
4224 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4227 - (void) setHidesBackButton:(NSString *)value {
4228 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4231 - (void) setHidesNavigationBar:(NSString *)value {
4232 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4235 - (void) setNavigationBarStyle:(NSString *)value {
4236 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4239 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4240 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4241 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4242 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4245 - (void) setPasteboardString:(NSString *)value {
4246 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4249 - (void) setPasteboardURL:(NSString *)value {
4250 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4253 - (void) _setToken:(NSString *)token {
4257 [Metadata_ removeObjectForKey:@"Token"];
4259 [Metadata_ setObject:Token_ forKey:@"Token"];
4264 - (void) setToken:(NSString *)token {
4265 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4268 - (void) scrollToBottom:(NSNumber *)animated {
4269 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4272 - (void) setViewportWidth:(float)width {
4273 [indirect_ setViewportWidthOnMainThread:width];
4276 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4277 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4278 unsigned count([arguments count]);
4280 for (unsigned i(0); i != count; ++i)
4281 values[i] = [arguments objectAtIndex:i];
4282 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4285 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4286 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4288 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4290 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4296 /* @ Loading... Indicator {{{ */
4297 @interface CYLoadingIndicator : UIView {
4298 _H<UIActivityIndicatorView> spinner_;
4300 _H<UIView> container_;
4303 @property (readonly, nonatomic) UILabel *label;
4304 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4308 @implementation CYLoadingIndicator
4310 - (id) initWithFrame:(CGRect)frame {
4311 if ((self = [super initWithFrame:frame]) != nil) {
4312 container_ = [[[UIView alloc] init] autorelease];
4313 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4315 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4316 [spinner_ startAnimating];
4317 [container_ addSubview:spinner_];
4319 label_ = [[[UILabel alloc] init] autorelease];
4320 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4321 [label_ setBackgroundColor:[UIColor clearColor]];
4322 [label_ setTextColor:[UIColor blackColor]];
4323 [label_ setShadowColor:[UIColor whiteColor]];
4324 [label_ setShadowOffset:CGSizeMake(0, 1)];
4325 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4326 [container_ addSubview:label_];
4328 CGSize viewsize = frame.size;
4329 CGSize spinnersize = [spinner_ bounds].size;
4330 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4331 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4333 CGRect containrect = {
4334 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4335 CGSizeMake(bothwidth, spinnersize.height)
4338 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4346 [container_ setFrame:containrect];
4347 [spinner_ setFrame:spinrect];
4348 [label_ setFrame:textrect];
4349 [self addSubview:container_];
4353 - (UILabel *) label {
4357 - (UIActivityIndicatorView *) activityIndicatorView {
4363 /* Emulated Loading Controller {{{ */
4364 @interface CYEmulatedLoadingController : CyteViewController {
4365 _transient Database *database_;
4366 _H<CYLoadingIndicator> indicator_;
4367 _H<UITabBar> tabbar_;
4368 _H<UINavigationBar> navbar_;
4373 @implementation CYEmulatedLoadingController
4375 - (id) initWithDatabase:(Database *)database {
4376 if ((self = [super init]) != nil) {
4377 database_ = database;
4382 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4384 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4385 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4386 [[self view] addSubview:table];
4388 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4389 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4390 [[self view] addSubview:indicator_];
4392 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4393 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4394 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4395 [[self view] addSubview:tabbar_];
4397 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4398 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4399 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4400 [[self view] addSubview:navbar_];
4403 - (void) releaseSubviews {
4412 /* Cydia Browser Controller {{{ */
4413 @implementation CydiaWebViewController
4415 - (NSURL *) navigationURL {
4416 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4419 + (void) initialize {
4420 Diversions_ = [NSMutableSet setWithCapacity:0];
4423 + (void) addDiversion:(Diversion *)diversion {
4424 [Diversions_ addObject:diversion];
4427 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4428 [super webView:view didClearWindowObject:window forFrame:frame];
4430 WebDataSource *source([frame dataSource]);
4431 NSURLResponse *response([source response]);
4432 NSURL *url([response URL]);
4433 NSString *scheme([[url scheme] lowercaseString]);
4435 bool bridged(false);
4437 @synchronized (HostConfig_) {
4438 if ([scheme isEqualToString:@"file"])
4440 else if ([scheme isEqualToString:@"https"])
4441 if ([BridgedHosts_ containsObject:[url host]])
4446 [window setValue:cydia_ forKey:@"cydia"];
4449 - (NSURL *) URLWithURL:(NSURL *)url {
4450 return [Diversion divertURL:url];
4453 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4454 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4456 if (System_ != NULL)
4457 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4458 if (Machine_ != NULL)
4459 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4461 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4466 - (void) setDelegate:(id)delegate {
4467 [super setDelegate:delegate];
4468 [cydia_ setDelegate:delegate];
4472 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4473 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4475 WebView *webview([[webview_ _documentView] webView]);
4477 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4480 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4482 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4483 if (Product_ != nil)
4484 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4486 [webview setApplicationNameForUserAgent:application];
4494 @interface NSObject (CydiaScript)
4495 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4498 @implementation NSObject (CydiaScript)
4500 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4506 @implementation NSArray (CydiaScript)
4508 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4509 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4510 for (size_t i(0), e([self count]); i != e; ++i)
4511 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4517 @implementation NSDictionary (CydiaScript)
4519 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4520 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4522 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4529 /* Confirmation Controller {{{ */
4530 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4531 if (!iterator.end())
4532 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4533 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4535 pkgCache::PkgIterator package(dep.TargetPkg());
4538 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4545 @protocol ConfirmationControllerDelegate
4546 - (void) cancelAndClear:(bool)clear;
4547 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4551 @interface ConfirmationController : CydiaWebViewController {
4552 _transient Database *database_;
4554 _H<UIAlertView> essential_;
4556 _H<NSDictionary> changes_;
4557 _H<NSMutableArray> issues_;
4558 _H<NSDictionary> sizes_;
4563 - (id) initWithDatabase:(Database *)database;
4567 @implementation ConfirmationController
4571 RestartSubstrate_ = true;
4572 [delegate_ confirmWithNavigationController:[self navigationController]];
4575 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4576 NSString *context([alert context]);
4578 if ([context isEqualToString:@"remove"]) {
4579 if (button == [alert cancelButtonIndex])
4580 [self dismissModalViewControllerAnimated:YES];
4581 else if (button == [alert firstOtherButtonIndex]) {
4585 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4586 } else if ([context isEqualToString:@"unable"]) {
4587 [self dismissModalViewControllerAnimated:YES];
4588 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4590 [super alertView:alert clickedButtonAtIndex:button];
4594 - (void) _doContinue {
4595 [self dismissModalViewControllerAnimated:YES];
4596 [delegate_ cancelAndClear:NO];
4599 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4600 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4604 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4605 [super webView:view didClearWindowObject:window forFrame:frame];
4607 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4608 (id) changes_, @"changes",
4609 (id) issues_, @"issues",
4610 (id) sizes_, @"sizes",
4612 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4615 - (id) initWithDatabase:(Database *)database {
4616 if ((self = [super init]) != nil) {
4617 database_ = database;
4619 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4620 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4621 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4622 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4623 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4627 pkgCacheFile &cache([database_ cache]);
4628 NSArray *packages([database_ packages]);
4629 pkgDepCache::Policy *policy([database_ policy]);
4631 issues_ = [NSMutableArray arrayWithCapacity:4];
4633 for (Package *package in packages) {
4634 pkgCache::PkgIterator iterator([package iterator]);
4635 NSString *name([package id]);
4637 if ([package broken]) {
4638 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4640 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4642 reasons, @"reasons",
4645 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4649 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4650 pkgCache::DepIterator start;
4651 pkgCache::DepIterator end;
4652 dep.GlobOr(start, end); // ++dep
4654 if (!cache->IsImportantDep(end))
4656 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4659 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4661 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4662 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4663 clauses, @"clauses",
4667 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4669 pkgCache::PkgIterator target(start.TargetPkg());
4670 if (target->ProvidesList != 0)
4671 reason = @"missing";
4673 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4675 reason = @"installed";
4676 installed = [NSString stringWithUTF8String:ver.VerStr()];
4677 } else if (!cache[target].CandidateVerIter(cache).end())
4678 reason = @"uninstalled";
4679 else if (target->ProvidesList == 0)
4680 reason = @"uninstallable";
4682 reason = @"virtual";
4685 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4686 [NSString stringWithUTF8String:start.CompType()], @"operator",
4687 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4690 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4691 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4692 version, @"version",
4694 installed, @"installed",
4697 // yes, seriously. (wtf?)
4705 pkgDepCache::StateCache &state(cache[iterator]);
4707 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4709 if (state.NewInstall())
4710 [installs addObject:name];
4711 // XXX: else if (state.Install())
4712 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4713 [reinstalls addObject:name];
4714 // XXX: move before previous if
4715 else if (state.Upgrade())
4716 [upgrades addObject:name];
4717 else if (state.Downgrade())
4718 [downgrades addObject:name];
4719 else if (!state.Delete())
4720 // XXX: _assert(state.Keep());
4722 else if (special_r(name))
4723 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4724 [NSNull null], @"package",
4725 [NSArray arrayWithObjects:
4726 [NSDictionary dictionaryWithObjectsAndKeys:
4727 @"Conflicts", @"relationship",
4728 [NSArray arrayWithObjects:
4729 [NSDictionary dictionaryWithObjectsAndKeys:
4731 [NSNull null], @"version",
4732 @"installed", @"reason",
4739 if ([package essential])
4741 [removes addObject:name];
4744 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4745 substrate_ |= DepSubstrate(iterator.CurrentVer());
4750 else if (Advanced_) {
4751 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4753 essential_ = [[[UIAlertView alloc]
4754 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4755 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4757 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4759 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4763 [essential_ setContext:@"remove"];
4765 essential_ = [[[UIAlertView alloc]
4766 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4767 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4769 cancelButtonTitle:UCLocalize("OKAY")
4770 otherButtonTitles:nil
4773 [essential_ setContext:@"unable"];
4776 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4777 installs, @"installs",
4778 reinstalls, @"reinstalls",
4779 upgrades, @"upgrades",
4780 downgrades, @"downgrades",
4781 removes, @"removes",
4784 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4785 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4786 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4789 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4793 - (UIBarButtonItem *) leftButton {
4794 return [[[UIBarButtonItem alloc]
4795 initWithTitle:UCLocalize("CANCEL")
4796 style:UIBarButtonItemStylePlain
4798 action:@selector(cancelButtonClicked)
4803 - (void) applyRightButton {
4804 if ([issues_ count] == 0 && ![self isLoading])
4805 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4806 initWithTitle:UCLocalize("CONFIRM")
4807 style:UIBarButtonItemStyleDone
4809 action:@selector(confirmButtonClicked)
4812 [[self navigationItem] setRightBarButtonItem:nil];
4816 - (void) cancelButtonClicked {
4817 [self dismissModalViewControllerAnimated:YES];
4818 [delegate_ cancelAndClear:YES];
4822 - (void) confirmButtonClicked {
4823 if (essential_ != nil)
4833 /* Progress Data {{{ */
4834 @interface CydiaProgressData : NSObject {
4835 _transient id delegate_;
4844 _H<NSMutableArray> events_;
4845 _H<NSString> title_;
4847 _H<NSString> status_;
4848 _H<NSString> finish_;
4853 @implementation CydiaProgressData
4855 + (NSArray *) _attributeKeys {
4856 return [NSArray arrayWithObjects:
4868 - (NSArray *) attributeKeys {
4869 return [[self class] _attributeKeys];
4872 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4873 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4877 if ((self = [super init]) != nil) {
4878 events_ = [NSMutableArray arrayWithCapacity:32];
4882 - (void) setDelegate:(id)delegate {
4883 delegate_ = delegate;
4886 - (void) setPercent:(float)value {
4890 - (NSNumber *) percent {
4891 return [NSNumber numberWithFloat:percent_];
4894 - (void) setCurrent:(float)value {
4898 - (NSNumber *) current {
4899 return [NSNumber numberWithFloat:current_];
4902 - (void) setTotal:(float)value {
4906 - (NSNumber *) total {
4907 return [NSNumber numberWithFloat:total_];
4910 - (void) setSpeed:(float)value {
4914 - (NSNumber *) speed {
4915 return [NSNumber numberWithFloat:speed_];
4918 - (NSArray *) events {
4922 - (void) removeAllEvents {
4923 [events_ removeAllObjects];
4926 - (void) addEvent:(CydiaProgressEvent *)event {
4927 [events_ addObject:event];
4930 - (void) setTitle:(NSString *)text {
4934 - (NSString *) title {
4938 - (void) setFinish:(NSString *)text {
4942 - (NSString *) finish {
4943 return (id) finish_ ?: [NSNull null];
4946 - (void) setRunning:(bool)running {
4950 - (NSNumber *) running {
4951 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4956 /* Progress Controller {{{ */
4957 @interface ProgressController : CydiaWebViewController <
4960 _transient Database *database_;
4961 _H<CydiaProgressData> progress_;
4965 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4967 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4969 - (void) setTitle:(NSString *)title;
4970 - (void) setCancellable:(bool)cancellable;
4974 @implementation ProgressController
4977 [database_ setProgressDelegate:nil];
4978 [progress_ setDelegate:nil];
4982 - (UIBarButtonItem *) leftButton {
4983 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4984 initWithTitle:UCLocalize("CANCEL")
4985 style:UIBarButtonItemStylePlain
4987 action:@selector(cancel)
4988 ] autorelease] : nil;
4991 - (void) updateCancel {
4992 [super applyLeftButton];
4995 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4996 if ((self = [super init]) != nil) {
4997 database_ = database;
4998 delegate_ = delegate;
5000 [database_ setProgressDelegate:self];
5002 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5003 [progress_ setDelegate:self];
5005 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5007 [scroller_ setBackgroundColor:[UIColor blackColor]];
5009 [[self navigationItem] setHidesBackButton:YES];
5011 [self updateCancel];
5015 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5016 [super webView:view didClearWindowObject:window forFrame:frame];
5017 [window setValue:progress_ forKey:@"cydiaProgress"];
5020 - (void) updateProgress {
5021 [self dispatchEvent:@"CydiaProgressUpdate"];
5024 - (void) viewWillAppear:(BOOL)animated {
5025 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5026 [super viewWillAppear:animated];
5030 UpdateExternalStatus(0);
5037 [delegate_ terminateWithSuccess];
5038 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5039 [delegate_ suspendWithAnimation:YES];
5041 [delegate_ suspend];*/
5053 system("/usr/bin/sbreload");
5059 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5060 SBReboot(SBSSpringBoardServerPort());
5062 reboot2(RB_AUTOBOOT);
5069 - (void) setTitle:(NSString *)title {
5070 [progress_ setTitle:title];
5071 [self updateProgress];
5074 - (UIBarButtonItem *) rightButton {
5075 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5076 initWithTitle:UCLocalize("CLOSE")
5077 style:UIBarButtonItemStylePlain
5079 action:@selector(close)
5083 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5084 UpdateExternalStatus(1);
5086 [progress_ setRunning:true];
5087 [self setTitle:title];
5088 // implicit updateProgress
5090 SHA1SumValue notifyconf; {
5092 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5095 MMap mmap(file, MMap::ReadOnly);
5097 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5098 notifyconf = sha1.Result();
5102 SHA1SumValue springlist; {
5104 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5107 MMap mmap(file, MMap::ReadOnly);
5109 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5110 springlist = sha1.Result();
5114 if (invocation != nil) {
5115 [invocation yieldToSelector:@selector(invoke)];
5116 [self setTitle:@"COMPLETE"];
5121 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5124 MMap mmap(file, MMap::ReadOnly);
5126 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5127 if (!(notifyconf == sha1.Result()))
5134 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5137 MMap mmap(file, MMap::ReadOnly);
5139 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5140 if (!(springlist == sha1.Result()))
5146 if (RestartSubstrate_)
5150 RestartSubstrate_ = false;
5153 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5154 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5155 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5156 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5157 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5161 system("su -c /usr/bin/uicache mobile");
5164 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5166 [progress_ setRunning:false];
5167 [self updateProgress];
5169 [self applyRightButton];
5172 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5173 [progress_ addEvent:event];
5174 [self updateProgress];
5177 - (bool) isProgressCancelled {
5178 return cancel_ == 2;
5183 [self updateCancel];
5186 - (void) setCancellable:(bool)cancellable {
5187 unsigned cancel(cancel_);
5191 else if (cancel_ == 0)
5194 if (cancel != cancel_)
5195 [self updateCancel];
5198 - (void) setProgressCancellable:(NSNumber *)cancellable {
5199 [self setCancellable:[cancellable boolValue]];
5202 - (void) setProgressPercent:(NSNumber *)percent {
5203 [progress_ setPercent:[percent floatValue]];
5204 [self updateProgress];
5207 - (void) setProgressStatus:(NSDictionary *)status {
5208 if (status == nil) {
5209 [progress_ setCurrent:0];
5210 [progress_ setTotal:0];
5211 [progress_ setSpeed:0];
5213 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5215 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5216 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5217 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5220 [self updateProgress];
5226 /* Cell Content View {{{ */
5227 @protocol ContentDelegate
5228 - (void) drawContentRect:(CGRect)rect;
5231 @interface ContentView : UIView {
5232 _transient id<ContentDelegate> delegate_;
5237 @implementation ContentView
5239 - (id) initWithFrame:(CGRect)frame {
5240 if ((self = [super initWithFrame:frame]) != nil) {
5241 [self setNeedsDisplayOnBoundsChange:YES];
5245 - (void) setDelegate:(id<ContentDelegate>)delegate {
5246 delegate_ = delegate;
5249 - (void) drawRect:(CGRect)rect {
5250 [super drawRect:rect];
5251 [delegate_ drawContentRect:rect];
5256 /* Cydia TableView Cell {{{ */
5257 @interface CYTableViewCell : UITableViewCell {
5258 _H<ContentView> content_;
5264 @implementation CYTableViewCell
5266 - (void) _updateHighlightColorsForView:(UIView *)view highlighted:(BOOL)highlighted {
5267 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5269 if (view == (UIView *) content_) {
5270 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5271 highlighted_ = highlighted;
5274 [super _updateHighlightColorsForView:view highlighted:highlighted];
5277 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5278 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5279 highlighted_ = selected;
5281 [super setSelected:selected animated:animated];
5282 [content_ setNeedsDisplay];
5288 /* Package Cell {{{ */
5289 @interface PackageCell : CYTableViewCell <
5294 _H<NSString> description_;
5296 _H<NSString> source_;
5298 _H<Package> package_;
5299 _H<UIImage> placard_;
5302 - (PackageCell *) init;
5303 - (void) setPackage:(Package *)package;
5305 - (void) drawContentRect:(CGRect)rect;
5309 @implementation PackageCell
5311 - (PackageCell *) init {
5312 CGRect frame(CGRectMake(0, 0, 320, 74));
5313 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5314 UIView *content([self contentView]);
5315 CGRect bounds([content bounds]);
5317 content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
5318 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5319 [content addSubview:content_];
5321 [content_ setDelegate:self];
5322 [content_ setOpaque:YES];
5326 - (NSString *) accessibilityLabel {
5327 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5330 - (void) setPackage:(Package *)package {
5341 Source *source = [package source];
5343 icon_ = [package icon];
5344 name_ = [package name];
5347 description_ = [package longDescription];
5348 if (description_ == nil)
5349 description_ = [package shortDescription];
5351 commercial_ = [package isCommercial];
5355 NSString *label = nil;
5356 bool trusted = false;
5358 if (source != nil) {
5359 label = [source label];
5360 trusted = [source trusted];
5361 } else if ([[package id] isEqualToString:@"firmware"])
5362 label = UCLocalize("APPLE");
5364 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5366 NSString *from(label);
5368 NSString *section = [package simpleSection];
5369 if (section != nil && ![section isEqualToString:label]) {
5370 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5371 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5374 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5376 if (NSString *purpose = [package primaryPurpose])
5377 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5382 if (NSString *mode = [package_ mode]) {
5383 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5384 color = RemovingColor_;
5385 //placard = @"removing";
5387 color = InstallingColor_;
5388 //placard = @"installing";
5391 // XXX: the removing/installing placards are not @2x
5394 color = [UIColor whiteColor];
5396 if ([package installed] != nil)
5397 placard = @"installed";
5402 [content_ setBackgroundColor:color];
5405 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5407 [self setNeedsDisplay];
5408 [content_ setNeedsDisplay];
5411 - (void) drawContentRect:(CGRect)rect {
5412 bool highlighted(highlighted_);
5413 float width([self bounds].size.width);
5416 CGContextRef context(UIGraphicsGetCurrentContext());
5417 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5418 CGContextFillRect(context, rect);
5423 rect.size = [(UIImage *) icon_ size];
5425 rect.size.width /= 2;
5426 rect.size.height /= 2;
5428 rect.origin.x = 25 - rect.size.width / 2;
5429 rect.origin.y = 25 - rect.size.height / 2;
5431 [icon_ drawInRect:rect];
5434 if (badge_ != nil) {
5436 rect.size = [(UIImage *) badge_ size];
5438 rect.size.width /= 2;
5439 rect.size.height /= 2;
5441 rect.origin.x = 36 - rect.size.width / 2;
5442 rect.origin.y = 36 - rect.size.height / 2;
5444 [badge_ drawInRect:rect];
5451 UISetColor(commercial_ ? Purple_ : Black_);
5452 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5453 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5456 UISetColor(commercial_ ? Purplish_ : Gray_);
5457 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5459 if (placard_ != nil)
5460 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5465 /* Section Cell {{{ */
5466 @interface SectionCell : CYTableViewCell <
5469 _H<NSString> basic_;
5470 _H<NSString> section_;
5472 _H<NSString> count_;
5474 _H<UISwitch> switch_;
5478 - (void) setSection:(Section *)section editing:(BOOL)editing;
5482 @implementation SectionCell
5484 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5485 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5486 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5487 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5488 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5490 UIView *content([self contentView]);
5491 CGRect bounds([content bounds]);
5493 content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
5494 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5495 [content addSubview:content_];
5496 [content_ setBackgroundColor:[UIColor whiteColor]];
5498 [content_ setDelegate:self];
5502 - (void) onSwitch:(id)sender {
5503 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5504 if (metadata == nil) {
5505 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5506 [Sections_ setObject:metadata forKey:basic_];
5509 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5513 - (void) setSection:(Section *)section editing:(BOOL)editing {
5514 if (editing != editing_) {
5516 [switch_ removeFromSuperview];
5518 [self addSubview:switch_];
5527 if (section == nil) {
5528 name_ = UCLocalize("ALL_PACKAGES");
5531 basic_ = [section name];
5532 section_ = [section localized];
5534 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5535 count_ = [NSString stringWithFormat:@"%d", [section count]];
5538 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5541 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5542 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5544 [content_ setNeedsDisplay];
5547 - (void) setFrame:(CGRect)frame {
5548 [super setFrame:frame];
5550 CGRect rect([switch_ frame]);
5551 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5554 - (NSString *) accessibilityLabel {
5558 - (void) drawContentRect:(CGRect)rect {
5559 bool highlighted(highlighted_ && !editing_);
5561 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5566 float width(rect.size.width);
5572 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5574 CGSize size = [count_ sizeWithFont:Font14_];
5578 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5584 /* File Table {{{ */
5585 @interface FileTable : CyteViewController <
5586 UITableViewDataSource,
5589 _transient Database *database_;
5590 _H<Package> package_;
5592 _H<NSMutableArray> files_;
5593 _H<UITableView> list_;
5596 - (id) initWithDatabase:(Database *)database;
5597 - (void) setPackage:(Package *)package;
5601 @implementation FileTable
5604 [(UITableView *) list_ setDataSource:nil];
5605 [list_ setDelegate:nil];
5609 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5610 return files_ == nil ? 0 : [files_ count];
5613 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5617 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5618 static NSString *reuseIdentifier = @"Cell";
5620 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5622 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5623 [cell setFont:[UIFont systemFontOfSize:16]];
5625 [cell setText:[files_ objectAtIndex:indexPath.row]];
5626 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5631 - (NSURL *) navigationURL {
5632 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5636 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5638 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5639 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5640 [list_ setRowHeight:24.0f];
5641 [(UITableView *) list_ setDataSource:self];
5642 [list_ setDelegate:self];
5643 [[self view] addSubview:list_];
5646 - (void) viewDidLoad {
5647 [super viewDidLoad];
5649 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5652 - (void) releaseSubviews {
5656 - (id) initWithDatabase:(Database *)database {
5657 if ((self = [super init]) != nil) {
5658 database_ = database;
5660 files_ = [NSMutableArray arrayWithCapacity:32];
5664 - (void) setPackage:(Package *)package {
5668 [files_ removeAllObjects];
5670 if (package != nil) {
5672 name_ = [package id];
5674 if (NSArray *files = [package files])
5675 [files_ addObjectsFromArray:files];
5677 if ([files_ count] != 0) {
5678 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5679 [files_ removeObjectAtIndex:0];
5680 [files_ sortUsingSelector:@selector(compareByPath:)];
5682 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5683 [stack addObject:@"/"];
5685 for (int i(0), e([files_ count]); i != e; ++i) {
5686 NSString *file = [files_ objectAtIndex:i];
5687 while (![file hasPrefix:[stack lastObject]])
5688 [stack removeLastObject];
5689 NSString *directory = [stack lastObject];
5690 [stack addObject:[file stringByAppendingString:@"/"]];
5691 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5692 ([stack count] - 2) * 3, "",
5693 [file substringFromIndex:[directory length]]
5702 - (void) reloadData {
5705 [self setPackage:[database_ packageWithName:name_]];
5710 /* Package Controller {{{ */
5711 @interface CYPackageController : CydiaWebViewController <
5712 UIActionSheetDelegate
5714 _transient Database *database_;
5715 _H<Package> package_;
5718 _H<NSMutableArray> buttons_;
5719 _H<UIBarButtonItem> button_;
5722 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5726 @implementation CYPackageController
5728 - (NSURL *) navigationURL {
5729 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5732 /* XXX: this is not safe at all... localization of /fail/ */
5733 - (void) _clickButtonWithName:(NSString *)name {
5734 if ([name isEqualToString:UCLocalize("CLEAR")])
5735 [delegate_ clearPackage:package_];
5736 else if ([name isEqualToString:UCLocalize("INSTALL")])
5737 [delegate_ installPackage:package_];
5738 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5739 [delegate_ installPackage:package_];
5740 else if ([name isEqualToString:UCLocalize("REMOVE")])
5741 [delegate_ removePackage:package_];
5742 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5743 [delegate_ installPackage:package_];
5744 else _assert(false);
5747 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5748 NSString *context([sheet context]);
5750 if ([context isEqualToString:@"modify"]) {
5751 if (button != [sheet cancelButtonIndex]) {
5752 NSString *buttonName = [buttons_ objectAtIndex:button];
5753 [self _clickButtonWithName:buttonName];
5756 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5760 - (bool) _allowJavaScriptPanel {
5765 - (void) _customButtonClicked {
5766 int count([buttons_ count]);
5771 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5773 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5774 [buttons addObjectsFromArray:buttons_];
5776 UIActionSheet *sheet = [[[UIActionSheet alloc]
5779 cancelButtonTitle:nil
5780 destructiveButtonTitle:nil
5781 otherButtonTitles:nil
5784 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5786 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5787 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5789 [sheet setContext:@"modify"];
5791 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5795 // We don't want to allow non-commercial packages to do custom things to the install button,
5796 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5797 - (void) customButtonClicked {
5799 [super customButtonClicked];
5801 [self _customButtonClicked];
5804 - (void) reloadButtonClicked {
5805 // Don't reload a commerical package by tapping the loading button,
5806 // but if it's not an Install button, we should forward it on.
5807 if (![package_ uninstalled])
5808 [self _customButtonClicked];
5811 - (void) applyLoadingTitle {
5812 // Don't show "Loading" as the title. Ever.
5815 - (UIBarButtonItem *) rightButton {
5820 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5821 if ((self = [super init]) != nil) {
5822 database_ = database;
5823 buttons_ = [NSMutableArray arrayWithCapacity:4];
5824 name_ = [NSString stringWithString:name];
5825 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5829 - (void) reloadData {
5832 package_ = [database_ packageWithName:name_];
5834 [buttons_ removeAllObjects];
5836 if (package_ != nil) {
5837 [(Package *) package_ parse];
5839 commercial_ = [package_ isCommercial];
5841 if ([package_ mode] != nil)
5842 [buttons_ addObject:UCLocalize("CLEAR")];
5843 if ([package_ source] == nil);
5844 else if ([package_ upgradableAndEssential:NO])
5845 [buttons_ addObject:UCLocalize("UPGRADE")];
5846 else if ([package_ uninstalled])
5847 [buttons_ addObject:UCLocalize("INSTALL")];
5849 [buttons_ addObject:UCLocalize("REINSTALL")];
5850 if (![package_ uninstalled])
5851 [buttons_ addObject:UCLocalize("REMOVE")];
5855 switch ([buttons_ count]) {
5856 case 0: title = nil; break;
5857 case 1: title = [buttons_ objectAtIndex:0]; break;
5858 default: title = UCLocalize("MODIFY"); break;
5861 button_ = [[[UIBarButtonItem alloc]
5863 style:UIBarButtonItemStylePlain
5865 action:@selector(customButtonClicked)
5869 - (bool) isLoading {
5870 return commercial_ ? [super isLoading] : false;
5876 /* Package List Controller {{{ */
5877 @interface PackageListController : CyteViewController <
5878 UITableViewDataSource,
5881 _transient Database *database_;
5883 _H<NSMutableArray> packages_;
5884 _H<NSMutableArray> sections_;
5885 _H<UITableView> list_;
5886 _H<NSMutableArray> index_;
5887 _H<NSMutableDictionary> indices_;
5888 _H<NSString> title_;
5891 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5892 - (void) setDelegate:(id)delegate;
5893 - (void) resetCursor;
5897 @implementation PackageListController
5900 [list_ setDataSource:nil];
5901 [list_ setDelegate:nil];
5905 - (void) deselectWithAnimation:(BOOL)animated {
5906 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5909 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5910 CGRect base = [[self view] bounds];
5911 base.size.height -= bounds.size.height;
5912 base.origin = [list_ frame].origin;
5914 [UIView beginAnimations:nil context:NULL];
5915 [UIView setAnimationBeginsFromCurrentState:YES];
5916 [UIView setAnimationCurve:curve];
5917 [UIView setAnimationDuration:duration];
5918 [list_ setFrame:base];
5919 [UIView commitAnimations];
5922 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5923 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5926 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5927 [self resizeForKeyboardBounds:bounds duration:0];
5930 - (void) keyboardWillShow:(NSNotification *)notification {
5933 NSTimeInterval duration;
5934 UIViewAnimationCurve curve;
5935 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5936 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5937 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5938 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5940 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);
5941 UIViewController *base = self;
5942 while ([base parentViewController] != nil)
5943 base = [base parentViewController];
5944 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5945 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5947 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5950 - (void) keyboardWillHide:(NSNotification *)notification {
5951 NSTimeInterval duration;
5952 UIViewAnimationCurve curve;
5953 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5954 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5956 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5959 - (void) viewWillAppear:(BOOL)animated {
5960 [super viewWillAppear:animated];
5962 [self resizeForKeyboardBounds:CGRectZero];
5963 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5964 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5967 - (void) viewWillDisappear:(BOOL)animated {
5968 [super viewWillDisappear:animated];
5970 [self resizeForKeyboardBounds:CGRectZero];
5971 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5972 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5975 - (void) viewDidAppear:(BOOL)animated {
5976 [super viewDidAppear:animated];
5977 [self deselectWithAnimation:animated];
5980 - (void) didSelectPackage:(Package *)package {
5981 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5982 [view setDelegate:delegate_];
5983 [[self navigationController] pushViewController:view animated:YES];
5986 #if TryIndexedCollation
5987 + (BOOL) hasIndexedCollation {
5988 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5992 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5993 NSInteger count([sections_ count]);
5994 return count == 0 ? 1 : count;
5997 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5998 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6000 return [[sections_ objectAtIndex:section] name];
6003 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6004 if ([sections_ count] == 0)
6006 return [[sections_ objectAtIndex:section] count];
6009 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6010 @synchronized (database_) {
6011 if ([database_ era] != era_)
6014 Section *section([sections_ objectAtIndex:[path section]]);
6015 NSInteger row([path row]);
6016 Package *package([packages_ objectAtIndex:([section row] + row)]);
6017 return [[package retain] autorelease];
6020 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6021 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6023 cell = [[[PackageCell alloc] init] autorelease];
6024 [cell setPackage:[self packageAtIndexPath:path]];
6028 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6029 Package *package([self packageAtIndexPath:path]);
6030 package = [database_ packageWithName:[package id]];
6031 [self didSelectPackage:package];
6034 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6035 // XXX: is 20 the most optimal number here?
6036 return [packages_ count] > 20 ? index_ : nil;
6039 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6040 #if TryIndexedCollation
6041 if ([[self class] hasIndexedCollation]) {
6042 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6049 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6050 if ((self = [super init]) != nil) {
6051 database_ = database;
6052 title_ = [title copy];
6053 [[self navigationItem] setTitle:title_];
6055 #if TryIndexedCollation
6056 if ([[self class] hasIndexedCollation])
6057 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6060 index_ = [NSMutableArray arrayWithCapacity:32];
6062 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6064 packages_ = [NSMutableArray arrayWithCapacity:16];
6065 sections_ = [NSMutableArray arrayWithCapacity:16];
6067 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6068 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6069 [list_ setRowHeight:73];
6070 [[self view] addSubview:list_];
6072 [(UITableView *) list_ setDataSource:self];
6073 [list_ setDelegate:self];
6077 - (void) setDelegate:(id)delegate {
6078 delegate_ = delegate;
6081 - (bool) hasPackage:(Package *)package {
6085 - (bool) shouldYield {
6089 - (void) _reloadPackages:(NSArray *)packages {
6090 [packages_ removeAllObjects];
6091 [sections_ removeAllObjects];
6093 _profile(PackageTable$reloadData$Filter)
6094 for (Package *package in packages)
6095 if ([self hasPackage:package])
6096 [packages_ addObject:package];
6100 - (void) _reloadData {
6101 era_ = [database_ era];
6102 NSArray *packages = [database_ packages];
6104 if ([self shouldYield]) {
6105 UIProgressHUD *hud([delegate_ addProgressHUD]);
6106 [hud setText:UCLocalize("LOADING")];
6107 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
6108 [delegate_ removeProgressHUD:hud];
6110 [self _reloadPackages:packages];
6113 [indices_ removeAllObjects];
6115 Section *section = nil;
6117 #if TryIndexedCollation
6118 if ([[self class] hasIndexedCollation]) {
6119 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6120 NSArray *titles = [collation sectionIndexTitles];
6123 _profile(PackageTable$reloadData$Section)
6124 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6128 _profile(PackageTable$reloadData$Section$Package)
6129 package = [packages_ objectAtIndex:offset];
6130 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6133 while (secidx < index) {
6136 _profile(PackageTable$reloadData$Section$Allocate)
6137 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6140 _profile(PackageTable$reloadData$Section$Add)
6141 [sections_ addObject:section];
6145 [section addToCount];
6151 [index_ removeAllObjects];
6153 _profile(PackageTable$reloadData$Section)
6154 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6158 _profile(PackageTable$reloadData$Section$Package)
6159 package = [packages_ objectAtIndex:offset];
6160 index = [package index];
6163 if (section == nil || [section index] != index) {
6164 _profile(PackageTable$reloadData$Section$Allocate)
6165 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6168 [index_ addObject:[section name]];
6169 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6171 _profile(PackageTable$reloadData$Section$Add)
6172 [sections_ addObject:section];
6176 [section addToCount];
6181 _profile(PackageTable$reloadData$List)
6186 - (void) reloadData {
6188 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6191 - (void) resetCursor {
6192 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6197 /* Filtered Package List Controller {{{ */
6198 @interface FilteredPackageListController : PackageListController {
6201 _H<NSObject> object_;
6204 - (void) setObject:(id)object;
6205 - (void) setObject:(id)object forFilter:(SEL)filter;
6208 - (void) setFilter:(SEL)filter;
6210 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6214 @implementation FilteredPackageListController
6220 - (void) setFilter:(SEL)filter {
6223 /* XXX: this is an unsafe optimization of doomy hell */
6224 Method method(class_getInstanceMethod([Package class], filter));
6225 _assert(method != NULL);
6226 imp_ = method_getImplementation(method);
6227 _assert(imp_ != NULL);
6230 - (void) setObject:(id)object {
6234 - (void) setObject:(id)object forFilter:(SEL)filter {
6235 [self setFilter:filter];
6236 [self setObject:object];
6239 - (bool) hasPackage:(Package *)package {
6240 _profile(FilteredPackageTable$hasPackage)
6241 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6245 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6246 if ((self = [super initWithDatabase:database title:title]) != nil) {
6247 [self setFilter:filter];
6248 [self setObject:object];
6255 /* Home Controller {{{ */
6256 @interface HomeController : CydiaWebViewController {
6261 @implementation HomeController
6264 if ((self = [super init]) != nil) {
6265 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6270 - (NSURL *) navigationURL {
6271 return [NSURL URLWithString:@"cydia://home"];
6274 - (void) aboutButtonClicked {
6275 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6277 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6278 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6279 [alert setCancelButtonIndex:0];
6282 @"Copyright \u00a9 2008-2011\n"
6285 "Jay Freeman (saurik)\n"
6286 "saurik@saurik.com\n"
6287 "http://www.saurik.com/"
6293 - (UIBarButtonItem *) leftButton {
6294 return [[[UIBarButtonItem alloc]
6295 initWithTitle:UCLocalize("ABOUT")
6296 style:UIBarButtonItemStylePlain
6298 action:@selector(aboutButtonClicked)
6302 - (void) unloadData {
6309 /* Manage Controller {{{ */
6310 @interface ManageController : CydiaWebViewController {
6313 - (void) queueStatusDidChange;
6317 @implementation ManageController
6320 if ((self = [super init]) != nil) {
6321 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6325 - (NSURL *) navigationURL {
6326 return [NSURL URLWithString:@"cydia://manage"];
6329 - (UIBarButtonItem *) leftButton {
6330 return [[[UIBarButtonItem alloc]
6331 initWithTitle:UCLocalize("SETTINGS")
6332 style:UIBarButtonItemStylePlain
6334 action:@selector(settingsButtonClicked)
6338 - (void) settingsButtonClicked {
6339 [delegate_ showSettings];
6342 - (void) queueButtonClicked {
6346 - (UIBarButtonItem *) customButton {
6347 return Queuing_ ? [[[UIBarButtonItem alloc]
6348 initWithTitle:UCLocalize("QUEUE")
6349 style:UIBarButtonItemStyleDone
6351 action:@selector(queueButtonClicked)
6352 ] autorelease] : [super customButton];
6355 - (void) queueStatusDidChange {
6356 [self applyRightButton];
6359 - (bool) isLoading {
6360 return !Queuing_ && [super isLoading];
6366 /* Refresh Bar {{{ */
6367 @interface RefreshBar : UINavigationBar {
6368 _H<UIProgressIndicator> indicator_;
6369 _H<UITextLabel> prompt_;
6370 _H<UIProgressBar> progress_;
6371 _H<UINavigationButton> cancel_;
6376 @implementation RefreshBar
6378 - (void) positionViews {
6379 CGRect frame = [cancel_ frame];
6380 frame.size = [cancel_ sizeThatFits:frame.size];
6381 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6382 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6383 [cancel_ setFrame:frame];
6385 CGSize prgsize = {75, 100};
6387 [self frame].size.width - prgsize.width - 10,
6388 ([self frame].size.height - prgsize.height) / 2
6390 [progress_ setFrame:prgrect];
6392 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6393 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6394 CGRect indrect = {{indoffset, indoffset}, indsize};
6395 [indicator_ setFrame:indrect];
6397 CGSize prmsize = {215, indsize.height + 4};
6399 indoffset * 2 + indsize.width,
6400 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6402 [prompt_ setFrame:prmrect];
6405 - (void) setFrame:(CGRect)frame {
6406 [super setFrame:frame];
6407 [self positionViews];
6410 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6411 if ((self = [super initWithFrame:frame]) != nil) {
6412 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6414 [self setBarStyle:UIBarStyleBlack];
6416 UIBarStyle barstyle([self _barStyle:NO]);
6417 bool ugly(barstyle == UIBarStyleDefault);
6419 UIProgressIndicatorStyle style = ugly ?
6420 UIProgressIndicatorStyleMediumBrown :
6421 UIProgressIndicatorStyleMediumWhite;
6423 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6424 [(UIProgressIndicator *) indicator_ setStyle:style];
6425 [indicator_ startAnimation];
6426 [self addSubview:indicator_];
6428 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6429 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6430 [prompt_ setBackgroundColor:[UIColor clearColor]];
6431 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6432 [self addSubview:prompt_];
6434 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6435 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6436 [(UIProgressBar *) progress_ setStyle:0];
6437 [self addSubview:progress_];
6439 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6440 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6441 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6442 [cancel_ setBarStyle:barstyle];
6444 [self positionViews];
6448 - (void) setCancellable:(bool)cancellable {
6450 [self addSubview:cancel_];
6452 [cancel_ removeFromSuperview];
6456 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6457 [progress_ setProgress:0];
6461 [self setCancellable:NO];
6464 - (void) setPrompt:(NSString *)prompt {
6465 [prompt_ setText:prompt];
6468 - (void) setProgress:(float)progress {
6469 [progress_ setProgress:progress];
6475 /* Cydia Navigation Controller Interface {{{ */
6476 @interface UINavigationController (Cydia)
6478 - (NSArray *) navigationURLCollection;
6479 - (void) unloadData;
6484 /* Cydia Tab Bar Controller {{{ */
6485 @interface CYTabBarController : UITabBarController <
6486 UITabBarControllerDelegate,
6489 _transient Database *database_;
6490 _H<RefreshBar> refreshbar_;
6494 // XXX: ok, "updatedelegate_"?...
6495 _transient NSObject<CydiaDelegate> *updatedelegate_;
6498 _H<UIViewController> remembered_;
6499 _transient UIViewController *transient_;
6502 - (NSArray *) navigationURLCollection;
6503 - (void) dropBar:(BOOL)animated;
6504 - (void) beginUpdate;
6505 - (void) raiseBar:(BOOL)animated;
6507 - (void) unloadData;
6511 @implementation CYTabBarController
6513 - (void) setUnselectedViewController:(UIViewController *)transient {
6514 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6515 if (transient != nil) {
6516 if (transient_ == nil)
6517 remembered_ = [controllers objectAtIndex:0];
6518 transient_ = transient;
6519 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6520 [controllers replaceObjectAtIndex:0 withObject:transient_];
6521 [self setSelectedIndex:0];
6522 [self setViewControllers:controllers];
6523 [self concealTabBarSelection];
6524 } else if (remembered_ != nil) {
6525 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6526 transient_ = transient;
6527 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6529 [self setViewControllers:controllers];
6530 [self revealTabBarSelection];
6534 - (UIViewController *) unselectedViewController {
6538 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6539 if ([self unselectedViewController])
6540 [self setUnselectedViewController:nil];
6543 - (NSArray *) navigationURLCollection {
6544 NSMutableArray *items([NSMutableArray array]);
6546 // XXX: Should this deal with transient view controllers?
6547 for (id navigation in [self viewControllers]) {
6548 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6550 [items addObject:stack];
6556 - (void) unloadData {
6557 UIViewController *selected([self selectedViewController]);
6558 for (UINavigationController *controller in [self viewControllers])
6559 [controller unloadData];
6561 [selected reloadData];
6563 if (UIViewController *unselected = [self unselectedViewController])
6564 [unselected reloadData];
6570 [refreshbar_ setDelegate:nil];
6571 [[NSNotificationCenter defaultCenter] removeObserver:self];
6576 - (id) initWithDatabase:(Database *)database {
6577 if ((self = [super init]) != nil) {
6578 database_ = database;
6579 [self setDelegate:self];
6581 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6582 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6584 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6588 - (void) setUpdate:(NSDate *)date {
6592 - (void) beginUpdate {
6593 [(RefreshBar *) refreshbar_ start];
6596 [updatedelegate_ retainNetworkActivityIndicator];
6600 detachNewThreadSelector:@selector(performUpdate)
6606 - (void) performUpdate { _pooled
6608 status.setDelegate(self);
6609 [database_ updateWithStatus:status];
6612 performSelectorOnMainThread:@selector(completeUpdate)
6618 - (void) stopUpdateWithSelector:(SEL)selector {
6620 [updatedelegate_ releaseNetworkActivityIndicator];
6622 [self raiseBar:YES];
6625 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6628 - (void) completeUpdate {
6631 [self stopUpdateWithSelector:@selector(reloadData)];
6634 - (void) cancelUpdate {
6635 [self stopUpdateWithSelector:@selector(updateData)];
6638 - (void) cancelPressed {
6639 [self cancelUpdate];
6646 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6647 [refreshbar_ setPrompt:[event compoundMessage]];
6650 - (bool) isProgressCancelled {
6654 - (void) setProgressCancellable:(NSNumber *)cancellable {
6655 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6658 - (void) setProgressPercent:(NSNumber *)percent {
6659 [refreshbar_ setProgress:[percent floatValue]];
6662 - (void) setProgressStatus:(NSDictionary *)status {
6664 [self setProgressPercent:[status objectForKey:@"Percent"]];
6667 - (void) setUpdateDelegate:(id)delegate {
6668 updatedelegate_ = delegate;
6671 - (CGFloat) statusBarHeight {
6672 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6673 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6675 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6679 - (UIView *) transitionView {
6680 if ([self respondsToSelector:@selector(_transitionView)])
6681 return [self _transitionView];
6683 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6686 - (void) dropBar:(BOOL)animated {
6691 UIView *transition([self transitionView]);
6692 [[self view] addSubview:refreshbar_];
6694 CGRect barframe([refreshbar_ frame]);
6696 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6697 barframe.origin.y = [self statusBarHeight];
6699 barframe.origin.y = 0;
6701 [refreshbar_ setFrame:barframe];
6704 [UIView beginAnimations:nil context:NULL];
6706 CGRect viewframe = [transition frame];
6707 viewframe.origin.y += barframe.size.height;
6708 viewframe.size.height -= barframe.size.height;
6709 [transition setFrame:viewframe];
6712 [UIView commitAnimations];
6714 // Ensure bar has the proper width for our view, it might have changed
6715 barframe.size.width = viewframe.size.width;
6716 [refreshbar_ setFrame:barframe];
6718 // XXX: fix Apple's layout bug
6719 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6722 - (void) raiseBar:(BOOL)animated {
6727 UIView *transition([self transitionView]);
6728 [refreshbar_ removeFromSuperview];
6730 CGRect barframe([refreshbar_ frame]);
6733 [UIView beginAnimations:nil context:NULL];
6735 CGRect viewframe = [transition frame];
6736 viewframe.origin.y -= barframe.size.height;
6737 viewframe.size.height += barframe.size.height;
6738 [transition setFrame:viewframe];
6741 [UIView commitAnimations];
6743 // XXX: fix Apple's layout bug
6744 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6748 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6749 // XXX: fix Apple's layout bug
6750 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6754 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6755 bool dropped(dropped_);
6760 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6765 // XXX: fix Apple's layout bug
6766 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6769 - (void) statusBarFrameChanged:(NSNotification *)notification {
6779 /* Cydia Navigation Controller Implementation {{{ */
6780 @implementation UINavigationController (Cydia)
6782 - (NSArray *) navigationURLCollection {
6783 NSMutableArray *stack([NSMutableArray array]);
6785 for (CyteViewController *controller in [self viewControllers]) {
6786 NSString *url = [[controller navigationURL] absoluteString];
6788 [stack addObject:url];
6794 - (void) reloadData {
6797 if (UIViewController *visible = [self visibleViewController])
6798 [visible reloadData];
6801 - (void) unloadData {
6802 for (CyteViewController *page in [self viewControllers])
6811 /* Cydia:// Protocol {{{ */
6812 @interface CydiaURLProtocol : NSURLProtocol {
6817 @implementation CydiaURLProtocol
6819 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6820 NSURL *url([request URL]);
6824 NSString *scheme([[url scheme] lowercaseString]);
6825 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6827 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6833 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6837 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6838 id<NSURLProtocolClient> client([self client]);
6840 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6842 NSData *data(UIImagePNGRepresentation(icon));
6844 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6845 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6846 [client URLProtocol:self didLoadData:data];
6847 [client URLProtocolDidFinishLoading:self];
6851 - (void) startLoading {
6852 id<NSURLProtocolClient> client([self client]);
6853 NSURLRequest *request([self request]);
6855 NSURL *url([request URL]);
6856 NSString *href([url absoluteString]);
6857 NSString *scheme([[url scheme] lowercaseString]);
6861 if ([scheme isEqualToString:@"cydia"])
6862 path = [href substringFromIndex:8];
6863 else if ([scheme isEqualToString:@"about"])
6864 path = [href substringFromIndex:12];
6865 else _assert(false);
6867 NSRange slash([path rangeOfString:@"/"]);
6870 if (slash.location == NSNotFound) {
6874 command = [path substringToIndex:slash.location];
6875 path = [path substringFromIndex:(slash.location + 1)];
6878 Database *database([Database sharedInstance]);
6880 if ([command isEqualToString:@"package-icon"]) {
6883 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6884 Package *package([database packageWithName:path]);
6887 UIImage *icon([package icon]);
6888 [self _returnPNGWithImage:icon forRequest:request];
6889 } else if ([command isEqualToString:@"source-icon"]) {
6892 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6893 NSString *source(Simplify(path));
6894 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6896 icon = [UIImage applicationImageNamed:@"unknown.png"];
6897 [self _returnPNGWithImage:icon forRequest:request];
6898 } else if ([command isEqualToString:@"uikit-image"]) {
6901 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6902 UIImage *icon(_UIImageWithName(path));
6903 [self _returnPNGWithImage:icon forRequest:request];
6904 } else if ([command isEqualToString:@"section-icon"]) {
6907 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6908 NSString *section(Simplify(path));
6909 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6911 icon = [UIImage applicationImageNamed:@"unknown.png"];
6912 [self _returnPNGWithImage:icon forRequest:request];
6914 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6918 - (void) stopLoading {
6924 /* Section Controller {{{ */
6925 @interface SectionController : FilteredPackageListController {
6926 _H<NSString> section_;
6929 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6933 @implementation SectionController
6935 - (NSURL *) navigationURL {
6936 NSString *name = section_;
6940 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6943 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6946 title = UCLocalize("ALL_PACKAGES");
6947 else if (![name isEqual:@""])
6948 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6950 title = UCLocalize("NO_SECTION");
6952 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6959 /* Sections Controller {{{ */
6960 @interface SectionsController : CyteViewController <
6961 UITableViewDataSource,
6964 _transient Database *database_;
6965 _H<NSMutableArray> sections_;
6966 _H<NSMutableArray> filtered_;
6967 _H<UITableView> list_;
6970 - (id) initWithDatabase:(Database *)database;
6971 - (void) editButtonClicked;
6975 @implementation SectionsController
6977 - (NSURL *) navigationURL {
6978 return [NSURL URLWithString:@"cydia://sections"];
6981 - (void) updateNavigationItem {
6982 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6983 if ([sections_ count] == 0) {
6984 [[self navigationItem] setRightBarButtonItem:nil];
6986 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6987 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6989 action:@selector(editButtonClicked)
6990 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6994 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6995 [super setEditing:editing animated:animated];
7000 [delegate_ updateData];
7002 [self updateNavigationItem];
7005 - (void) viewDidAppear:(BOOL)animated {
7006 [super viewDidAppear:animated];
7007 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7010 - (void) viewWillDisappear:(BOOL)animated {
7011 [super viewWillDisappear:animated];
7012 if ([self isEditing]) [self setEditing:NO];
7015 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7016 Section *section = nil;
7017 int index = [indexPath row];
7018 if (![self isEditing]) {
7021 section = [filtered_ objectAtIndex:index];
7023 section = [sections_ objectAtIndex:index];
7028 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7029 if ([self isEditing])
7030 return [sections_ count];
7032 return [filtered_ count] + 1;
7035 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7039 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7040 static NSString *reuseIdentifier = @"SectionCell";
7042 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7044 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7046 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7051 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7052 if ([self isEditing])
7055 Section *section = [self sectionAtIndexPath:indexPath];
7057 SectionController *controller = [[[SectionController alloc]
7058 initWithDatabase:database_
7059 section:[section name]
7061 [controller setDelegate:delegate_];
7063 [[self navigationController] pushViewController:controller animated:YES];
7067 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7069 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7070 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7071 [list_ setRowHeight:45.0f];
7072 [(UITableView *) list_ setDataSource:self];
7073 [list_ setDelegate:self];
7074 [[self view] addSubview:list_];
7077 - (void) viewDidLoad {
7078 [super viewDidLoad];
7080 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7083 - (void) releaseSubviews {
7087 - (id) initWithDatabase:(Database *)database {
7088 if ((self = [super init]) != nil) {
7089 database_ = database;
7091 sections_ = [NSMutableArray arrayWithCapacity:16];
7092 filtered_ = [NSMutableArray arrayWithCapacity:16];
7096 - (void) reloadData {
7099 NSArray *packages = [database_ packages];
7101 [sections_ removeAllObjects];
7102 [filtered_ removeAllObjects];
7104 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7107 for (Package *package in packages) {
7108 NSString *name([package section]);
7109 NSString *key(name == nil ? @"" : name);
7113 _profile(SectionsView$reloadData$Section)
7114 section = [sections objectForKey:key];
7115 if (section == nil) {
7116 _profile(SectionsView$reloadData$Section$Allocate)
7117 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7118 [sections setObject:section forKey:key];
7123 [section addToCount];
7125 _profile(SectionsView$reloadData$Filter)
7126 if (![package valid] || ![package visible])
7134 [sections_ addObjectsFromArray:[sections allValues]];
7136 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7138 for (Section *section in (id) sections_) {
7139 size_t count([section row]);
7143 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7144 [section setCount:count];
7145 [filtered_ addObject:section];
7148 [self updateNavigationItem];
7153 - (void) editButtonClicked {
7154 [self setEditing:![self isEditing] animated:YES];
7160 /* Changes Controller {{{ */
7161 @interface ChangesController : CyteViewController <
7162 UITableViewDataSource,
7165 _transient Database *database_;
7167 CFMutableArrayRef packages_;
7168 _H<NSMutableArray> sections_;
7169 _H<UITableView> list_;
7173 - (id) initWithDatabase:(Database *)database;
7177 @implementation ChangesController
7180 CFRelease(packages_);
7184 - (NSURL *) navigationURL {
7185 return [NSURL URLWithString:@"cydia://changes"];
7188 - (void) viewDidAppear:(BOOL)animated {
7189 [super viewDidAppear:animated];
7190 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7193 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7194 NSInteger count([sections_ count]);
7195 return count == 0 ? 1 : count;
7198 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7199 if ([sections_ count] == 0)
7201 return [[sections_ objectAtIndex:section] name];
7204 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7205 if ([sections_ count] == 0)
7207 return [[sections_ objectAtIndex:section] count];
7210 - (Package *) packageAtIndex:(NSUInteger)index {
7211 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7214 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7215 @synchronized (database_) {
7216 if ([database_ era] != era_)
7219 NSUInteger sectionIndex([path section]);
7220 if (sectionIndex >= [sections_ count])
7222 Section *section([sections_ objectAtIndex:sectionIndex]);
7223 NSInteger row([path row]);
7224 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7227 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7228 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7230 cell = [[[PackageCell alloc] init] autorelease];
7231 [cell setPackage:[self packageAtIndexPath:path]];
7235 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7236 Package *package([self packageAtIndexPath:path]);
7237 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7238 [view setDelegate:delegate_];
7239 [[self navigationController] pushViewController:view animated:YES];
7243 - (void) refreshButtonClicked {
7244 [delegate_ beginUpdate];
7245 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7248 - (void) upgradeButtonClicked {
7249 [delegate_ distUpgrade];
7253 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7255 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7256 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7257 [list_ setRowHeight:73];
7258 [(UITableView *) list_ setDataSource:self];
7259 [list_ setDelegate:self];
7260 [[self view] addSubview:list_];
7263 - (void) viewDidLoad {
7264 [super viewDidLoad];
7266 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7269 - (void) releaseSubviews {
7273 - (id) initWithDatabase:(Database *)database {
7274 if ((self = [super init]) != nil) {
7275 database_ = database;
7277 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7278 sections_ = [NSMutableArray arrayWithCapacity:16];
7282 // this mostly works because reloadData (below) is @synchronized (database_)
7283 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7284 - (void) _reloadPackages:(NSArray *)packages {
7285 CFRelease(packages_);
7286 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7289 _profile(ChangesController$_reloadPackages$Filter)
7290 for (Package *package in packages)
7291 if ([package upgradableAndEssential:YES] || [package visible])
7292 CFArrayAppendValue(packages_, package);
7295 _profile(ChangesController$_reloadPackages$radixSort)
7296 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7301 - (void) _reloadData {
7302 @synchronized (database_) {
7303 era_ = [database_ era];
7304 NSArray *packages = [database_ packages];
7307 UIProgressHUD *hud([delegate_ addProgressHUD]);
7308 [hud setText:UCLocalize("LOADING")];
7309 //NSLog(@"HUD:%@::%@", delegate_, hud);
7310 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7311 [delegate_ removeProgressHUD:hud];
7313 [self _reloadPackages:packages];
7316 [sections_ removeAllObjects];
7318 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7319 Section *ignored = nil;
7320 Section *section = nil;
7324 bool unseens = false;
7326 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7328 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7329 Package *package = [self packageAtIndex:offset];
7331 BOOL uae = [package upgradableAndEssential:YES];
7335 time_t seen([package seen]);
7337 if (section == nil || last != seen) {
7341 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7344 _profile(ChangesController$reloadData$Allocate)
7345 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7346 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7347 [sections_ addObject:section];
7351 [section addToCount];
7352 } else if ([package ignored]) {
7353 if (ignored == nil) {
7354 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7356 [ignored addToCount];
7359 [upgradable addToCount];
7364 CFRelease(formatter);
7367 Section *last = [sections_ lastObject];
7368 size_t count = [last count];
7369 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7370 [sections_ removeLastObject];
7373 if ([ignored count] != 0)
7374 [sections_ insertObject:ignored atIndex:0];
7376 [sections_ insertObject:upgradable atIndex:0];
7381 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7382 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7383 style:UIBarButtonItemStylePlain
7385 action:@selector(upgradeButtonClicked)
7388 if (![delegate_ updating])
7389 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7390 initWithTitle:UCLocalize("REFRESH")
7391 style:UIBarButtonItemStylePlain
7393 action:@selector(refreshButtonClicked)
7399 - (void) reloadData {
7401 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7406 /* Search Controller {{{ */
7407 @interface SearchController : FilteredPackageListController <
7410 _H<UISearchBar> search_;
7414 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7415 - (void) reloadData;
7419 @implementation SearchController
7422 [search_ setDelegate:nil];
7426 - (NSURL *) navigationURL {
7427 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7428 return [NSURL URLWithString:@"cydia://search"];
7430 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7433 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7434 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7437 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7438 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7439 [search_ resignFirstResponder];
7443 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7444 [search_ setText:@""];
7445 [self searchBarButtonClicked:searchBar];
7448 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7449 [self searchBarButtonClicked:searchBar];
7452 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7453 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7457 - (bool) shouldYield {
7458 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7461 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7462 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7463 search_ = [[[UISearchBar alloc] init] autorelease];
7464 [search_ setDelegate:self];
7467 [search_ setText:query];
7471 - (void) viewDidAppear:(BOOL)animated {
7472 [super viewDidAppear:animated];
7474 if (!searchloaded_) {
7475 searchloaded_ = YES;
7476 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7477 [search_ layoutSubviews];
7478 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7480 UITextField *textField;
7481 if ([search_ respondsToSelector:@selector(searchField)])
7482 textField = [search_ searchField];
7484 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7486 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7487 [textField setEnablesReturnKeyAutomatically:NO];
7488 [[self navigationItem] setTitleView:textField];
7492 - (void) reloadData {
7493 [self setObject:[search_ text]];
7499 - (void) didSelectPackage:(Package *)package {
7500 [search_ resignFirstResponder];
7501 [super didSelectPackage:package];
7506 /* Package Settings Controller {{{ */
7507 @interface PackageSettingsController : CyteViewController <
7508 UITableViewDataSource,
7511 _transient Database *database_;
7513 _H<Package> package_;
7514 _H<UITableView> table_;
7515 _H<UISwitch> subscribedSwitch_;
7516 _H<UISwitch> ignoredSwitch_;
7517 _H<UITableViewCell> subscribedCell_;
7518 _H<UITableViewCell> ignoredCell_;
7521 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7525 @implementation PackageSettingsController
7527 - (NSURL *) navigationURL {
7528 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7531 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7532 if (package_ == nil)
7535 if ([package_ installed] == nil)
7541 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7542 if (package_ == nil)
7545 // both sections contain just one item right now.
7549 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7553 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7555 return UCLocalize("SHOW_ALL_CHANGES_EX");
7557 return UCLocalize("IGNORE_UPGRADES_EX");
7560 - (void) onSubscribed:(id)control {
7561 bool value([control isOn]);
7562 if (package_ == nil)
7564 if ([package_ setSubscribed:value])
7565 [delegate_ updateData];
7568 - (void) _updateIgnored {
7569 const char *package([name_ UTF8String]);
7570 bool on([ignoredSwitch_ isOn]);
7572 pid_t pid(ExecFork());
7574 FILE *dpkg(popen("dpkg --set-selections", "w"));
7575 fwrite(package, strlen(package), 1, dpkg);
7578 fwrite(" hold\n", 6, 1, dpkg);
7580 fwrite(" install\n", 9, 1, dpkg);
7590 int result(waitpid(pid, &status, 0));
7593 _assert(result == pid);
7599 - (void) onIgnored:(id)control {
7600 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7601 [invocation setTarget:self];
7602 [invocation setSelector:@selector(_updateIgnored)];
7604 [delegate_ reloadDataWithInvocation:invocation];
7607 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7608 if (package_ == nil)
7611 switch ([indexPath section]) {
7612 case 0: return subscribedCell_;
7613 case 1: return ignoredCell_;
7622 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7624 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7625 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7626 [(UITableView *) table_ setDataSource:self];
7627 [table_ setDelegate:self];
7628 [[self view] addSubview:table_];
7630 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7631 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7632 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7634 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7635 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7636 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7638 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7639 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7640 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7641 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7643 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7644 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7645 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7646 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7649 - (void) viewDidLoad {
7650 [super viewDidLoad];
7652 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7655 - (void) releaseSubviews {
7657 subscribedCell_ = nil;
7659 ignoredSwitch_ = nil;
7660 subscribedSwitch_ = nil;
7663 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7664 if ((self = [super init]) != nil) {
7665 database_ = database;
7670 - (void) reloadData {
7673 package_ = [database_ packageWithName:name_];
7675 if (package_ != nil) {
7676 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7677 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7678 } // XXX: what now, G?
7680 [table_ reloadData];
7686 /* Installed Controller {{{ */
7687 @interface InstalledController : FilteredPackageListController {
7691 - (id) initWithDatabase:(Database *)database;
7693 - (void) updateRoleButton;
7694 - (void) queueStatusDidChange;
7698 @implementation InstalledController
7704 - (NSURL *) navigationURL {
7705 return [NSURL URLWithString:@"cydia://installed"];
7708 - (id) initWithDatabase:(Database *)database {
7709 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7710 [self updateRoleButton];
7711 [self queueStatusDidChange];
7716 - (void) queueButtonClicked {
7721 - (void) queueStatusDidChange {
7725 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7726 initWithTitle:UCLocalize("QUEUE")
7727 style:UIBarButtonItemStyleDone
7729 action:@selector(queueButtonClicked)
7732 [[self navigationItem] setLeftBarButtonItem:nil];
7738 - (void) updateRoleButton {
7739 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7740 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7741 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7742 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7744 action:@selector(roleButtonClicked)
7748 - (void) roleButtonClicked {
7749 [self setObject:[NSNumber numberWithBool:expert_]];
7753 [self updateRoleButton];
7759 /* Source Cell {{{ */
7760 @interface SourceCell : CYTableViewCell <
7764 _H<NSString> origin_;
7765 _H<NSString> label_;
7768 - (void) setSource:(Source *)source;
7772 @implementation SourceCell
7774 - (void) setSource:(Source *)source {
7777 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7779 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7781 origin_ = [source name];
7782 label_ = [source uri];
7784 [content_ setNeedsDisplay];
7787 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7788 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7789 UIView *content([self contentView]);
7790 CGRect bounds([content bounds]);
7792 content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
7793 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7794 [content_ setBackgroundColor:[UIColor whiteColor]];
7795 [content addSubview:content_];
7797 [content_ setDelegate:self];
7798 [content_ setOpaque:YES];
7802 - (NSString *) accessibilityLabel {
7806 - (void) drawContentRect:(CGRect)rect {
7807 bool highlighted(highlighted_);
7808 float width(rect.size.width);
7811 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7818 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7822 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7827 /* Source Controller {{{ */
7828 @interface SourceController : FilteredPackageListController {
7829 _transient Source *source_;
7833 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7837 @implementation SourceController
7839 - (NSURL *) navigationURL {
7840 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7843 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7844 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7846 key_ = [source key];
7850 - (void) reloadData {
7851 source_ = [database_ sourceWithKey:key_];
7852 key_ = [source_ key];
7853 [self setObject:source_];
7855 [[self navigationItem] setTitle:[source_ label]];
7862 /* Sources Controller {{{ */
7863 @interface SourcesController : CyteViewController <
7864 UITableViewDataSource,
7867 _transient Database *database_;
7868 _H<UITableView> list_;
7869 _H<NSMutableArray> sources_;
7873 _H<UIProgressHUD> hud_;
7876 //NSURLConnection *installer_;
7877 NSURLConnection *trivial_;
7878 NSURLConnection *trivial_bz2_;
7879 NSURLConnection *trivial_gz_;
7880 //NSURLConnection *automatic_;
7885 - (id) initWithDatabase:(Database *)database;
7886 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7890 @implementation SourcesController
7892 - (void) _releaseConnection:(NSURLConnection *)connection {
7893 if (connection != nil) {
7894 [connection cancel];
7895 //[connection setDelegate:nil];
7896 [connection release];
7901 //[self _releaseConnection:installer_];
7902 [self _releaseConnection:trivial_];
7903 [self _releaseConnection:trivial_gz_];
7904 [self _releaseConnection:trivial_bz2_];
7905 //[self _releaseConnection:automatic_];
7910 - (NSURL *) navigationURL {
7911 return [NSURL URLWithString:@"cydia://sources"];
7914 - (void) viewDidAppear:(BOOL)animated {
7915 [super viewDidAppear:animated];
7916 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7919 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7920 return offset_ == 0 ? 1 : 2;
7923 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7924 switch (section + (offset_ == 0 ? 1 : 0)) {
7925 case 0: return UCLocalize("ENTERED_BY_USER");
7926 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7932 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7933 int count = [sources_ count];
7935 case 0: return (offset_ == 0 ? count : offset_);
7936 case 1: return count - offset_;
7942 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7944 switch (indexPath.section) {
7945 case 0: idx = indexPath.row; break;
7946 case 1: idx = indexPath.row + offset_; break;
7950 return [sources_ objectAtIndex:idx];
7953 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7954 static NSString *cellIdentifier = @"SourceCell";
7956 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7957 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7958 [cell setSource:[self sourceAtIndexPath:indexPath]];
7959 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7964 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7965 Source *source = [self sourceAtIndexPath:indexPath];
7967 SourceController *controller = [[[SourceController alloc]
7968 initWithDatabase:database_
7972 [controller setDelegate:delegate_];
7974 [[self navigationController] pushViewController:controller animated:YES];
7977 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7978 Source *source = [self sourceAtIndexPath:indexPath];
7979 return [source record] != nil;
7982 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7983 if (editingStyle == UITableViewCellEditingStyleDelete) {
7984 Source *source = [self sourceAtIndexPath:indexPath];
7985 [Sources_ removeObjectForKey:[source key]];
7986 [delegate_ syncData];
7991 [delegate_ addTrivialSource:href_];
7992 [delegate_ syncData];
7995 - (NSString *) getWarning {
7996 NSString *href(href_);
7997 NSRange colon([href rangeOfString:@"://"]);
7998 if (colon.location != NSNotFound)
7999 href = [href substringFromIndex:(colon.location + 3)];
8000 href = [href stringByAddingPercentEscapes];
8001 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8002 href = [href stringByCachingURLWithCurrentCDN];
8004 NSURL *url([NSURL URLWithString:href]);
8006 NSStringEncoding encoding;
8007 NSError *error(nil);
8009 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8010 return [warning length] == 0 ? nil : warning;
8014 - (void) _endConnection:(NSURLConnection *)connection {
8015 // XXX: the memory management in this method is horribly awkward
8017 NSURLConnection **field = NULL;
8018 if (connection == trivial_)
8020 else if (connection == trivial_bz2_)
8021 field = &trivial_bz2_;
8022 else if (connection == trivial_gz_)
8023 field = &trivial_gz_;
8024 _assert(field != NULL);
8025 [connection release];
8030 trivial_bz2_ == nil &&
8033 [delegate_ releaseNetworkActivityIndicator];
8035 [delegate_ removeProgressHUD:hud_];
8041 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8044 UIAlertView *alert = [[[UIAlertView alloc]
8045 initWithTitle:UCLocalize("SOURCE_WARNING")
8048 cancelButtonTitle:UCLocalize("CANCEL")
8050 UCLocalize("ADD_ANYWAY"),
8054 [alert setContext:@"warning"];
8055 [alert setNumberOfRows:1];
8059 } else if (error_ != nil) {
8060 UIAlertView *alert = [[[UIAlertView alloc]
8061 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8062 message:[error_ localizedDescription]
8064 cancelButtonTitle:UCLocalize("OK")
8065 otherButtonTitles:nil
8068 [alert setContext:@"urlerror"];
8071 UIAlertView *alert = [[[UIAlertView alloc]
8072 initWithTitle:UCLocalize("NOT_REPOSITORY")
8073 message:UCLocalize("NOT_REPOSITORY_EX")
8075 cancelButtonTitle:UCLocalize("OK")
8076 otherButtonTitles:nil
8079 [alert setContext:@"trivial"];
8088 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8089 switch ([response statusCode]) {
8095 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8096 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8098 [self _endConnection:connection];
8101 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8102 [self _endConnection:connection];
8105 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8106 NSMutableURLRequest *request = [NSMutableURLRequest
8107 requestWithURL:[NSURL URLWithString:href]
8108 cachePolicy:NSURLRequestUseProtocolCachePolicy
8109 timeoutInterval:120.0
8112 [request setHTTPMethod:method];
8114 if (Machine_ != NULL)
8115 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8116 if (UniqueID_ != nil)
8117 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8119 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8122 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8123 NSString *context([alert context]);
8125 if ([context isEqualToString:@"source"]) {
8128 NSString *href = [[alert textField] text];
8130 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8132 if (![href hasSuffix:@"/"])
8133 href_ = [href stringByAppendingString:@"/"];
8137 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8138 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8139 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8140 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8144 // XXX: this is stupid
8145 hud_ = [delegate_ addProgressHUD];
8146 [hud_ setText:UCLocalize("VERIFYING_URL")];
8147 [delegate_ retainNetworkActivityIndicator];
8156 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8157 } else if ([context isEqualToString:@"trivial"])
8158 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8159 else if ([context isEqualToString:@"urlerror"])
8160 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8161 else if ([context isEqualToString:@"warning"]) {
8175 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8180 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8182 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8183 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8184 [list_ setRowHeight:56];
8185 [(UITableView *) list_ setDataSource:self];
8186 [list_ setDelegate:self];
8187 [[self view] addSubview:list_];
8190 - (void) viewDidLoad {
8191 [super viewDidLoad];
8193 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8194 [self updateButtonsForEditingStatus:NO animated:NO];
8197 - (void) releaseSubviews {
8201 - (id) initWithDatabase:(Database *)database {
8202 if ((self = [super init]) != nil) {
8203 database_ = database;
8204 sources_ = [NSMutableArray arrayWithCapacity:16];
8208 - (void) reloadData {
8212 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8215 [sources_ removeAllObjects];
8216 [sources_ addObjectsFromArray:[database_ sources]];
8218 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8221 int count([sources_ count]);
8223 for (int i = 0; i != count; i++) {
8224 if ([[sources_ objectAtIndex:i] record] == nil)
8229 [list_ setEditing:NO];
8230 [self updateButtonsForEditingStatus:NO animated:NO];
8234 - (void) showAddSourcePrompt {
8235 UIAlertView *alert = [[[UIAlertView alloc]
8236 initWithTitle:UCLocalize("ENTER_APT_URL")
8239 cancelButtonTitle:UCLocalize("CANCEL")
8241 UCLocalize("ADD_SOURCE"),
8245 [alert setContext:@"source"];
8246 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8248 [alert setNumberOfRows:1];
8249 [alert addTextFieldWithValue:@"http://" label:@""];
8251 UITextInputTraits *traits = [[alert textField] textInputTraits];
8252 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8253 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8254 [traits setKeyboardType:UIKeyboardTypeURL];
8255 // XXX: UIReturnKeyDone
8256 [traits setReturnKeyType:UIReturnKeyNext];
8261 - (void) addButtonClicked {
8262 [self showAddSourcePrompt];
8265 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8266 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8267 initWithTitle:UCLocalize("ADD")
8268 style:UIBarButtonItemStylePlain
8270 action:@selector(addButtonClicked)
8271 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8273 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8274 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8275 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8277 action:@selector(editButtonClicked)
8278 ] autorelease] animated:animated];
8280 if (IsWildcat_ && !editing)
8281 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8282 initWithTitle:UCLocalize("SETTINGS")
8283 style:UIBarButtonItemStylePlain
8285 action:@selector(settingsButtonClicked)
8289 - (void) settingsButtonClicked {
8290 [delegate_ showSettings];
8293 - (void) editButtonClicked {
8294 [list_ setEditing:![list_ isEditing] animated:YES];
8296 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8302 /* Settings Controller {{{ */
8303 @interface SettingsController : CyteViewController <
8304 UITableViewDataSource,
8307 _transient Database *database_;
8308 // XXX: ok, "roledelegate_"?...
8309 _transient id roledelegate_;
8310 _H<UITableView> table_;
8311 _H<UISegmentedControl> segment_;
8312 _H<UIView> container_;
8315 - (void) showDoneButton;
8316 - (void) resizeSegmentedControl;
8320 @implementation SettingsController
8323 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8325 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8326 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8327 [table_ setDelegate:self];
8328 [(UITableView *) table_ setDataSource:self];
8329 [[self view] addSubview:table_];
8331 NSArray *items = [NSArray arrayWithObjects:
8333 UCLocalize("HACKER"),
8334 UCLocalize("DEVELOPER"),
8336 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8337 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8338 [container_ addSubview:segment_];
8341 - (void) viewDidLoad {
8342 [super viewDidLoad];
8344 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8347 if ([Role_ isEqualToString:@"User"]) index = 0;
8348 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8349 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8351 [segment_ setSelectedSegmentIndex:index];
8352 [self showDoneButton];
8355 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8356 [self resizeSegmentedControl];
8359 - (void) releaseSubviews {
8365 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8366 if ((self = [super init]) != nil) {
8367 database_ = database;
8368 roledelegate_ = delegate;
8372 - (void) resizeSegmentedControl {
8373 CGFloat width = [[self view] frame].size.width;
8374 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8377 - (void) viewWillAppear:(BOOL)animated {
8378 [super viewWillAppear:animated];
8380 [self resizeSegmentedControl];
8383 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8384 [self resizeSegmentedControl];
8387 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8388 [self resizeSegmentedControl];
8392 NSString *role(nil);
8394 switch ([segment_ selectedSegmentIndex]) {
8395 case 0: role = @"User"; break;
8396 case 1: role = @"Hacker"; break;
8397 case 2: role = @"Developer"; break;
8402 if (![role isEqualToString:Role_]) {
8403 bool rolling(Role_ == nil);
8406 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8410 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8414 [roledelegate_ loadData];
8416 [roledelegate_ updateData];
8420 - (void) segmentChanged:(UISegmentedControl *)control {
8421 [self showDoneButton];
8424 - (void) saveAndClose {
8427 [[self navigationItem] setRightBarButtonItem:nil];
8428 [[self navigationController] dismissModalViewControllerAnimated:YES];
8431 - (void) doneButtonClicked {
8432 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8433 [spinner startAnimating];
8434 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8435 [[self navigationItem] setRightBarButtonItem:spinItem];
8437 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8440 - (void) showDoneButton {
8441 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8442 initWithTitle:UCLocalize("DONE")
8443 style:UIBarButtonItemStyleDone
8445 action:@selector(doneButtonClicked)
8446 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8449 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8450 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8454 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8458 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8459 return nil; // This method is required by the protocol.
8462 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8464 return UCLocalize("ROLE_EX");
8466 return [NSString stringWithFormat:
8467 @"%@: %@\n%@: %@\n%@: %@",
8468 UCLocalize("USER"), UCLocalize("USER_EX"),
8469 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8470 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8475 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8476 return section == 3 ? 44.0f : 0;
8479 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8480 return section == 3 ? container_ : nil;
8483 - (void) reloadData {
8486 [table_ reloadData];
8491 /* Stash Controller {{{ */
8492 @interface StashController : CyteViewController {
8493 _H<UIActivityIndicatorView> spinner_;
8494 _H<UILabel> status_;
8495 _H<UILabel> caption_;
8500 @implementation StashController
8503 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8504 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8506 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8507 CGRect spinrect = [spinner_ frame];
8508 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8509 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8510 [spinner_ setFrame:spinrect];
8511 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8512 [[self view] addSubview:spinner_];
8513 [spinner_ startAnimating];
8516 captrect.size.width = [[self view] frame].size.width;
8517 captrect.size.height = 40.0f;
8518 captrect.origin.x = 0;
8519 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8520 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8521 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8522 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8523 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8524 [caption_ setTextColor:[UIColor whiteColor]];
8525 [caption_ setBackgroundColor:[UIColor clearColor]];
8526 [caption_ setShadowColor:[UIColor blackColor]];
8527 [caption_ setTextAlignment:UITextAlignmentCenter];
8528 [[self view] addSubview:caption_];
8531 statusrect.size.width = [[self view] frame].size.width;
8532 statusrect.size.height = 30.0f;
8533 statusrect.origin.x = 0;
8534 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8535 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8536 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8537 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8538 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8539 [status_ setTextColor:[UIColor whiteColor]];
8540 [status_ setBackgroundColor:[UIColor clearColor]];
8541 [status_ setShadowColor:[UIColor blackColor]];
8542 [status_ setTextAlignment:UITextAlignmentCenter];
8543 [[self view] addSubview:status_];
8549 @interface CYURLCache : SDURLCache {
8554 @implementation CYURLCache
8556 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8559 else if ([event isEqualToString:@"no-cache"])
8561 else if ([event isEqualToString:@"store"])
8563 else if ([event isEqualToString:@"invalid"])
8565 else if ([event isEqualToString:@"memory"])
8567 else if ([event isEqualToString:@"disk"])
8569 else if ([event isEqualToString:@"miss"])
8572 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8578 @interface Cydia : UIApplication <
8579 ConfirmationControllerDelegate,
8582 UINavigationControllerDelegate,
8583 UITabBarControllerDelegate
8585 _H<UIWindow> window_;
8586 _H<CYTabBarController> tabbar_;
8587 _H<CYEmulatedLoadingController> emulated_;
8589 _H<NSMutableArray> essential_;
8590 _H<NSMutableArray> broken_;
8592 Database *database_;
8594 _H<NSURL> starturl_;
8599 _H<StashController> stash_;
8608 @implementation Cydia
8610 - (void) beginUpdate {
8611 [tabbar_ beginUpdate];
8615 return [tabbar_ updating];
8619 if ([broken_ count] != 0) {
8620 int count = [broken_ count];
8622 UIAlertView *alert = [[[UIAlertView alloc]
8623 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8624 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8626 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8628 UCLocalize("TEMPORARY_IGNORE"),
8632 [alert setContext:@"fixhalf"];
8633 [alert setNumberOfRows:2];
8635 } else if (!Ignored_ && [essential_ count] != 0) {
8636 int count = [essential_ count];
8638 UIAlertView *alert = [[[UIAlertView alloc]
8639 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8640 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8642 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8644 UCLocalize("UPGRADE_ESSENTIAL"),
8645 UCLocalize("COMPLETE_UPGRADE"),
8649 [alert setContext:@"upgrade"];
8654 - (void) _saveConfig {
8660 NSString *error(nil);
8662 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8664 NSError *error(nil);
8665 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8666 NSLog(@"failure to save metadata data: %@", error);
8671 NSLog(@"failure to serialize metadata: %@", error);
8676 // Navigation controller for the queuing badge.
8677 - (UINavigationController *) queueNavigationController {
8678 NSArray *controllers = [tabbar_ viewControllers];
8679 return [controllers objectAtIndex:3];
8682 - (void) unloadData {
8683 [tabbar_ unloadData];
8686 - (void) _updateData {
8691 UINavigationController *navigation = [self queueNavigationController];
8693 id queuedelegate = nil;
8694 if ([[navigation viewControllers] count] > 0)
8695 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8697 [queuedelegate queueStatusDidChange];
8698 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8701 - (void) _refreshIfPossible:(NSDate *)update {
8702 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8704 bool recently = false;
8705 if (update != nil) {
8706 NSTimeInterval interval([update timeIntervalSinceNow]);
8707 if (interval <= 0 && interval > -(15*60))
8711 // Don't automatic refresh if:
8712 // - We already refreshed recently.
8713 // - We already auto-refreshed this launch.
8714 // - Auto-refresh is disabled.
8715 if (recently || loaded_ || ManualRefresh) {
8716 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8718 // If we are cancelling, we need to make sure it knows it's already loaded.
8722 // We are going to load, so remember that.
8726 SCNetworkReachabilityFlags flags; {
8727 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8728 SCNetworkReachabilityGetFlags(reachability, &flags);
8729 CFRelease(reachability);
8732 // XXX: this elaborate mess is what Apple is using to determine this? :(
8733 // XXX: do we care if the user has to intervene? maybe that's ok?
8735 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8736 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8737 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8738 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8739 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8740 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8744 // If we can reach the server, auto-refresh!
8746 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8751 - (void) refreshIfPossible {
8752 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8755 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8756 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8757 [hud setText:UCLocalize("RELOADING_DATA")];
8759 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8762 [self removeProgressHUD:hud];
8766 [essential_ removeAllObjects];
8767 [broken_ removeAllObjects];
8769 NSArray *packages([database_ packages]);
8770 for (Package *package in packages) {
8772 [broken_ addObject:package];
8773 if ([package upgradableAndEssential:NO]) {
8774 if ([package essential])
8775 [essential_ addObject:package];
8780 NSLog(@"changes:#%u", changes);
8782 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8785 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8786 [changesItem setBadgeValue:badge];
8787 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8788 [self setApplicationIconBadgeNumber:changes];
8791 [changesItem setBadgeValue:nil];
8792 [changesItem setAnimatedBadge:NO];
8793 [self setApplicationIconBadgeNumber:0];
8798 [self refreshIfPossible];
8801 - (void) updateData {
8810 @synchronized (self) {
8811 [self _reloadDataWithInvocation:nil];
8815 - (void) disemulate {
8816 if (emulated_ == nil)
8819 [window_ addSubview:[tabbar_ view]];
8820 [[emulated_ view] removeFromSuperview];
8822 [window_ setUserInteractionEnabled:YES];
8825 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8826 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8828 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8830 UIViewController *parent;
8831 if (emulated_ == nil)
8840 [parent presentModalViewController:navigation animated:YES];
8843 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8844 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8846 if (navigation != nil)
8847 [navigation pushViewController:progress animated:YES];
8849 [self presentModalViewController:progress force:YES];
8851 [progress invoke:invocation withTitle:title];
8855 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8856 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8859 - (void) repairWithInvocation:(NSInvocation *)invocation {
8861 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8865 - (void) repairWithSelector:(SEL)selector {
8866 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8872 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8873 _assert(file != NULL);
8875 for (NSString *key in [Sources_ allKeys]) {
8876 NSDictionary *source([Sources_ objectForKey:key]);
8878 fprintf(file, "%s %s %s\n",
8879 [[source objectForKey:@"Type"] UTF8String],
8880 [[source objectForKey:@"URI"] UTF8String],
8881 [[source objectForKey:@"Distribution"] UTF8String]
8887 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8892 - (void) addTrivialSource:(NSString *)href {
8893 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8896 @"./", @"Distribution",
8897 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8902 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8903 @synchronized (self) {
8904 [self _reloadDataWithInvocation:invocation];
8908 - (void) reloadData {
8909 [self reloadDataWithInvocation:nil];
8913 pkgProblemResolver *resolver = [database_ resolver];
8915 resolver->InstallProtect();
8916 if (!resolver->Resolve(true))
8921 // XXX: this is a really crappy way of doing this.
8922 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8923 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8924 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8925 if ([tabbar_ updating])
8926 [tabbar_ cancelUpdate];
8928 if (![database_ prepare])
8931 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8932 [page setDelegate:self];
8933 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8936 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8937 [tabbar_ presentModalViewController:confirm_ animated:YES];
8943 @synchronized (self) {
8948 - (void) clearPackage:(Package *)package {
8949 @synchronized (self) {
8956 - (void) installPackages:(NSArray *)packages {
8957 @synchronized (self) {
8958 for (Package *package in packages)
8965 - (void) installPackage:(Package *)package {
8966 @synchronized (self) {
8973 - (void) removePackage:(Package *)package {
8974 @synchronized (self) {
8981 - (void) distUpgrade {
8982 @synchronized (self) {
8983 if (![database_ upgrade])
8989 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8992 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8997 - (void) showSettings {
8998 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9001 - (void) retainNetworkActivityIndicator {
9002 if (activity_++ == 0)
9003 [self setNetworkActivityIndicatorVisible:YES];
9006 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9010 - (void) releaseNetworkActivityIndicator {
9011 if (--activity_ == 0)
9012 [self setNetworkActivityIndicatorVisible:NO];
9015 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9020 - (void) cancelAndClear:(bool)clear {
9021 @synchronized (self) {
9033 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9034 NSString *context([alert context]);
9036 if ([context isEqualToString:@"conffile"]) {
9037 FILE *input = [database_ input];
9038 if (button == [alert cancelButtonIndex])
9039 fprintf(input, "N\n");
9040 else if (button == [alert firstOtherButtonIndex])
9041 fprintf(input, "Y\n");
9044 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9045 } else if ([context isEqualToString:@"fixhalf"]) {
9046 if (button == [alert cancelButtonIndex]) {
9047 @synchronized (self) {
9048 for (Package *broken in (id) broken_) {
9051 NSString *id = [broken id];
9052 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9053 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9054 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9055 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9061 } else if (button == [alert firstOtherButtonIndex]) {
9062 [broken_ removeAllObjects];
9066 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9067 } else if ([context isEqualToString:@"upgrade"]) {
9068 if (button == [alert firstOtherButtonIndex]) {
9069 @synchronized (self) {
9070 for (Package *essential in (id) essential_)
9071 [essential install];
9076 } else if (button == [alert firstOtherButtonIndex] + 1) {
9078 } else if (button == [alert cancelButtonIndex]) {
9082 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9086 - (void) system:(NSString *)command { _pooled
9088 system([command UTF8String]);
9092 - (void) applicationWillSuspend {
9094 [super applicationWillSuspend];
9097 - (BOOL) isSafeToSuspend {
9100 NSLog(@"isSafeToSuspend: locked_ != 0");
9105 // Use external process status API internally.
9106 // This is probably a really bad idea.
9107 // XXX: what is the point of this? does this solve anything at all?
9108 uint64_t status = 0;
9110 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9111 notify_get_state(notify_token, &status);
9112 notify_cancel(notify_token);
9117 NSLog(@"isSafeToSuspend: status != 0");
9123 NSLog(@"isSafeToSuspend: -> true");
9128 - (void) applicationSuspend:(__GSEvent *)event {
9129 if ([self isSafeToSuspend])
9130 [super applicationSuspend:event];
9133 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9134 if ([self isSafeToSuspend])
9135 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9138 - (void) _setSuspended:(BOOL)value {
9139 if ([self isSafeToSuspend])
9140 [super _setSuspended:value];
9143 - (UIProgressHUD *) addProgressHUD {
9144 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9145 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9147 [window_ setUserInteractionEnabled:NO];
9149 UIViewController *target(tabbar_);
9150 if (UIViewController *modal = [target modalViewController])
9153 UIView *view([target view]);
9154 [view addSubview:hud];
9162 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9165 [hud removeFromSuperview];
9166 [window_ setUserInteractionEnabled:YES];
9169 - (CyteViewController *) pageForPackage:(NSString *)name {
9170 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9173 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9174 NSString *scheme([[url scheme] lowercaseString]);
9175 if ([[url absoluteString] length] <= [scheme length] + 3)
9177 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9178 NSArray *components([path pathComponents]);
9180 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9181 return [self pageForPackage:[components objectAtIndex:1]];
9183 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9186 NSString *base([components objectAtIndex:0]);
9188 CyteViewController *controller = nil;
9190 if ([base isEqualToString:@"url"]) {
9191 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9192 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9193 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9194 } else if (!external && [components count] == 1) {
9195 if ([base isEqualToString:@"manage"]) {
9196 controller = [[[ManageController alloc] init] autorelease];
9199 if ([base isEqualToString:@"sources"]) {
9200 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9203 if ([base isEqualToString:@"home"]) {
9204 controller = [[[HomeController alloc] init] autorelease];
9207 if ([base isEqualToString:@"sections"]) {
9208 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9211 if ([base isEqualToString:@"search"]) {
9212 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9215 if ([base isEqualToString:@"changes"]) {
9216 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9219 if ([base isEqualToString:@"installed"]) {
9220 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9222 } else if ([components count] == 2) {
9223 NSString *argument = [components objectAtIndex:1];
9225 if ([base isEqualToString:@"package"]) {
9226 controller = [self pageForPackage:argument];
9229 if (!external && [base isEqualToString:@"search"]) {
9230 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9233 if (!external && [base isEqualToString:@"sections"]) {
9234 if ([argument isEqualToString:@"all"])
9236 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9239 if (!external && [base isEqualToString:@"sources"]) {
9240 if ([argument isEqualToString:@"add"]) {
9241 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9242 [(SourcesController *)controller showAddSourcePrompt];
9244 Source *source = [database_ sourceWithKey:argument];
9245 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9249 if (!external && [base isEqualToString:@"launch"]) {
9250 [self launchApplicationWithIdentifier:argument suspended:NO];
9253 } else if (!external && [components count] == 3) {
9254 NSString *arg1 = [components objectAtIndex:1];
9255 NSString *arg2 = [components objectAtIndex:2];
9257 if ([base isEqualToString:@"package"]) {
9258 if ([arg2 isEqualToString:@"settings"]) {
9259 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9260 } else if ([arg2 isEqualToString:@"files"]) {
9261 if (Package *package = [database_ packageWithName:arg1]) {
9262 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9263 [(FileTable *)controller setPackage:package];
9269 [controller setDelegate:self];
9273 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9274 CyteViewController *page([self pageForURL:url forExternal:external]);
9277 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9278 [nav setViewControllers:[NSArray arrayWithObject:page]];
9279 [tabbar_ setUnselectedViewController:nav];
9285 - (void) applicationOpenURL:(NSURL *)url {
9286 [super applicationOpenURL:url];
9291 [self openCydiaURL:url forExternal:YES];
9294 - (void) applicationWillResignActive:(UIApplication *)application {
9295 // Stop refreshing if you get a phone call or lock the device.
9296 if ([tabbar_ updating])
9297 [tabbar_ cancelUpdate];
9299 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9300 [super applicationWillResignActive:application];
9303 - (void) applicationWillTerminate:(UIApplication *)application {
9305 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9306 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9307 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9312 - (void) setConfigurationData:(NSString *)data {
9313 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9315 if (!conffile_r(data)) {
9316 lprintf("E:invalid conffile\n");
9320 NSString *ofile = conffile_r[1];
9321 //NSString *nfile = conffile_r[2];
9323 UIAlertView *alert = [[[UIAlertView alloc]
9324 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9325 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9327 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9329 UCLocalize("ACCEPT_NEW_COPY"),
9330 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9334 [alert setContext:@"conffile"];
9335 [alert setNumberOfRows:2];
9339 - (void) addStashController {
9341 stash_ = [[[StashController alloc] init] autorelease];
9342 [window_ addSubview:[stash_ view]];
9345 - (void) removeStashController {
9346 [[stash_ view] removeFromSuperview];
9352 [self setIdleTimerDisabled:YES];
9354 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9355 UpdateExternalStatus(1);
9356 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9357 UpdateExternalStatus(0);
9359 [self removeStashController];
9361 if (ExecFork() == 0) {
9362 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9363 perror("launchctl stop");
9367 - (void) setupViewControllers {
9368 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9370 NSMutableArray *items([NSMutableArray arrayWithObjects:
9371 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9372 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9373 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9374 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9378 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9379 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9381 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9384 NSMutableArray *controllers([NSMutableArray array]);
9385 for (UITabBarItem *item in items) {
9386 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9387 [controller setTabBarItem:item];
9388 [controllers addObject:controller];
9390 [tabbar_ setViewControllers:controllers];
9392 [tabbar_ setUpdateDelegate:self];
9395 - (void) applicationDidFinishLaunching:(id)unused {
9397 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9398 [self setApplicationSupportsShakeToEdit:NO];
9400 @synchronized (HostConfig_) {
9401 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9404 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9405 initWithMemoryCapacity:524288
9406 diskCapacity:10485760
9407 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9410 [CydiaWebViewController _initialize];
9412 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9414 // this would disallow http{,s} URLs from accessing this data
9415 //[WebView registerURLSchemeAsLocal:@"cydia"];
9417 Font12_ = [UIFont systemFontOfSize:12];
9418 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9419 Font14_ = [UIFont systemFontOfSize:14];
9420 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9421 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9423 essential_ = [NSMutableArray arrayWithCapacity:4];
9424 broken_ = [NSMutableArray arrayWithCapacity:4];
9426 // XXX: I really need this thing... like, seriously... I'm sorry
9427 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9429 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9430 [window_ orderFront:self];
9431 [window_ makeKey:self];
9432 [window_ setHidden:NO];
9435 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9436 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9437 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9438 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9439 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9440 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9441 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9442 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9443 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9446 [self addStashController];
9447 // XXX: this would be much cleaner as a yieldToSelector:
9448 // that way the removeStashController could happen right here inline
9449 // we also could no longer require the useless stash_ field anymore
9450 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9454 database_ = [Database sharedInstance];
9455 [database_ setDelegate:self];
9457 [window_ setUserInteractionEnabled:NO];
9458 [self setupViewControllers];
9460 emulated_ = [[[CYEmulatedLoadingController alloc] initWithDatabase:database_] autorelease];
9461 [window_ addSubview:[emulated_ view]];
9463 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9467 - (NSArray *) defaultStartPages {
9468 NSMutableArray *standard = [NSMutableArray array];
9469 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9470 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9471 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9473 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9475 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9476 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9478 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9485 [window_ setUserInteractionEnabled:YES];
9486 [self showSettings];
9489 if ([emulated_ modalViewController] != nil)
9490 [emulated_ dismissModalViewControllerAnimated:YES];
9491 [window_ setUserInteractionEnabled:NO];
9499 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9500 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9501 int standardIndex = 0;
9502 NSArray *standard = [self defaultStartPages];
9509 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9510 if (valid && closed != nil) {
9511 NSTimeInterval interval([closed timeIntervalSinceNow]);
9512 // XXX: Is 15 minutes the optimal time here?
9513 if (interval > 0 && interval <= -(15*60))
9517 if (valid && [saved count] != [standard count])
9521 for (unsigned int i = 0; i < [standard count]; i++) {
9522 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9523 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9524 // but it's good enough for now.
9525 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9532 NSArray *items = nil;
9534 [tabbar_ setSelectedIndex:savedIndex];
9537 [tabbar_ setSelectedIndex:standardIndex];
9541 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9542 NSArray *stack = [items objectAtIndex:tab];
9543 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9544 NSMutableArray *current = [NSMutableArray array];
9546 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9547 NSString *addr = [stack objectAtIndex:nav];
9548 NSURL *url = [NSURL URLWithString:addr];
9549 CyteViewController *page = [self pageForURL:url forExternal:NO];
9551 [current addObject:page];
9554 [navigation setViewControllers:current];
9557 // (Try to) show the startup URL.
9558 if (starturl_ != nil) {
9559 [self openCydiaURL:starturl_ forExternal:NO];
9564 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9565 if (item != nil && IsWildcat_) {
9566 [sheet showFromBarButtonItem:item animated:YES];
9568 [sheet showInView:window_];
9572 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9573 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9574 [progress setTitle:task];
9575 [progress addProgressEvent:event];
9578 - (void) addProgressEventForTask:(NSArray *)data {
9579 CydiaProgressEvent *event([data objectAtIndex:0]);
9580 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9581 [self addProgressEvent:event forTask:task];
9584 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9585 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9591 id Alloc_(id self, SEL selector) {
9592 id object = alloc_(self, selector);
9593 lprintf("[%s]A-%p\n", self->isa->name, object);
9598 id Dealloc_(id self, SEL selector) {
9599 id object = dealloc_(self, selector);
9600 lprintf("[%s]D-%p\n", self->isa->name, object);
9604 Class $WebDefaultUIKitDelegate;
9606 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9607 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9608 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9609 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9612 static NSSet *MobilizedFiles_;
9614 static NSURL *MobilizeURL(NSURL *url) {
9615 NSString *path([url path]);
9616 if ([path hasPrefix:@"/var/root/"]) {
9617 NSString *file([path substringFromIndex:10]);
9618 if ([MobilizedFiles_ containsObject:file])
9619 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9625 Class $CFXPreferencesPropertyListSource;
9626 @class CFXPreferencesPropertyListSource;
9628 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9629 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9630 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9631 url = MobilizeURL(url);
9632 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9633 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9639 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9640 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9641 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9642 url = MobilizeURL(url);
9643 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9644 //NSLog(@"%@ %@", [url absoluteString], value);
9650 Class $NSURLConnection;
9652 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9653 NSMutableURLRequest *copy([request mutableCopy]);
9655 NSURL *url([copy URL]);
9656 NSString *host([url host]);
9657 NSString *scheme([[url scheme] lowercaseString]);
9659 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9661 @synchronized (HostConfig_) {
9662 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9663 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9664 [copy setHTTPShouldUsePipelining:YES];
9667 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9671 int main(int argc, char *argv[]) { _pooled
9674 UpdateExternalStatus(0);
9676 if (Class $UIDevice = objc_getClass("UIDevice")) {
9677 UIDevice *device([$UIDevice currentDevice]);
9678 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9682 UIScreen *screen([UIScreen mainScreen]);
9683 if ([screen respondsToSelector:@selector(scale)])
9684 ScreenScale_ = [screen scale];
9688 UIDevice *device([UIDevice currentDevice]);
9689 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9692 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9693 if (idiom == UIUserInterfaceIdiomPhone)
9695 else if (idiom == UIUserInterfaceIdiomPad)
9698 NSLog(@"unknown UIUserInterfaceIdiom!");
9701 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9703 HostConfig_ = [[[NSObject alloc] init] autorelease];
9704 @synchronized (HostConfig_) {
9705 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9706 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9709 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9711 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9713 MobilizedFiles_ = [NSMutableSet setWithObjects:
9714 @"Library/Preferences/com.apple.Accessibility.plist",
9715 @"Library/Preferences/com.apple.preferences.sounds.plist",
9718 /* Library Hacks {{{ */
9719 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9721 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9723 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9724 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9725 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9726 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9729 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9730 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9731 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9732 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9735 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9736 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9737 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9738 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9739 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9742 $NSURLConnection = objc_getClass("NSURLConnection");
9743 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9744 if (NSURLConnection$init$ != NULL) {
9745 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9746 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9749 /* Set Locale {{{ */
9750 Locale_ = CFLocaleCopyCurrent();
9751 Languages_ = [NSLocale preferredLanguages];
9753 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9754 //NSLog(@"%@", [Languages_ description]);
9757 if (Locale_ != NULL)
9758 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9759 else if (Languages_ != nil && [Languages_ count] != 0)
9760 lang = [[Languages_ objectAtIndex:0] UTF8String];
9762 // XXX: consider just setting to C and then falling through?
9766 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9767 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9770 NSLog(@"Setting Language: %s", lang);
9773 setenv("LANG", lang, true);
9774 std::setlocale(LC_ALL, lang);
9778 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9780 /* Parse Arguments {{{ */
9781 bool substrate(false);
9787 for (int argi(1); argi != argc; ++argi)
9788 if (strcmp(argv[argi], "--") == 0) {
9790 argv[argi] = argv[0];
9796 for (int argi(1); argi != arge; ++argi)
9797 if (strcmp(args[argi], "--substrate") == 0)
9800 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9804 App_ = [[NSBundle mainBundle] bundlePath];
9810 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9811 alloc_ = alloc->method_imp;
9812 alloc->method_imp = (IMP) &Alloc_;*/
9814 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9815 dealloc_ = dealloc->method_imp;
9816 dealloc->method_imp = (IMP) &Dealloc_;*/
9818 /* System Information {{{ */
9822 size = sizeof(maxproc);
9823 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9824 perror("sysctlbyname(\"kern.maxproc\", ?)");
9825 else if (maxproc < 64) {
9827 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9828 perror("sysctlbyname(\"kern.maxproc\", #)");
9831 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9832 char *osversion = new char[size];
9833 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9834 perror("sysctlbyname(\"kern.osversion\", ?)");
9836 System_ = [NSString stringWithUTF8String:osversion];
9838 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9839 char *machine = new char[size];
9840 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9841 perror("sysctlbyname(\"hw.machine\", ?)");
9845 SerialNumber_ = CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9846 ChipID_ = CYHex(CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true, true);
9847 BBSNum_ = CYHex(CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false, false);
9849 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9851 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9852 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9853 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9855 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9856 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9857 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9859 if (mcc != NULL && mnc != NULL)
9860 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9867 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9868 Build_ = [system objectForKey:@"ProductBuildVersion"];
9869 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9870 Product_ = [info objectForKey:@"SafariProductVersion"];
9871 Safari_ = [info objectForKey:@"CFBundleVersion"];
9874 /* Load Database {{{ */
9876 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9878 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9880 if (Metadata_ == NULL)
9881 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9883 Settings_ = [Metadata_ objectForKey:@"Settings"];
9885 Packages_ = [Metadata_ objectForKey:@"Packages"];
9886 Sections_ = [Metadata_ objectForKey:@"Sections"];
9887 Sources_ = [Metadata_ objectForKey:@"Sources"];
9889 Token_ = [Metadata_ objectForKey:@"Token"];
9892 if (Settings_ != nil)
9893 Role_ = [Settings_ objectForKey:@"Role"];
9895 if (Sections_ == nil) {
9896 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9897 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9900 if (Sources_ == nil) {
9901 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9902 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9907 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9910 if (Packages_ != nil) {
9912 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9916 [Metadata_ removeObjectForKey:@"Packages"];
9922 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9924 #define MobileSubstrate_(name) \
9925 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9926 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9927 if (handle == NULL) \
9928 NSLog(@"%s", dlerror()); \
9931 MobileSubstrate_(Activator)
9932 MobileSubstrate_(libstatusbar)
9933 MobileSubstrate_(SimulatedKeyEvents)
9934 MobileSubstrate_(WinterBoard)
9936 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9937 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9939 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9941 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9942 unlink("/tmp/.cydia.fw");
9944 } else if (access("/User", F_OK) != 0 || version < 4) {
9947 system("/usr/libexec/cydia/firmware.sh");
9951 _assert([[NSFileManager defaultManager]
9952 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9953 withIntermediateDirectories:YES
9958 if (access("/tmp/cydia.chk", F_OK) == 0) {
9959 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9960 _assert(errno == ENOENT);
9961 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9962 _assert(errno == ENOENT);
9965 /* APT Initialization {{{ */
9966 _assert(pkgInitConfig(*_config));
9967 _assert(pkgInitSystem(*_config, _system));
9970 _config->Set("APT::Acquire::Translation", lang);
9972 // XXX: this timeout might be important :(
9973 //_config->Set("Acquire::http::Timeout", 15);
9975 _config->Set("Acquire::http::MaxParallel", 3);
9977 /* Color Choices {{{ */
9978 space_ = CGColorSpaceCreateDeviceRGB();
9980 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9981 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9982 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9983 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9984 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9985 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9986 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9987 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9988 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9990 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9991 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9993 /* UIKit Configuration {{{ */
9994 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9995 if ($GSFontSetUseLegacyFontMetrics != NULL)
9996 $GSFontSetUseLegacyFontMetrics(YES);
9998 // XXX: I have a feeling this was important
9999 //UIKeyboardDisableAutomaticAppearance();
10002 Colon_ = UCLocalize("COLON_DELIMITED");
10003 Elision_ = UCLocalize("ELISION");
10004 Error_ = UCLocalize("ERROR");
10005 Warning_ = UCLocalize("WARNING");
10008 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10010 CGColorSpaceRelease(space_);
10011 CFRelease(Locale_);