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 NSObject *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 = false) {
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, "%.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];
3718 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3722 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
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(getIORegistryEntry::))
3959 return @"getIORegistryEntry";
3960 else if (selector == @selector(getLocaleIdentifier))
3961 return @"getLocaleIdentifier";
3962 else if (selector == @selector(getPreferredLanguages))
3963 return @"getPreferredLanguages";
3964 else if (selector == @selector(getPackageById:))
3965 return @"getPackageById";
3966 else if (selector == @selector(getSessionValue:))
3967 return @"getSessionValue";
3968 else if (selector == @selector(installPackages:))
3969 return @"installPackages";
3970 else if (selector == @selector(localizedStringForKey:value:table:))
3972 else if (selector == @selector(popViewController:))
3973 return @"popViewController";
3974 else if (selector == @selector(refreshSources))
3975 return @"refreshSources";
3976 else if (selector == @selector(removeButton))
3977 return @"removeButton";
3978 else if (selector == @selector(setSessionValue::))
3979 return @"setSessionValue";
3980 else if (selector == @selector(substitutePackageNames:))
3981 return @"substitutePackageNames";
3982 else if (selector == @selector(scrollToBottom:))
3983 return @"scrollToBottom";
3984 else if (selector == @selector(setAllowsNavigationAction:))
3985 return @"setAllowsNavigationAction";
3986 else if (selector == @selector(setBadgeValue:))
3987 return @"setBadgeValue";
3988 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3989 return @"setButtonImage";
3990 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3991 return @"setButtonTitle";
3992 else if (selector == @selector(setHidesBackButton:))
3993 return @"setHidesBackButton";
3994 else if (selector == @selector(setHidesNavigationBar:))
3995 return @"setHidesNavigationBar";
3996 else if (selector == @selector(setNavigationBarStyle:))
3997 return @"setNavigationBarStyle";
3998 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
3999 return @"setNavigationBarTintColor";
4000 else if (selector == @selector(setPasteboardString:))
4001 return @"setPasteboardString";
4002 else if (selector == @selector(setPasteboardURL:))
4003 return @"setPasteboardURL";
4004 else if (selector == @selector(setToken:))
4006 else if (selector == @selector(setViewportWidth:))
4007 return @"setViewportWidth";
4008 else if (selector == @selector(statfs:))
4010 else if (selector == @selector(supports:))
4016 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4017 return [self webScriptNameForSelector:selector] == nil;
4020 - (BOOL) supports:(NSString *)feature {
4021 return [feature isEqualToString:@"window.open"];
4024 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4025 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4028 - (NSNumber *) getKernelNumber:(NSString *)name {
4029 const char *string([name UTF8String]);
4032 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4033 return (id) [NSNull null];
4035 if (size != sizeof(int))
4036 return (id) [NSNull null];
4039 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4040 return (id) [NSNull null];
4042 return [NSNumber numberWithInt:value];
4045 - (NSString *) getKernelString:(NSString *)name {
4046 const char *string([name UTF8String]);
4049 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4050 return (id) [NSNull null];
4052 char value[size + 1];
4053 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4054 return (id) [NSNull null];
4056 // XXX: just in case you request something ludicrous
4059 return [NSString stringWithCString:value];
4062 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4063 NSObject *value(CYIOGetValue([path UTF8String], entry));
4066 if ([value isKindOfClass:[NSData class]])
4067 value = CYHex((NSData *) value);
4072 - (id) getSessionValue:(NSString *)key {
4073 @synchronized (SessionData_) {
4074 return [SessionData_ objectForKey:key];
4077 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4078 @synchronized (SessionData_) {
4079 if (value == (id) [WebUndefined undefined])
4080 [SessionData_ removeObjectForKey:key];
4082 [SessionData_ setObject:value forKey:key];
4085 - (void) addBridgedHost:(NSString *)host {
4086 @synchronized (HostConfig_) {
4087 [BridgedHosts_ addObject:host];
4090 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4091 @synchronized (HostConfig_) {
4092 if (scheme != (id) [WebUndefined undefined])
4093 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4095 [PipelinedHosts_ addObject:host];
4098 - (void) popViewController:(NSNumber *)value {
4099 if (value == (id) [WebUndefined undefined])
4100 value = [NSNumber numberWithBool:YES];
4101 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4104 - (void) addTrivialSource:(NSString *)href {
4105 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4108 - (void) refreshSources {
4109 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4112 - (NSArray *) getAllSources {
4113 return [[Database sharedInstance] sources];
4116 - (NSArray *) getInstalledPackages {
4117 Database *database([Database sharedInstance]);
4118 @synchronized (database) {
4119 NSArray *packages([database packages]);
4120 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4121 for (Package *package in packages)
4122 if (![package uninstalled])
4123 [installed addObject:package];
4127 - (Package *) getPackageById:(NSString *)id {
4128 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4132 return (Package *) [NSNull null];
4135 - (NSString *) getLocaleIdentifier {
4136 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4139 - (NSArray *) getPreferredLanguages {
4143 - (NSArray *) statfs:(NSString *)path {
4146 if (path == nil || statfs([path UTF8String], &stat) == -1)
4149 return [NSArray arrayWithObjects:
4150 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4151 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4152 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4156 - (NSNumber *) du:(NSString *)path {
4157 NSNumber *value(nil);
4160 _assert(pipe(fds) != -1);
4162 pid_t pid(ExecFork());
4164 _assert(dup2(fds[1], 1) != -1);
4165 _assert(close(fds[0]) != -1);
4166 _assert(close(fds[1]) != -1);
4167 /* XXX: this should probably not use du */
4168 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4173 _assert(close(fds[1]) != -1);
4175 if (FILE *du = fdopen(fds[0], "r")) {
4177 while (fgets(line, sizeof(line), du) != NULL) {
4178 size_t length(strlen(line));
4179 while (length != 0 && line[length - 1] == '\n')
4180 line[--length] = '\0';
4181 if (char *tab = strchr(line, '\t')) {
4183 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4188 } else _assert(close(fds[0]));
4192 if (waitpid(pid, &status, 0) == -1)
4195 else _assert(false);
4201 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4204 - (void) installPackages:(NSArray *)packages {
4205 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4208 - (NSString *) substitutePackageNames:(NSString *)message {
4209 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4210 for (size_t i(0), e([words count]); i != e; ++i) {
4211 NSString *word([words objectAtIndex:i]);
4212 if (Package *package = [[Database sharedInstance] packageWithName:word])
4213 [words replaceObjectAtIndex:i withObject:[package name]];
4216 return [words componentsJoinedByString:@" "];
4219 - (void) removeButton {
4220 [indirect_ removeButton];
4223 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4224 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4227 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4228 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4231 - (void) setBadgeValue:(id)value {
4232 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4235 - (void) setAllowsNavigationAction:(NSString *)value {
4236 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4239 - (void) setHidesBackButton:(NSString *)value {
4240 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4243 - (void) setHidesNavigationBar:(NSString *)value {
4244 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4247 - (void) setNavigationBarStyle:(NSString *)value {
4248 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4251 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4252 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4253 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4254 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4257 - (void) setPasteboardString:(NSString *)value {
4258 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4261 - (void) setPasteboardURL:(NSString *)value {
4262 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4265 - (void) _setToken:(NSString *)token {
4269 [Metadata_ removeObjectForKey:@"Token"];
4271 [Metadata_ setObject:Token_ forKey:@"Token"];
4276 - (void) setToken:(NSString *)token {
4277 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4280 - (void) scrollToBottom:(NSNumber *)animated {
4281 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4284 - (void) setViewportWidth:(float)width {
4285 [indirect_ setViewportWidthOnMainThread:width];
4288 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4289 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4290 unsigned count([arguments count]);
4292 for (unsigned i(0); i != count; ++i)
4293 values[i] = [arguments objectAtIndex:i];
4294 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4297 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4298 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4300 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4302 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4308 /* @ Loading... Indicator {{{ */
4309 @interface CYLoadingIndicator : UIView {
4310 _H<UIActivityIndicatorView> spinner_;
4312 _H<UIView> container_;
4315 @property (readonly, nonatomic) UILabel *label;
4316 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4320 @implementation CYLoadingIndicator
4322 - (id) initWithFrame:(CGRect)frame {
4323 if ((self = [super initWithFrame:frame]) != nil) {
4324 container_ = [[[UIView alloc] init] autorelease];
4325 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4327 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4328 [spinner_ startAnimating];
4329 [container_ addSubview:spinner_];
4331 label_ = [[[UILabel alloc] init] autorelease];
4332 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4333 [label_ setBackgroundColor:[UIColor clearColor]];
4334 [label_ setTextColor:[UIColor blackColor]];
4335 [label_ setShadowColor:[UIColor whiteColor]];
4336 [label_ setShadowOffset:CGSizeMake(0, 1)];
4337 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4338 [container_ addSubview:label_];
4340 CGSize viewsize = frame.size;
4341 CGSize spinnersize = [spinner_ bounds].size;
4342 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4343 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4345 CGRect containrect = {
4346 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4347 CGSizeMake(bothwidth, spinnersize.height)
4350 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4358 [container_ setFrame:containrect];
4359 [spinner_ setFrame:spinrect];
4360 [label_ setFrame:textrect];
4361 [self addSubview:container_];
4365 - (UILabel *) label {
4369 - (UIActivityIndicatorView *) activityIndicatorView {
4375 /* Emulated Loading Controller {{{ */
4376 @interface CYEmulatedLoadingController : CyteViewController {
4377 _transient Database *database_;
4378 _H<CYLoadingIndicator> indicator_;
4379 _H<UITabBar> tabbar_;
4380 _H<UINavigationBar> navbar_;
4385 @implementation CYEmulatedLoadingController
4387 - (id) initWithDatabase:(Database *)database {
4388 if ((self = [super init]) != nil) {
4389 database_ = database;
4394 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4396 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4397 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4398 [[self view] addSubview:table];
4400 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4401 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4402 [[self view] addSubview:indicator_];
4404 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4405 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4406 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4407 [[self view] addSubview:tabbar_];
4409 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4410 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4411 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4412 [[self view] addSubview:navbar_];
4415 - (void) releaseSubviews {
4424 /* Cydia Browser Controller {{{ */
4425 @implementation CydiaWebViewController
4427 - (NSURL *) navigationURL {
4428 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4431 + (void) initialize {
4432 Diversions_ = [NSMutableSet setWithCapacity:0];
4435 + (void) addDiversion:(Diversion *)diversion {
4436 [Diversions_ addObject:diversion];
4439 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4440 [super webView:view didClearWindowObject:window forFrame:frame];
4442 WebDataSource *source([frame dataSource]);
4443 NSURLResponse *response([source response]);
4444 NSURL *url([response URL]);
4445 NSString *scheme([[url scheme] lowercaseString]);
4447 bool bridged(false);
4449 @synchronized (HostConfig_) {
4450 if ([scheme isEqualToString:@"file"])
4452 else if ([scheme isEqualToString:@"https"])
4453 if ([BridgedHosts_ containsObject:[url host]])
4458 [window setValue:cydia_ forKey:@"cydia"];
4461 - (NSURL *) URLWithURL:(NSURL *)url {
4462 return [Diversion divertURL:url];
4465 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4466 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4468 if (System_ != NULL)
4469 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4470 if (Machine_ != NULL)
4471 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4473 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4478 - (void) setDelegate:(id)delegate {
4479 [super setDelegate:delegate];
4480 [cydia_ setDelegate:delegate];
4484 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4485 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4487 WebView *webview([[webview_ _documentView] webView]);
4489 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4492 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4494 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4495 if (Product_ != nil)
4496 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4498 [webview setApplicationNameForUserAgent:application];
4506 @interface NSObject (CydiaScript)
4507 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4510 @implementation NSObject (CydiaScript)
4512 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4518 @implementation NSArray (CydiaScript)
4520 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4521 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4522 for (size_t i(0), e([self count]); i != e; ++i)
4523 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4529 @implementation NSDictionary (CydiaScript)
4531 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4532 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4534 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4541 /* Confirmation Controller {{{ */
4542 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4543 if (!iterator.end())
4544 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4545 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4547 pkgCache::PkgIterator package(dep.TargetPkg());
4550 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4557 @protocol ConfirmationControllerDelegate
4558 - (void) cancelAndClear:(bool)clear;
4559 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4563 @interface ConfirmationController : CydiaWebViewController {
4564 _transient Database *database_;
4566 _H<UIAlertView> essential_;
4568 _H<NSDictionary> changes_;
4569 _H<NSMutableArray> issues_;
4570 _H<NSDictionary> sizes_;
4575 - (id) initWithDatabase:(Database *)database;
4579 @implementation ConfirmationController
4583 RestartSubstrate_ = true;
4584 [delegate_ confirmWithNavigationController:[self navigationController]];
4587 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4588 NSString *context([alert context]);
4590 if ([context isEqualToString:@"remove"]) {
4591 if (button == [alert cancelButtonIndex])
4592 [self dismissModalViewControllerAnimated:YES];
4593 else if (button == [alert firstOtherButtonIndex]) {
4597 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4598 } else if ([context isEqualToString:@"unable"]) {
4599 [self dismissModalViewControllerAnimated:YES];
4600 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4602 [super alertView:alert clickedButtonAtIndex:button];
4606 - (void) _doContinue {
4607 [self dismissModalViewControllerAnimated:YES];
4608 [delegate_ cancelAndClear:NO];
4611 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4612 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4616 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4617 [super webView:view didClearWindowObject:window forFrame:frame];
4619 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4620 (id) changes_, @"changes",
4621 (id) issues_, @"issues",
4622 (id) sizes_, @"sizes",
4624 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4627 - (id) initWithDatabase:(Database *)database {
4628 if ((self = [super init]) != nil) {
4629 database_ = database;
4631 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4632 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4633 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4634 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4635 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4639 pkgCacheFile &cache([database_ cache]);
4640 NSArray *packages([database_ packages]);
4641 pkgDepCache::Policy *policy([database_ policy]);
4643 issues_ = [NSMutableArray arrayWithCapacity:4];
4645 for (Package *package in packages) {
4646 pkgCache::PkgIterator iterator([package iterator]);
4647 NSString *name([package id]);
4649 if ([package broken]) {
4650 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4652 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4654 reasons, @"reasons",
4657 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4661 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4662 pkgCache::DepIterator start;
4663 pkgCache::DepIterator end;
4664 dep.GlobOr(start, end); // ++dep
4666 if (!cache->IsImportantDep(end))
4668 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4671 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4673 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4674 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4675 clauses, @"clauses",
4679 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4681 pkgCache::PkgIterator target(start.TargetPkg());
4682 if (target->ProvidesList != 0)
4683 reason = @"missing";
4685 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4687 reason = @"installed";
4688 installed = [NSString stringWithUTF8String:ver.VerStr()];
4689 } else if (!cache[target].CandidateVerIter(cache).end())
4690 reason = @"uninstalled";
4691 else if (target->ProvidesList == 0)
4692 reason = @"uninstallable";
4694 reason = @"virtual";
4697 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4698 [NSString stringWithUTF8String:start.CompType()], @"operator",
4699 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4702 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4703 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4704 version, @"version",
4706 installed, @"installed",
4709 // yes, seriously. (wtf?)
4717 pkgDepCache::StateCache &state(cache[iterator]);
4719 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4721 if (state.NewInstall())
4722 [installs addObject:name];
4723 // XXX: else if (state.Install())
4724 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4725 [reinstalls addObject:name];
4726 // XXX: move before previous if
4727 else if (state.Upgrade())
4728 [upgrades addObject:name];
4729 else if (state.Downgrade())
4730 [downgrades addObject:name];
4731 else if (!state.Delete())
4732 // XXX: _assert(state.Keep());
4734 else if (special_r(name))
4735 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4736 [NSNull null], @"package",
4737 [NSArray arrayWithObjects:
4738 [NSDictionary dictionaryWithObjectsAndKeys:
4739 @"Conflicts", @"relationship",
4740 [NSArray arrayWithObjects:
4741 [NSDictionary dictionaryWithObjectsAndKeys:
4743 [NSNull null], @"version",
4744 @"installed", @"reason",
4751 if ([package essential])
4753 [removes addObject:name];
4756 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4757 substrate_ |= DepSubstrate(iterator.CurrentVer());
4762 else if (Advanced_) {
4763 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4765 essential_ = [[[UIAlertView alloc]
4766 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4767 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4769 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4771 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4775 [essential_ setContext:@"remove"];
4777 essential_ = [[[UIAlertView alloc]
4778 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4779 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4781 cancelButtonTitle:UCLocalize("OKAY")
4782 otherButtonTitles:nil
4785 [essential_ setContext:@"unable"];
4788 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4789 installs, @"installs",
4790 reinstalls, @"reinstalls",
4791 upgrades, @"upgrades",
4792 downgrades, @"downgrades",
4793 removes, @"removes",
4796 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4797 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4798 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4801 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4805 - (UIBarButtonItem *) leftButton {
4806 return [[[UIBarButtonItem alloc]
4807 initWithTitle:UCLocalize("CANCEL")
4808 style:UIBarButtonItemStylePlain
4810 action:@selector(cancelButtonClicked)
4815 - (void) applyRightButton {
4816 if ([issues_ count] == 0 && ![self isLoading])
4817 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4818 initWithTitle:UCLocalize("CONFIRM")
4819 style:UIBarButtonItemStyleDone
4821 action:@selector(confirmButtonClicked)
4824 [[self navigationItem] setRightBarButtonItem:nil];
4828 - (void) cancelButtonClicked {
4829 [self dismissModalViewControllerAnimated:YES];
4830 [delegate_ cancelAndClear:YES];
4834 - (void) confirmButtonClicked {
4835 if (essential_ != nil)
4845 /* Progress Data {{{ */
4846 @interface CydiaProgressData : NSObject {
4847 _transient id delegate_;
4856 _H<NSMutableArray> events_;
4857 _H<NSString> title_;
4859 _H<NSString> status_;
4860 _H<NSString> finish_;
4865 @implementation CydiaProgressData
4867 + (NSArray *) _attributeKeys {
4868 return [NSArray arrayWithObjects:
4880 - (NSArray *) attributeKeys {
4881 return [[self class] _attributeKeys];
4884 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4885 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4889 if ((self = [super init]) != nil) {
4890 events_ = [NSMutableArray arrayWithCapacity:32];
4894 - (void) setDelegate:(id)delegate {
4895 delegate_ = delegate;
4898 - (void) setPercent:(float)value {
4902 - (NSNumber *) percent {
4903 return [NSNumber numberWithFloat:percent_];
4906 - (void) setCurrent:(float)value {
4910 - (NSNumber *) current {
4911 return [NSNumber numberWithFloat:current_];
4914 - (void) setTotal:(float)value {
4918 - (NSNumber *) total {
4919 return [NSNumber numberWithFloat:total_];
4922 - (void) setSpeed:(float)value {
4926 - (NSNumber *) speed {
4927 return [NSNumber numberWithFloat:speed_];
4930 - (NSArray *) events {
4934 - (void) removeAllEvents {
4935 [events_ removeAllObjects];
4938 - (void) addEvent:(CydiaProgressEvent *)event {
4939 [events_ addObject:event];
4942 - (void) setTitle:(NSString *)text {
4946 - (NSString *) title {
4950 - (void) setFinish:(NSString *)text {
4954 - (NSString *) finish {
4955 return (id) finish_ ?: [NSNull null];
4958 - (void) setRunning:(bool)running {
4962 - (NSNumber *) running {
4963 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4968 /* Progress Controller {{{ */
4969 @interface ProgressController : CydiaWebViewController <
4972 _transient Database *database_;
4973 _H<CydiaProgressData> progress_;
4977 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4979 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4981 - (void) setTitle:(NSString *)title;
4982 - (void) setCancellable:(bool)cancellable;
4986 @implementation ProgressController
4989 [database_ setProgressDelegate:nil];
4990 [progress_ setDelegate:nil];
4994 - (UIBarButtonItem *) leftButton {
4995 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
4996 initWithTitle:UCLocalize("CANCEL")
4997 style:UIBarButtonItemStylePlain
4999 action:@selector(cancel)
5000 ] autorelease] : nil;
5003 - (void) updateCancel {
5004 [super applyLeftButton];
5007 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5008 if ((self = [super init]) != nil) {
5009 database_ = database;
5010 delegate_ = delegate;
5012 [database_ setProgressDelegate:self];
5014 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5015 [progress_ setDelegate:self];
5017 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5019 [scroller_ setBackgroundColor:[UIColor blackColor]];
5021 [[self navigationItem] setHidesBackButton:YES];
5023 [self updateCancel];
5027 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5028 [super webView:view didClearWindowObject:window forFrame:frame];
5029 [window setValue:progress_ forKey:@"cydiaProgress"];
5032 - (void) updateProgress {
5033 [self dispatchEvent:@"CydiaProgressUpdate"];
5036 - (void) viewWillAppear:(BOOL)animated {
5037 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5038 [super viewWillAppear:animated];
5042 UpdateExternalStatus(0);
5049 [delegate_ terminateWithSuccess];
5050 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5051 [delegate_ suspendWithAnimation:YES];
5053 [delegate_ suspend];*/
5065 system("/usr/bin/sbreload");
5071 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5072 SBReboot(SBSSpringBoardServerPort());
5074 reboot2(RB_AUTOBOOT);
5081 - (void) setTitle:(NSString *)title {
5082 [progress_ setTitle:title];
5083 [self updateProgress];
5086 - (UIBarButtonItem *) rightButton {
5087 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5088 initWithTitle:UCLocalize("CLOSE")
5089 style:UIBarButtonItemStylePlain
5091 action:@selector(close)
5095 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5096 UpdateExternalStatus(1);
5098 [progress_ setRunning:true];
5099 [self setTitle:title];
5100 // implicit updateProgress
5102 SHA1SumValue notifyconf; {
5104 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5107 MMap mmap(file, MMap::ReadOnly);
5109 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5110 notifyconf = sha1.Result();
5114 SHA1SumValue springlist; {
5116 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5119 MMap mmap(file, MMap::ReadOnly);
5121 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5122 springlist = sha1.Result();
5126 if (invocation != nil) {
5127 [invocation yieldToSelector:@selector(invoke)];
5128 [self setTitle:@"COMPLETE"];
5133 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5136 MMap mmap(file, MMap::ReadOnly);
5138 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5139 if (!(notifyconf == sha1.Result()))
5146 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5149 MMap mmap(file, MMap::ReadOnly);
5151 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5152 if (!(springlist == sha1.Result()))
5158 if (RestartSubstrate_)
5162 RestartSubstrate_ = false;
5165 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5166 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5167 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5168 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5169 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5173 system("su -c /usr/bin/uicache mobile");
5176 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5178 [progress_ setRunning:false];
5179 [self updateProgress];
5181 [self applyRightButton];
5184 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5185 [progress_ addEvent:event];
5186 [self updateProgress];
5189 - (bool) isProgressCancelled {
5190 return cancel_ == 2;
5195 [self updateCancel];
5198 - (void) setCancellable:(bool)cancellable {
5199 unsigned cancel(cancel_);
5203 else if (cancel_ == 0)
5206 if (cancel != cancel_)
5207 [self updateCancel];
5210 - (void) setProgressCancellable:(NSNumber *)cancellable {
5211 [self setCancellable:[cancellable boolValue]];
5214 - (void) setProgressPercent:(NSNumber *)percent {
5215 [progress_ setPercent:[percent floatValue]];
5216 [self updateProgress];
5219 - (void) setProgressStatus:(NSDictionary *)status {
5220 if (status == nil) {
5221 [progress_ setCurrent:0];
5222 [progress_ setTotal:0];
5223 [progress_ setSpeed:0];
5225 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5227 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5228 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5229 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5232 [self updateProgress];
5238 /* Cell Content View {{{ */
5239 @protocol ContentDelegate
5240 - (void) drawContentRect:(CGRect)rect;
5243 @interface ContentView : UIView {
5244 _transient id<ContentDelegate> delegate_;
5249 @implementation ContentView
5251 - (id) initWithFrame:(CGRect)frame {
5252 if ((self = [super initWithFrame:frame]) != nil) {
5253 [self setNeedsDisplayOnBoundsChange:YES];
5257 - (void) setDelegate:(id<ContentDelegate>)delegate {
5258 delegate_ = delegate;
5261 - (void) drawRect:(CGRect)rect {
5262 [super drawRect:rect];
5263 [delegate_ drawContentRect:rect];
5268 /* Cydia TableView Cell {{{ */
5269 @interface CYTableViewCell : UITableViewCell {
5270 _H<ContentView> content_;
5276 @implementation CYTableViewCell
5278 - (void) _updateHighlightColorsForView:(UIView *)view highlighted:(BOOL)highlighted {
5279 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5281 if (view == (UIView *) content_) {
5282 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5283 highlighted_ = highlighted;
5286 [super _updateHighlightColorsForView:view highlighted:highlighted];
5289 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5290 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5291 highlighted_ = selected;
5293 [super setSelected:selected animated:animated];
5294 [content_ setNeedsDisplay];
5300 /* Package Cell {{{ */
5301 @interface PackageCell : CYTableViewCell <
5306 _H<NSString> description_;
5308 _H<NSString> source_;
5310 _H<Package> package_;
5311 _H<UIImage> placard_;
5314 - (PackageCell *) init;
5315 - (void) setPackage:(Package *)package;
5317 - (void) drawContentRect:(CGRect)rect;
5321 @implementation PackageCell
5323 - (PackageCell *) init {
5324 CGRect frame(CGRectMake(0, 0, 320, 74));
5325 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5326 UIView *content([self contentView]);
5327 CGRect bounds([content bounds]);
5329 content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
5330 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5331 [content addSubview:content_];
5333 [content_ setDelegate:self];
5334 [content_ setOpaque:YES];
5338 - (NSString *) accessibilityLabel {
5339 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5342 - (void) setPackage:(Package *)package {
5353 Source *source = [package source];
5355 icon_ = [package icon];
5356 name_ = [package name];
5359 description_ = [package longDescription];
5360 if (description_ == nil)
5361 description_ = [package shortDescription];
5363 commercial_ = [package isCommercial];
5367 NSString *label = nil;
5368 bool trusted = false;
5370 if (source != nil) {
5371 label = [source label];
5372 trusted = [source trusted];
5373 } else if ([[package id] isEqualToString:@"firmware"])
5374 label = UCLocalize("APPLE");
5376 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5378 NSString *from(label);
5380 NSString *section = [package simpleSection];
5381 if (section != nil && ![section isEqualToString:label]) {
5382 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5383 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5386 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5388 if (NSString *purpose = [package primaryPurpose])
5389 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5394 if (NSString *mode = [package_ mode]) {
5395 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5396 color = RemovingColor_;
5397 //placard = @"removing";
5399 color = InstallingColor_;
5400 //placard = @"installing";
5403 // XXX: the removing/installing placards are not @2x
5406 color = [UIColor whiteColor];
5408 if ([package installed] != nil)
5409 placard = @"installed";
5414 [content_ setBackgroundColor:color];
5417 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5419 [self setNeedsDisplay];
5420 [content_ setNeedsDisplay];
5423 - (void) drawContentRect:(CGRect)rect {
5424 bool highlighted(highlighted_);
5425 float width([self bounds].size.width);
5428 CGContextRef context(UIGraphicsGetCurrentContext());
5429 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5430 CGContextFillRect(context, rect);
5435 rect.size = [(UIImage *) icon_ size];
5437 rect.size.width /= 2;
5438 rect.size.height /= 2;
5440 rect.origin.x = 25 - rect.size.width / 2;
5441 rect.origin.y = 25 - rect.size.height / 2;
5443 [icon_ drawInRect:rect];
5446 if (badge_ != nil) {
5448 rect.size = [(UIImage *) badge_ size];
5450 rect.size.width /= 2;
5451 rect.size.height /= 2;
5453 rect.origin.x = 36 - rect.size.width / 2;
5454 rect.origin.y = 36 - rect.size.height / 2;
5456 [badge_ drawInRect:rect];
5463 UISetColor(commercial_ ? Purple_ : Black_);
5464 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5465 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5468 UISetColor(commercial_ ? Purplish_ : Gray_);
5469 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5471 if (placard_ != nil)
5472 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5477 /* Section Cell {{{ */
5478 @interface SectionCell : CYTableViewCell <
5481 _H<NSString> basic_;
5482 _H<NSString> section_;
5484 _H<NSString> count_;
5486 _H<UISwitch> switch_;
5490 - (void) setSection:(Section *)section editing:(BOOL)editing;
5494 @implementation SectionCell
5496 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5497 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5498 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5499 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5500 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5502 UIView *content([self contentView]);
5503 CGRect bounds([content bounds]);
5505 content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
5506 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5507 [content addSubview:content_];
5508 [content_ setBackgroundColor:[UIColor whiteColor]];
5510 [content_ setDelegate:self];
5514 - (void) onSwitch:(id)sender {
5515 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5516 if (metadata == nil) {
5517 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5518 [Sections_ setObject:metadata forKey:basic_];
5521 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5525 - (void) setSection:(Section *)section editing:(BOOL)editing {
5526 if (editing != editing_) {
5528 [switch_ removeFromSuperview];
5530 [self addSubview:switch_];
5539 if (section == nil) {
5540 name_ = UCLocalize("ALL_PACKAGES");
5543 basic_ = [section name];
5544 section_ = [section localized];
5546 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5547 count_ = [NSString stringWithFormat:@"%d", [section count]];
5550 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5553 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5554 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5556 [content_ setNeedsDisplay];
5559 - (void) setFrame:(CGRect)frame {
5560 [super setFrame:frame];
5562 CGRect rect([switch_ frame]);
5563 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5566 - (NSString *) accessibilityLabel {
5570 - (void) drawContentRect:(CGRect)rect {
5571 bool highlighted(highlighted_ && !editing_);
5573 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5578 float width(rect.size.width);
5584 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5586 CGSize size = [count_ sizeWithFont:Font14_];
5590 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5596 /* File Table {{{ */
5597 @interface FileTable : CyteViewController <
5598 UITableViewDataSource,
5601 _transient Database *database_;
5602 _H<Package> package_;
5604 _H<NSMutableArray> files_;
5605 _H<UITableView> list_;
5608 - (id) initWithDatabase:(Database *)database;
5609 - (void) setPackage:(Package *)package;
5613 @implementation FileTable
5616 [(UITableView *) list_ setDataSource:nil];
5617 [list_ setDelegate:nil];
5621 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5622 return files_ == nil ? 0 : [files_ count];
5625 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5629 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5630 static NSString *reuseIdentifier = @"Cell";
5632 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5634 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5635 [cell setFont:[UIFont systemFontOfSize:16]];
5637 [cell setText:[files_ objectAtIndex:indexPath.row]];
5638 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5643 - (NSURL *) navigationURL {
5644 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5648 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5650 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5651 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5652 [list_ setRowHeight:24.0f];
5653 [(UITableView *) list_ setDataSource:self];
5654 [list_ setDelegate:self];
5655 [[self view] addSubview:list_];
5658 - (void) viewDidLoad {
5659 [super viewDidLoad];
5661 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5664 - (void) releaseSubviews {
5668 - (id) initWithDatabase:(Database *)database {
5669 if ((self = [super init]) != nil) {
5670 database_ = database;
5672 files_ = [NSMutableArray arrayWithCapacity:32];
5676 - (void) setPackage:(Package *)package {
5680 [files_ removeAllObjects];
5682 if (package != nil) {
5684 name_ = [package id];
5686 if (NSArray *files = [package files])
5687 [files_ addObjectsFromArray:files];
5689 if ([files_ count] != 0) {
5690 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5691 [files_ removeObjectAtIndex:0];
5692 [files_ sortUsingSelector:@selector(compareByPath:)];
5694 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5695 [stack addObject:@"/"];
5697 for (int i(0), e([files_ count]); i != e; ++i) {
5698 NSString *file = [files_ objectAtIndex:i];
5699 while (![file hasPrefix:[stack lastObject]])
5700 [stack removeLastObject];
5701 NSString *directory = [stack lastObject];
5702 [stack addObject:[file stringByAppendingString:@"/"]];
5703 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5704 ([stack count] - 2) * 3, "",
5705 [file substringFromIndex:[directory length]]
5714 - (void) reloadData {
5717 [self setPackage:[database_ packageWithName:name_]];
5722 /* Package Controller {{{ */
5723 @interface CYPackageController : CydiaWebViewController <
5724 UIActionSheetDelegate
5726 _transient Database *database_;
5727 _H<Package> package_;
5730 _H<NSMutableArray> buttons_;
5731 _H<UIBarButtonItem> button_;
5734 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5738 @implementation CYPackageController
5740 - (NSURL *) navigationURL {
5741 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5744 /* XXX: this is not safe at all... localization of /fail/ */
5745 - (void) _clickButtonWithName:(NSString *)name {
5746 if ([name isEqualToString:UCLocalize("CLEAR")])
5747 [delegate_ clearPackage:package_];
5748 else if ([name isEqualToString:UCLocalize("INSTALL")])
5749 [delegate_ installPackage:package_];
5750 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5751 [delegate_ installPackage:package_];
5752 else if ([name isEqualToString:UCLocalize("REMOVE")])
5753 [delegate_ removePackage:package_];
5754 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5755 [delegate_ installPackage:package_];
5756 else _assert(false);
5759 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5760 NSString *context([sheet context]);
5762 if ([context isEqualToString:@"modify"]) {
5763 if (button != [sheet cancelButtonIndex]) {
5764 NSString *buttonName = [buttons_ objectAtIndex:button];
5765 [self _clickButtonWithName:buttonName];
5768 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5772 - (bool) _allowJavaScriptPanel {
5777 - (void) _customButtonClicked {
5778 int count([buttons_ count]);
5783 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5785 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5786 [buttons addObjectsFromArray:buttons_];
5788 UIActionSheet *sheet = [[[UIActionSheet alloc]
5791 cancelButtonTitle:nil
5792 destructiveButtonTitle:nil
5793 otherButtonTitles:nil
5796 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5798 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5799 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5801 [sheet setContext:@"modify"];
5803 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5807 // We don't want to allow non-commercial packages to do custom things to the install button,
5808 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5809 - (void) customButtonClicked {
5811 [super customButtonClicked];
5813 [self _customButtonClicked];
5816 - (void) reloadButtonClicked {
5817 // Don't reload a commerical package by tapping the loading button,
5818 // but if it's not an Install button, we should forward it on.
5819 if (![package_ uninstalled])
5820 [self _customButtonClicked];
5823 - (void) applyLoadingTitle {
5824 // Don't show "Loading" as the title. Ever.
5827 - (UIBarButtonItem *) rightButton {
5832 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5833 if ((self = [super init]) != nil) {
5834 database_ = database;
5835 buttons_ = [NSMutableArray arrayWithCapacity:4];
5836 name_ = [NSString stringWithString:name];
5837 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5841 - (void) reloadData {
5844 package_ = [database_ packageWithName:name_];
5846 [buttons_ removeAllObjects];
5848 if (package_ != nil) {
5849 [(Package *) package_ parse];
5851 commercial_ = [package_ isCommercial];
5853 if ([package_ mode] != nil)
5854 [buttons_ addObject:UCLocalize("CLEAR")];
5855 if ([package_ source] == nil);
5856 else if ([package_ upgradableAndEssential:NO])
5857 [buttons_ addObject:UCLocalize("UPGRADE")];
5858 else if ([package_ uninstalled])
5859 [buttons_ addObject:UCLocalize("INSTALL")];
5861 [buttons_ addObject:UCLocalize("REINSTALL")];
5862 if (![package_ uninstalled])
5863 [buttons_ addObject:UCLocalize("REMOVE")];
5867 switch ([buttons_ count]) {
5868 case 0: title = nil; break;
5869 case 1: title = [buttons_ objectAtIndex:0]; break;
5870 default: title = UCLocalize("MODIFY"); break;
5873 button_ = [[[UIBarButtonItem alloc]
5875 style:UIBarButtonItemStylePlain
5877 action:@selector(customButtonClicked)
5881 - (bool) isLoading {
5882 return commercial_ ? [super isLoading] : false;
5888 /* Package List Controller {{{ */
5889 @interface PackageListController : CyteViewController <
5890 UITableViewDataSource,
5893 _transient Database *database_;
5895 _H<NSMutableArray> packages_;
5896 _H<NSMutableArray> sections_;
5897 _H<UITableView> list_;
5898 _H<NSMutableArray> index_;
5899 _H<NSMutableDictionary> indices_;
5900 _H<NSString> title_;
5903 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5904 - (void) setDelegate:(id)delegate;
5905 - (void) resetCursor;
5909 @implementation PackageListController
5912 [list_ setDataSource:nil];
5913 [list_ setDelegate:nil];
5917 - (void) deselectWithAnimation:(BOOL)animated {
5918 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5921 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5922 CGRect base = [[self view] bounds];
5923 base.size.height -= bounds.size.height;
5924 base.origin = [list_ frame].origin;
5926 [UIView beginAnimations:nil context:NULL];
5927 [UIView setAnimationBeginsFromCurrentState:YES];
5928 [UIView setAnimationCurve:curve];
5929 [UIView setAnimationDuration:duration];
5930 [list_ setFrame:base];
5931 [UIView commitAnimations];
5934 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5935 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5938 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5939 [self resizeForKeyboardBounds:bounds duration:0];
5942 - (void) keyboardWillShow:(NSNotification *)notification {
5945 NSTimeInterval duration;
5946 UIViewAnimationCurve curve;
5947 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5948 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5949 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5950 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5952 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);
5953 UIViewController *base = self;
5954 while ([base parentViewController] != nil)
5955 base = [base parentViewController];
5956 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5957 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5959 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5962 - (void) keyboardWillHide:(NSNotification *)notification {
5963 NSTimeInterval duration;
5964 UIViewAnimationCurve curve;
5965 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5966 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5968 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5971 - (void) viewWillAppear:(BOOL)animated {
5972 [super viewWillAppear:animated];
5974 [self resizeForKeyboardBounds:CGRectZero];
5975 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5976 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5979 - (void) viewWillDisappear:(BOOL)animated {
5980 [super viewWillDisappear:animated];
5982 [self resizeForKeyboardBounds:CGRectZero];
5983 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5984 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5987 - (void) viewDidAppear:(BOOL)animated {
5988 [super viewDidAppear:animated];
5989 [self deselectWithAnimation:animated];
5992 - (void) didSelectPackage:(Package *)package {
5993 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5994 [view setDelegate:delegate_];
5995 [[self navigationController] pushViewController:view animated:YES];
5998 #if TryIndexedCollation
5999 + (BOOL) hasIndexedCollation {
6000 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6004 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6005 NSInteger count([sections_ count]);
6006 return count == 0 ? 1 : count;
6009 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6010 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6012 return [[sections_ objectAtIndex:section] name];
6015 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6016 if ([sections_ count] == 0)
6018 return [[sections_ objectAtIndex:section] count];
6021 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6022 @synchronized (database_) {
6023 if ([database_ era] != era_)
6026 Section *section([sections_ objectAtIndex:[path section]]);
6027 NSInteger row([path row]);
6028 Package *package([packages_ objectAtIndex:([section row] + row)]);
6029 return [[package retain] autorelease];
6032 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6033 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6035 cell = [[[PackageCell alloc] init] autorelease];
6036 [cell setPackage:[self packageAtIndexPath:path]];
6040 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6041 Package *package([self packageAtIndexPath:path]);
6042 package = [database_ packageWithName:[package id]];
6043 [self didSelectPackage:package];
6046 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6050 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6051 #if TryIndexedCollation
6052 if ([[self class] hasIndexedCollation]) {
6053 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6060 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6061 if ((self = [super init]) != nil) {
6062 database_ = database;
6063 title_ = [title copy];
6064 [[self navigationItem] setTitle:title_];
6066 #if TryIndexedCollation
6067 if ([[self class] hasIndexedCollation])
6068 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6071 index_ = [NSMutableArray arrayWithCapacity:32];
6073 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6075 packages_ = [NSMutableArray arrayWithCapacity:16];
6076 sections_ = [NSMutableArray arrayWithCapacity:16];
6078 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6079 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6080 [list_ setRowHeight:73];
6081 [[self view] addSubview:list_];
6083 // XXX: is 20 the most optimal number here?
6084 [list_ setSectionIndexMinimumDisplayRowCount:20];
6086 [(UITableView *) list_ setDataSource:self];
6087 [list_ setDelegate:self];
6091 - (void) setDelegate:(id)delegate {
6092 delegate_ = delegate;
6095 - (bool) hasPackage:(Package *)package {
6099 - (bool) shouldYield {
6103 - (void) _reloadPackages:(NSArray *)packages {
6104 [packages_ removeAllObjects];
6105 [sections_ removeAllObjects];
6107 _profile(PackageTable$reloadData$Filter)
6108 for (Package *package in packages)
6109 if ([self hasPackage:package])
6110 [packages_ addObject:package];
6114 - (void) _reloadData {
6115 era_ = [database_ era];
6116 NSArray *packages = [database_ packages];
6118 if ([self shouldYield]) {
6119 UIProgressHUD *hud([delegate_ addProgressHUD]);
6120 [hud setText:UCLocalize("LOADING")];
6121 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
6122 [delegate_ removeProgressHUD:hud];
6124 [self _reloadPackages:packages];
6127 [indices_ removeAllObjects];
6129 Section *section = nil;
6131 #if TryIndexedCollation
6132 if ([[self class] hasIndexedCollation]) {
6133 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6134 NSArray *titles = [collation sectionIndexTitles];
6137 _profile(PackageTable$reloadData$Section)
6138 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6142 _profile(PackageTable$reloadData$Section$Package)
6143 package = [packages_ objectAtIndex:offset];
6144 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6147 while (secidx < index) {
6150 _profile(PackageTable$reloadData$Section$Allocate)
6151 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6154 _profile(PackageTable$reloadData$Section$Add)
6155 [sections_ addObject:section];
6159 [section addToCount];
6165 [index_ removeAllObjects];
6167 _profile(PackageTable$reloadData$Section)
6168 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6172 _profile(PackageTable$reloadData$Section$Package)
6173 package = [packages_ objectAtIndex:offset];
6174 index = [package index];
6177 if (section == nil || [section index] != index) {
6178 _profile(PackageTable$reloadData$Section$Allocate)
6179 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6182 [index_ addObject:[section name]];
6183 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6185 _profile(PackageTable$reloadData$Section$Add)
6186 [sections_ addObject:section];
6190 [section addToCount];
6195 _profile(PackageTable$reloadData$List)
6200 - (void) reloadData {
6202 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6205 - (void) resetCursor {
6206 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6211 /* Filtered Package List Controller {{{ */
6212 @interface FilteredPackageListController : PackageListController {
6215 _H<NSObject> object_;
6218 - (void) setObject:(id)object;
6219 - (void) setObject:(id)object forFilter:(SEL)filter;
6222 - (void) setFilter:(SEL)filter;
6224 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6228 @implementation FilteredPackageListController
6234 - (void) setFilter:(SEL)filter {
6237 /* XXX: this is an unsafe optimization of doomy hell */
6238 Method method(class_getInstanceMethod([Package class], filter));
6239 _assert(method != NULL);
6240 imp_ = method_getImplementation(method);
6241 _assert(imp_ != NULL);
6244 - (void) setObject:(id)object {
6248 - (void) setObject:(id)object forFilter:(SEL)filter {
6249 [self setFilter:filter];
6250 [self setObject:object];
6253 - (bool) hasPackage:(Package *)package {
6254 _profile(FilteredPackageTable$hasPackage)
6255 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6259 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6260 if ((self = [super initWithDatabase:database title:title]) != nil) {
6261 [self setFilter:filter];
6262 [self setObject:object];
6269 /* Home Controller {{{ */
6270 @interface HomeController : CydiaWebViewController {
6275 @implementation HomeController
6278 if ((self = [super init]) != nil) {
6279 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6284 - (NSURL *) navigationURL {
6285 return [NSURL URLWithString:@"cydia://home"];
6288 - (void) aboutButtonClicked {
6289 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6291 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6292 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6293 [alert setCancelButtonIndex:0];
6296 @"Copyright \u00a9 2008-2011\n"
6299 "Jay Freeman (saurik)\n"
6300 "saurik@saurik.com\n"
6301 "http://www.saurik.com/"
6307 - (UIBarButtonItem *) leftButton {
6308 return [[[UIBarButtonItem alloc]
6309 initWithTitle:UCLocalize("ABOUT")
6310 style:UIBarButtonItemStylePlain
6312 action:@selector(aboutButtonClicked)
6316 - (void) unloadData {
6323 /* Manage Controller {{{ */
6324 @interface ManageController : CydiaWebViewController {
6327 - (void) queueStatusDidChange;
6331 @implementation ManageController
6334 if ((self = [super init]) != nil) {
6335 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6339 - (NSURL *) navigationURL {
6340 return [NSURL URLWithString:@"cydia://manage"];
6343 - (UIBarButtonItem *) leftButton {
6344 return [[[UIBarButtonItem alloc]
6345 initWithTitle:UCLocalize("SETTINGS")
6346 style:UIBarButtonItemStylePlain
6348 action:@selector(settingsButtonClicked)
6352 - (void) settingsButtonClicked {
6353 [delegate_ showSettings];
6356 - (void) queueButtonClicked {
6360 - (UIBarButtonItem *) customButton {
6361 return Queuing_ ? [[[UIBarButtonItem alloc]
6362 initWithTitle:UCLocalize("QUEUE")
6363 style:UIBarButtonItemStyleDone
6365 action:@selector(queueButtonClicked)
6366 ] autorelease] : [super customButton];
6369 - (void) queueStatusDidChange {
6370 [self applyRightButton];
6373 - (bool) isLoading {
6374 return !Queuing_ && [super isLoading];
6380 /* Refresh Bar {{{ */
6381 @interface RefreshBar : UINavigationBar {
6382 _H<UIProgressIndicator> indicator_;
6383 _H<UITextLabel> prompt_;
6384 _H<UIProgressBar> progress_;
6385 _H<UINavigationButton> cancel_;
6390 @implementation RefreshBar
6392 - (void) positionViews {
6393 CGRect frame = [cancel_ frame];
6394 frame.size = [cancel_ sizeThatFits:frame.size];
6395 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6396 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6397 [cancel_ setFrame:frame];
6399 CGSize prgsize = {75, 100};
6401 [self frame].size.width - prgsize.width - 10,
6402 ([self frame].size.height - prgsize.height) / 2
6404 [progress_ setFrame:prgrect];
6406 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6407 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6408 CGRect indrect = {{indoffset, indoffset}, indsize};
6409 [indicator_ setFrame:indrect];
6411 CGSize prmsize = {215, indsize.height + 4};
6413 indoffset * 2 + indsize.width,
6414 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6416 [prompt_ setFrame:prmrect];
6419 - (void) setFrame:(CGRect)frame {
6420 [super setFrame:frame];
6421 [self positionViews];
6424 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6425 if ((self = [super initWithFrame:frame]) != nil) {
6426 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6428 [self setBarStyle:UIBarStyleBlack];
6430 UIBarStyle barstyle([self _barStyle:NO]);
6431 bool ugly(barstyle == UIBarStyleDefault);
6433 UIProgressIndicatorStyle style = ugly ?
6434 UIProgressIndicatorStyleMediumBrown :
6435 UIProgressIndicatorStyleMediumWhite;
6437 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6438 [(UIProgressIndicator *) indicator_ setStyle:style];
6439 [indicator_ startAnimation];
6440 [self addSubview:indicator_];
6442 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6443 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6444 [prompt_ setBackgroundColor:[UIColor clearColor]];
6445 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6446 [self addSubview:prompt_];
6448 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6449 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6450 [(UIProgressBar *) progress_ setStyle:0];
6451 [self addSubview:progress_];
6453 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6454 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6455 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6456 [cancel_ setBarStyle:barstyle];
6458 [self positionViews];
6462 - (void) setCancellable:(bool)cancellable {
6464 [self addSubview:cancel_];
6466 [cancel_ removeFromSuperview];
6470 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6471 [progress_ setProgress:0];
6475 [self setCancellable:NO];
6478 - (void) setPrompt:(NSString *)prompt {
6479 [prompt_ setText:prompt];
6482 - (void) setProgress:(float)progress {
6483 [progress_ setProgress:progress];
6489 /* Cydia Navigation Controller Interface {{{ */
6490 @interface UINavigationController (Cydia)
6492 - (NSArray *) navigationURLCollection;
6493 - (void) unloadData;
6498 /* Cydia Tab Bar Controller {{{ */
6499 @interface CYTabBarController : UITabBarController <
6500 UITabBarControllerDelegate,
6503 _transient Database *database_;
6504 _H<RefreshBar> refreshbar_;
6508 // XXX: ok, "updatedelegate_"?...
6509 _transient NSObject<CydiaDelegate> *updatedelegate_;
6511 _H<UIViewController> remembered_;
6512 _transient UIViewController *transient_;
6515 - (NSArray *) navigationURLCollection;
6516 - (void) dropBar:(BOOL)animated;
6517 - (void) beginUpdate;
6518 - (void) raiseBar:(BOOL)animated;
6520 - (void) unloadData;
6524 @implementation CYTabBarController
6526 - (void) setUnselectedViewController:(UIViewController *)transient {
6527 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6528 if (transient != nil) {
6529 if (transient_ == nil)
6530 remembered_ = [controllers objectAtIndex:0];
6531 transient_ = transient;
6532 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6533 [controllers replaceObjectAtIndex:0 withObject:transient_];
6534 [self setSelectedIndex:0];
6535 [self setViewControllers:controllers];
6536 [self concealTabBarSelection];
6537 } else if (remembered_ != nil) {
6538 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6539 transient_ = transient;
6540 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6542 [self setViewControllers:controllers];
6543 [self revealTabBarSelection];
6547 - (UIViewController *) unselectedViewController {
6551 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6552 if ([self unselectedViewController])
6553 [self setUnselectedViewController:nil];
6556 - (NSArray *) navigationURLCollection {
6557 NSMutableArray *items([NSMutableArray array]);
6559 // XXX: Should this deal with transient view controllers?
6560 for (id navigation in [self viewControllers]) {
6561 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6563 [items addObject:stack];
6569 - (void) unloadData {
6570 UIViewController *selected([self selectedViewController]);
6571 for (UINavigationController *controller in [self viewControllers])
6572 [controller unloadData];
6574 [selected reloadData];
6576 if (UIViewController *unselected = [self unselectedViewController])
6577 [unselected reloadData];
6583 [refreshbar_ setDelegate:nil];
6584 [[NSNotificationCenter defaultCenter] removeObserver:self];
6589 - (id) initWithDatabase:(Database *)database {
6590 if ((self = [super init]) != nil) {
6591 database_ = database;
6592 [self setDelegate:self];
6594 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6595 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6597 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6601 - (void) setUpdate:(NSDate *)date {
6605 - (void) beginUpdate {
6606 [(RefreshBar *) refreshbar_ start];
6609 [updatedelegate_ retainNetworkActivityIndicator];
6613 detachNewThreadSelector:@selector(performUpdate)
6619 - (void) performUpdate { _pooled
6621 status.setDelegate(self);
6622 [database_ updateWithStatus:status];
6625 performSelectorOnMainThread:@selector(completeUpdate)
6631 - (void) stopUpdateWithSelector:(SEL)selector {
6633 [updatedelegate_ releaseNetworkActivityIndicator];
6635 [self raiseBar:YES];
6638 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6641 - (void) completeUpdate {
6644 [self stopUpdateWithSelector:@selector(reloadData)];
6647 - (void) cancelUpdate {
6648 [self stopUpdateWithSelector:@selector(updateData)];
6651 - (void) cancelPressed {
6652 [self cancelUpdate];
6659 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6660 [refreshbar_ setPrompt:[event compoundMessage]];
6663 - (bool) isProgressCancelled {
6667 - (void) setProgressCancellable:(NSNumber *)cancellable {
6668 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6671 - (void) setProgressPercent:(NSNumber *)percent {
6672 [refreshbar_ setProgress:[percent floatValue]];
6675 - (void) setProgressStatus:(NSDictionary *)status {
6677 [self setProgressPercent:[status objectForKey:@"Percent"]];
6680 - (void) setUpdateDelegate:(id)delegate {
6681 updatedelegate_ = delegate;
6684 - (CGFloat) statusBarHeight {
6685 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6686 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6688 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6692 - (UIView *) transitionView {
6693 if ([self respondsToSelector:@selector(_transitionView)])
6694 return [self _transitionView];
6696 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6699 - (void) dropBar:(BOOL)animated {
6704 UIView *transition([self transitionView]);
6705 [[self view] addSubview:refreshbar_];
6707 CGRect barframe([refreshbar_ frame]);
6709 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6710 barframe.origin.y = [self statusBarHeight];
6712 barframe.origin.y = 0;
6714 [refreshbar_ setFrame:barframe];
6717 [UIView beginAnimations:nil context:NULL];
6719 CGRect viewframe = [transition frame];
6720 viewframe.origin.y += barframe.size.height;
6721 viewframe.size.height -= barframe.size.height;
6722 [transition setFrame:viewframe];
6725 [UIView commitAnimations];
6727 // Ensure bar has the proper width for our view, it might have changed
6728 barframe.size.width = viewframe.size.width;
6729 [refreshbar_ setFrame:barframe];
6732 - (void) raiseBar:(BOOL)animated {
6737 UIView *transition([self transitionView]);
6738 [refreshbar_ removeFromSuperview];
6740 CGRect barframe([refreshbar_ frame]);
6743 [UIView beginAnimations:nil context:NULL];
6745 CGRect viewframe = [transition frame];
6746 viewframe.origin.y -= barframe.size.height;
6747 viewframe.size.height += barframe.size.height;
6748 [transition setFrame:viewframe];
6751 [UIView commitAnimations];
6754 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6755 bool dropped(dropped_);
6760 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6766 - (void) statusBarFrameChanged:(NSNotification *)notification {
6776 /* Cydia Navigation Controller Implementation {{{ */
6777 @implementation UINavigationController (Cydia)
6779 - (NSArray *) navigationURLCollection {
6780 NSMutableArray *stack([NSMutableArray array]);
6782 for (CyteViewController *controller in [self viewControllers]) {
6783 NSString *url = [[controller navigationURL] absoluteString];
6785 [stack addObject:url];
6791 - (void) reloadData {
6794 if (UIViewController *visible = [self visibleViewController])
6795 [visible reloadData];
6798 - (void) unloadData {
6799 for (CyteViewController *page in [self viewControllers])
6808 /* Cydia:// Protocol {{{ */
6809 @interface CydiaURLProtocol : NSURLProtocol {
6814 @implementation CydiaURLProtocol
6816 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6817 NSURL *url([request URL]);
6821 NSString *scheme([[url scheme] lowercaseString]);
6822 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6824 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6830 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6834 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6835 id<NSURLProtocolClient> client([self client]);
6837 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6839 NSData *data(UIImagePNGRepresentation(icon));
6841 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6842 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6843 [client URLProtocol:self didLoadData:data];
6844 [client URLProtocolDidFinishLoading:self];
6848 - (void) startLoading {
6849 id<NSURLProtocolClient> client([self client]);
6850 NSURLRequest *request([self request]);
6852 NSURL *url([request URL]);
6853 NSString *href([url absoluteString]);
6854 NSString *scheme([[url scheme] lowercaseString]);
6858 if ([scheme isEqualToString:@"cydia"])
6859 path = [href substringFromIndex:8];
6860 else if ([scheme isEqualToString:@"about"])
6861 path = [href substringFromIndex:12];
6862 else _assert(false);
6864 NSRange slash([path rangeOfString:@"/"]);
6867 if (slash.location == NSNotFound) {
6871 command = [path substringToIndex:slash.location];
6872 path = [path substringFromIndex:(slash.location + 1)];
6875 Database *database([Database sharedInstance]);
6877 if ([command isEqualToString:@"package-icon"]) {
6880 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6881 Package *package([database packageWithName:path]);
6884 UIImage *icon([package icon]);
6885 [self _returnPNGWithImage:icon forRequest:request];
6886 } else if ([command isEqualToString:@"source-icon"]) {
6889 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6890 NSString *source(Simplify(path));
6891 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6893 icon = [UIImage applicationImageNamed:@"unknown.png"];
6894 [self _returnPNGWithImage:icon forRequest:request];
6895 } else if ([command isEqualToString:@"uikit-image"]) {
6898 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6899 UIImage *icon(_UIImageWithName(path));
6900 [self _returnPNGWithImage:icon forRequest:request];
6901 } else if ([command isEqualToString:@"section-icon"]) {
6904 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6905 NSString *section(Simplify(path));
6906 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6908 icon = [UIImage applicationImageNamed:@"unknown.png"];
6909 [self _returnPNGWithImage:icon forRequest:request];
6911 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6915 - (void) stopLoading {
6921 /* Section Controller {{{ */
6922 @interface SectionController : FilteredPackageListController {
6923 _H<NSString> section_;
6926 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6930 @implementation SectionController
6932 - (NSURL *) navigationURL {
6933 NSString *name = section_;
6937 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6940 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6943 title = UCLocalize("ALL_PACKAGES");
6944 else if (![name isEqual:@""])
6945 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6947 title = UCLocalize("NO_SECTION");
6949 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6956 /* Sections Controller {{{ */
6957 @interface SectionsController : CyteViewController <
6958 UITableViewDataSource,
6961 _transient Database *database_;
6962 _H<NSMutableArray> sections_;
6963 _H<NSMutableArray> filtered_;
6964 _H<UITableView> list_;
6967 - (id) initWithDatabase:(Database *)database;
6968 - (void) editButtonClicked;
6972 @implementation SectionsController
6974 - (NSURL *) navigationURL {
6975 return [NSURL URLWithString:@"cydia://sections"];
6978 - (void) updateNavigationItem {
6979 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6980 if ([sections_ count] == 0) {
6981 [[self navigationItem] setRightBarButtonItem:nil];
6983 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6984 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6986 action:@selector(editButtonClicked)
6987 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6991 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6992 [super setEditing:editing animated:animated];
6997 [delegate_ updateData];
6999 [self updateNavigationItem];
7002 - (void) viewDidAppear:(BOOL)animated {
7003 [super viewDidAppear:animated];
7004 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7007 - (void) viewWillDisappear:(BOOL)animated {
7008 [super viewWillDisappear:animated];
7009 if ([self isEditing]) [self setEditing:NO];
7012 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7013 Section *section = nil;
7014 int index = [indexPath row];
7015 if (![self isEditing]) {
7018 section = [filtered_ objectAtIndex:index];
7020 section = [sections_ objectAtIndex:index];
7025 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7026 if ([self isEditing])
7027 return [sections_ count];
7029 return [filtered_ count] + 1;
7032 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7036 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7037 static NSString *reuseIdentifier = @"SectionCell";
7039 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7041 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7043 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7048 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7049 if ([self isEditing])
7052 Section *section = [self sectionAtIndexPath:indexPath];
7054 SectionController *controller = [[[SectionController alloc]
7055 initWithDatabase:database_
7056 section:[section name]
7058 [controller setDelegate:delegate_];
7060 [[self navigationController] pushViewController:controller animated:YES];
7064 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7066 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7067 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7068 [list_ setRowHeight:45.0f];
7069 [(UITableView *) list_ setDataSource:self];
7070 [list_ setDelegate:self];
7071 [[self view] addSubview:list_];
7074 - (void) viewDidLoad {
7075 [super viewDidLoad];
7077 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7080 - (void) releaseSubviews {
7084 - (id) initWithDatabase:(Database *)database {
7085 if ((self = [super init]) != nil) {
7086 database_ = database;
7088 sections_ = [NSMutableArray arrayWithCapacity:16];
7089 filtered_ = [NSMutableArray arrayWithCapacity:16];
7093 - (void) reloadData {
7096 NSArray *packages = [database_ packages];
7098 [sections_ removeAllObjects];
7099 [filtered_ removeAllObjects];
7101 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7104 for (Package *package in packages) {
7105 NSString *name([package section]);
7106 NSString *key(name == nil ? @"" : name);
7110 _profile(SectionsView$reloadData$Section)
7111 section = [sections objectForKey:key];
7112 if (section == nil) {
7113 _profile(SectionsView$reloadData$Section$Allocate)
7114 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7115 [sections setObject:section forKey:key];
7120 [section addToCount];
7122 _profile(SectionsView$reloadData$Filter)
7123 if (![package valid] || ![package visible])
7131 [sections_ addObjectsFromArray:[sections allValues]];
7133 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7135 for (Section *section in (id) sections_) {
7136 size_t count([section row]);
7140 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7141 [section setCount:count];
7142 [filtered_ addObject:section];
7145 [self updateNavigationItem];
7150 - (void) editButtonClicked {
7151 [self setEditing:![self isEditing] animated:YES];
7157 /* Changes Controller {{{ */
7158 @interface ChangesController : CyteViewController <
7159 UITableViewDataSource,
7162 _transient Database *database_;
7164 CFMutableArrayRef packages_;
7165 _H<NSMutableArray> sections_;
7166 _H<UITableView> list_;
7170 - (id) initWithDatabase:(Database *)database;
7174 @implementation ChangesController
7177 CFRelease(packages_);
7181 - (NSURL *) navigationURL {
7182 return [NSURL URLWithString:@"cydia://changes"];
7185 - (void) viewDidAppear:(BOOL)animated {
7186 [super viewDidAppear:animated];
7187 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7190 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7191 NSInteger count([sections_ count]);
7192 return count == 0 ? 1 : count;
7195 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7196 if ([sections_ count] == 0)
7198 return [[sections_ objectAtIndex:section] name];
7201 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7202 if ([sections_ count] == 0)
7204 return [[sections_ objectAtIndex:section] count];
7207 - (Package *) packageAtIndex:(NSUInteger)index {
7208 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7211 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7212 @synchronized (database_) {
7213 if ([database_ era] != era_)
7216 NSUInteger sectionIndex([path section]);
7217 if (sectionIndex >= [sections_ count])
7219 Section *section([sections_ objectAtIndex:sectionIndex]);
7220 NSInteger row([path row]);
7221 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7224 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7225 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7227 cell = [[[PackageCell alloc] init] autorelease];
7228 [cell setPackage:[self packageAtIndexPath:path]];
7232 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7233 Package *package([self packageAtIndexPath:path]);
7234 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7235 [view setDelegate:delegate_];
7236 [[self navigationController] pushViewController:view animated:YES];
7240 - (void) refreshButtonClicked {
7241 [delegate_ beginUpdate];
7242 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7245 - (void) upgradeButtonClicked {
7246 [delegate_ distUpgrade];
7250 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7252 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7253 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7254 [list_ setRowHeight:73];
7255 [(UITableView *) list_ setDataSource:self];
7256 [list_ setDelegate:self];
7257 [[self view] addSubview:list_];
7260 - (void) viewDidLoad {
7261 [super viewDidLoad];
7263 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7266 - (void) releaseSubviews {
7270 - (id) initWithDatabase:(Database *)database {
7271 if ((self = [super init]) != nil) {
7272 database_ = database;
7274 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7275 sections_ = [NSMutableArray arrayWithCapacity:16];
7279 // this mostly works because reloadData (below) is @synchronized (database_)
7280 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7281 - (void) _reloadPackages:(NSArray *)packages {
7282 CFRelease(packages_);
7283 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7286 _profile(ChangesController$_reloadPackages$Filter)
7287 for (Package *package in packages)
7288 if ([package upgradableAndEssential:YES] || [package visible])
7289 CFArrayAppendValue(packages_, package);
7292 _profile(ChangesController$_reloadPackages$radixSort)
7293 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7298 - (void) _reloadData {
7299 @synchronized (database_) {
7300 era_ = [database_ era];
7301 NSArray *packages = [database_ packages];
7304 UIProgressHUD *hud([delegate_ addProgressHUD]);
7305 [hud setText:UCLocalize("LOADING")];
7306 //NSLog(@"HUD:%@::%@", delegate_, hud);
7307 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7308 [delegate_ removeProgressHUD:hud];
7310 [self _reloadPackages:packages];
7313 [sections_ removeAllObjects];
7315 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7316 Section *ignored = nil;
7317 Section *section = nil;
7321 bool unseens = false;
7323 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7325 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7326 Package *package = [self packageAtIndex:offset];
7328 BOOL uae = [package upgradableAndEssential:YES];
7332 time_t seen([package seen]);
7334 if (section == nil || last != seen) {
7338 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7341 _profile(ChangesController$reloadData$Allocate)
7342 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7343 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7344 [sections_ addObject:section];
7348 [section addToCount];
7349 } else if ([package ignored]) {
7350 if (ignored == nil) {
7351 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7353 [ignored addToCount];
7356 [upgradable addToCount];
7361 CFRelease(formatter);
7364 Section *last = [sections_ lastObject];
7365 size_t count = [last count];
7366 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7367 [sections_ removeLastObject];
7370 if ([ignored count] != 0)
7371 [sections_ insertObject:ignored atIndex:0];
7373 [sections_ insertObject:upgradable atIndex:0];
7378 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7379 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7380 style:UIBarButtonItemStylePlain
7382 action:@selector(upgradeButtonClicked)
7385 if (![delegate_ updating])
7386 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7387 initWithTitle:UCLocalize("REFRESH")
7388 style:UIBarButtonItemStylePlain
7390 action:@selector(refreshButtonClicked)
7396 - (void) reloadData {
7398 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7403 /* Search Controller {{{ */
7404 @interface SearchController : FilteredPackageListController <
7407 _H<UISearchBar> search_;
7411 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7412 - (void) reloadData;
7416 @implementation SearchController
7419 [search_ setDelegate:nil];
7423 - (NSURL *) navigationURL {
7424 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7425 return [NSURL URLWithString:@"cydia://search"];
7427 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7430 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7431 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7434 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7435 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7436 [search_ resignFirstResponder];
7440 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7441 [search_ setText:@""];
7442 [self searchBarButtonClicked:searchBar];
7445 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7446 [self searchBarButtonClicked:searchBar];
7449 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7450 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7454 - (bool) shouldYield {
7455 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7458 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7459 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7460 search_ = [[[UISearchBar alloc] init] autorelease];
7461 [search_ setDelegate:self];
7464 [search_ setText:query];
7468 - (void) viewDidAppear:(BOOL)animated {
7469 [super viewDidAppear:animated];
7471 if (!searchloaded_) {
7472 searchloaded_ = YES;
7473 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7474 [search_ layoutSubviews];
7475 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7477 UITextField *textField;
7478 if ([search_ respondsToSelector:@selector(searchField)])
7479 textField = [search_ searchField];
7481 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7483 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7484 [textField setEnablesReturnKeyAutomatically:NO];
7485 [[self navigationItem] setTitleView:textField];
7489 - (void) reloadData {
7490 [self setObject:[search_ text]];
7496 - (void) didSelectPackage:(Package *)package {
7497 [search_ resignFirstResponder];
7498 [super didSelectPackage:package];
7503 /* Package Settings Controller {{{ */
7504 @interface PackageSettingsController : CyteViewController <
7505 UITableViewDataSource,
7508 _transient Database *database_;
7510 _H<Package> package_;
7511 _H<UITableView> table_;
7512 _H<UISwitch> subscribedSwitch_;
7513 _H<UISwitch> ignoredSwitch_;
7514 _H<UITableViewCell> subscribedCell_;
7515 _H<UITableViewCell> ignoredCell_;
7518 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7522 @implementation PackageSettingsController
7524 - (NSURL *) navigationURL {
7525 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7528 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7529 if (package_ == nil)
7532 if ([package_ installed] == nil)
7538 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7539 if (package_ == nil)
7542 // both sections contain just one item right now.
7546 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7550 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7552 return UCLocalize("SHOW_ALL_CHANGES_EX");
7554 return UCLocalize("IGNORE_UPGRADES_EX");
7557 - (void) onSubscribed:(id)control {
7558 bool value([control isOn]);
7559 if (package_ == nil)
7561 if ([package_ setSubscribed:value])
7562 [delegate_ updateData];
7565 - (void) _updateIgnored {
7566 const char *package([name_ UTF8String]);
7567 bool on([ignoredSwitch_ isOn]);
7569 pid_t pid(ExecFork());
7571 FILE *dpkg(popen("dpkg --set-selections", "w"));
7572 fwrite(package, strlen(package), 1, dpkg);
7575 fwrite(" hold\n", 6, 1, dpkg);
7577 fwrite(" install\n", 9, 1, dpkg);
7587 int result(waitpid(pid, &status, 0));
7590 _assert(result == pid);
7596 - (void) onIgnored:(id)control {
7597 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7598 [invocation setTarget:self];
7599 [invocation setSelector:@selector(_updateIgnored)];
7601 [delegate_ reloadDataWithInvocation:invocation];
7604 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7605 if (package_ == nil)
7608 switch ([indexPath section]) {
7609 case 0: return subscribedCell_;
7610 case 1: return ignoredCell_;
7619 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7621 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7622 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7623 [(UITableView *) table_ setDataSource:self];
7624 [table_ setDelegate:self];
7625 [[self view] addSubview:table_];
7627 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7628 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7629 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7631 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7632 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7633 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7635 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7636 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7637 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7638 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7640 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7641 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7642 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7643 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7646 - (void) viewDidLoad {
7647 [super viewDidLoad];
7649 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7652 - (void) releaseSubviews {
7654 subscribedCell_ = nil;
7656 ignoredSwitch_ = nil;
7657 subscribedSwitch_ = nil;
7660 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7661 if ((self = [super init]) != nil) {
7662 database_ = database;
7667 - (void) reloadData {
7670 package_ = [database_ packageWithName:name_];
7672 if (package_ != nil) {
7673 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7674 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7675 } // XXX: what now, G?
7677 [table_ reloadData];
7683 /* Installed Controller {{{ */
7684 @interface InstalledController : FilteredPackageListController {
7688 - (id) initWithDatabase:(Database *)database;
7690 - (void) updateRoleButton;
7691 - (void) queueStatusDidChange;
7695 @implementation InstalledController
7701 - (NSURL *) navigationURL {
7702 return [NSURL URLWithString:@"cydia://installed"];
7705 - (id) initWithDatabase:(Database *)database {
7706 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7707 [self updateRoleButton];
7708 [self queueStatusDidChange];
7713 - (void) queueButtonClicked {
7718 - (void) queueStatusDidChange {
7722 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7723 initWithTitle:UCLocalize("QUEUE")
7724 style:UIBarButtonItemStyleDone
7726 action:@selector(queueButtonClicked)
7729 [[self navigationItem] setLeftBarButtonItem:nil];
7735 - (void) updateRoleButton {
7736 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7737 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7738 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7739 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7741 action:@selector(roleButtonClicked)
7745 - (void) roleButtonClicked {
7746 [self setObject:[NSNumber numberWithBool:expert_]];
7750 [self updateRoleButton];
7756 /* Source Cell {{{ */
7757 @interface SourceCell : CYTableViewCell <
7761 _H<NSString> origin_;
7762 _H<NSString> label_;
7765 - (void) setSource:(Source *)source;
7769 @implementation SourceCell
7771 - (void) setSource:(Source *)source {
7774 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7776 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7778 origin_ = [source name];
7779 label_ = [source uri];
7781 [content_ setNeedsDisplay];
7784 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7785 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7786 UIView *content([self contentView]);
7787 CGRect bounds([content bounds]);
7789 content_ = [[[ContentView alloc] initWithFrame:bounds] autorelease];
7790 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7791 [content_ setBackgroundColor:[UIColor whiteColor]];
7792 [content addSubview:content_];
7794 [content_ setDelegate:self];
7795 [content_ setOpaque:YES];
7799 - (NSString *) accessibilityLabel {
7803 - (void) drawContentRect:(CGRect)rect {
7804 bool highlighted(highlighted_);
7805 float width(rect.size.width);
7808 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7815 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7819 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7824 /* Source Controller {{{ */
7825 @interface SourceController : FilteredPackageListController {
7826 _transient Source *source_;
7830 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7834 @implementation SourceController
7836 - (NSURL *) navigationURL {
7837 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7840 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7841 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7843 key_ = [source key];
7847 - (void) reloadData {
7848 source_ = [database_ sourceWithKey:key_];
7849 key_ = [source_ key];
7850 [self setObject:source_];
7852 [[self navigationItem] setTitle:[source_ label]];
7859 /* Sources Controller {{{ */
7860 @interface SourcesController : CyteViewController <
7861 UITableViewDataSource,
7864 _transient Database *database_;
7865 _H<UITableView> list_;
7866 _H<NSMutableArray> sources_;
7870 _H<UIProgressHUD> hud_;
7873 //NSURLConnection *installer_;
7874 NSURLConnection *trivial_;
7875 NSURLConnection *trivial_bz2_;
7876 NSURLConnection *trivial_gz_;
7877 //NSURLConnection *automatic_;
7882 - (id) initWithDatabase:(Database *)database;
7883 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7887 @implementation SourcesController
7889 - (void) _releaseConnection:(NSURLConnection *)connection {
7890 if (connection != nil) {
7891 [connection cancel];
7892 //[connection setDelegate:nil];
7893 [connection release];
7898 //[self _releaseConnection:installer_];
7899 [self _releaseConnection:trivial_];
7900 [self _releaseConnection:trivial_gz_];
7901 [self _releaseConnection:trivial_bz2_];
7902 //[self _releaseConnection:automatic_];
7907 - (NSURL *) navigationURL {
7908 return [NSURL URLWithString:@"cydia://sources"];
7911 - (void) viewDidAppear:(BOOL)animated {
7912 [super viewDidAppear:animated];
7913 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7916 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7917 return offset_ == 0 ? 1 : 2;
7920 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7921 switch (section + (offset_ == 0 ? 1 : 0)) {
7922 case 0: return UCLocalize("ENTERED_BY_USER");
7923 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7929 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7930 int count = [sources_ count];
7932 case 0: return (offset_ == 0 ? count : offset_);
7933 case 1: return count - offset_;
7939 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7941 switch (indexPath.section) {
7942 case 0: idx = indexPath.row; break;
7943 case 1: idx = indexPath.row + offset_; break;
7947 return [sources_ objectAtIndex:idx];
7950 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7951 static NSString *cellIdentifier = @"SourceCell";
7953 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7954 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7955 [cell setSource:[self sourceAtIndexPath:indexPath]];
7956 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7961 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7962 Source *source = [self sourceAtIndexPath:indexPath];
7964 SourceController *controller = [[[SourceController alloc]
7965 initWithDatabase:database_
7969 [controller setDelegate:delegate_];
7971 [[self navigationController] pushViewController:controller animated:YES];
7974 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7975 Source *source = [self sourceAtIndexPath:indexPath];
7976 return [source record] != nil;
7979 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7980 if (editingStyle == UITableViewCellEditingStyleDelete) {
7981 Source *source = [self sourceAtIndexPath:indexPath];
7982 [Sources_ removeObjectForKey:[source key]];
7983 [delegate_ syncData];
7988 [delegate_ addTrivialSource:href_];
7989 [delegate_ syncData];
7992 - (NSString *) getWarning {
7993 NSString *href(href_);
7994 NSRange colon([href rangeOfString:@"://"]);
7995 if (colon.location != NSNotFound)
7996 href = [href substringFromIndex:(colon.location + 3)];
7997 href = [href stringByAddingPercentEscapes];
7998 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7999 href = [href stringByCachingURLWithCurrentCDN];
8001 NSURL *url([NSURL URLWithString:href]);
8003 NSStringEncoding encoding;
8004 NSError *error(nil);
8006 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8007 return [warning length] == 0 ? nil : warning;
8011 - (void) _endConnection:(NSURLConnection *)connection {
8012 // XXX: the memory management in this method is horribly awkward
8014 NSURLConnection **field = NULL;
8015 if (connection == trivial_)
8017 else if (connection == trivial_bz2_)
8018 field = &trivial_bz2_;
8019 else if (connection == trivial_gz_)
8020 field = &trivial_gz_;
8021 _assert(field != NULL);
8022 [connection release];
8027 trivial_bz2_ == nil &&
8030 [delegate_ releaseNetworkActivityIndicator];
8032 [delegate_ removeProgressHUD:hud_];
8038 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8041 UIAlertView *alert = [[[UIAlertView alloc]
8042 initWithTitle:UCLocalize("SOURCE_WARNING")
8045 cancelButtonTitle:UCLocalize("CANCEL")
8047 UCLocalize("ADD_ANYWAY"),
8051 [alert setContext:@"warning"];
8052 [alert setNumberOfRows:1];
8056 } else if (error_ != nil) {
8057 UIAlertView *alert = [[[UIAlertView alloc]
8058 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8059 message:[error_ localizedDescription]
8061 cancelButtonTitle:UCLocalize("OK")
8062 otherButtonTitles:nil
8065 [alert setContext:@"urlerror"];
8068 UIAlertView *alert = [[[UIAlertView alloc]
8069 initWithTitle:UCLocalize("NOT_REPOSITORY")
8070 message:UCLocalize("NOT_REPOSITORY_EX")
8072 cancelButtonTitle:UCLocalize("OK")
8073 otherButtonTitles:nil
8076 [alert setContext:@"trivial"];
8085 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8086 switch ([response statusCode]) {
8092 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8093 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8095 [self _endConnection:connection];
8098 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8099 [self _endConnection:connection];
8102 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8103 NSMutableURLRequest *request = [NSMutableURLRequest
8104 requestWithURL:[NSURL URLWithString:href]
8105 cachePolicy:NSURLRequestUseProtocolCachePolicy
8106 timeoutInterval:120.0
8109 [request setHTTPMethod:method];
8111 if (Machine_ != NULL)
8112 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8113 if (UniqueID_ != nil)
8114 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8116 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8119 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8120 NSString *context([alert context]);
8122 if ([context isEqualToString:@"source"]) {
8125 NSString *href = [[alert textField] text];
8127 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8129 if (![href hasSuffix:@"/"])
8130 href_ = [href stringByAppendingString:@"/"];
8134 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8135 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8136 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8137 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8141 // XXX: this is stupid
8142 hud_ = [delegate_ addProgressHUD];
8143 [hud_ setText:UCLocalize("VERIFYING_URL")];
8144 [delegate_ retainNetworkActivityIndicator];
8153 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8154 } else if ([context isEqualToString:@"trivial"])
8155 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8156 else if ([context isEqualToString:@"urlerror"])
8157 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8158 else if ([context isEqualToString:@"warning"]) {
8172 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8177 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8179 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8180 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8181 [list_ setRowHeight:56];
8182 [(UITableView *) list_ setDataSource:self];
8183 [list_ setDelegate:self];
8184 [[self view] addSubview:list_];
8187 - (void) viewDidLoad {
8188 [super viewDidLoad];
8190 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8191 [self updateButtonsForEditingStatus:NO animated:NO];
8194 - (void) releaseSubviews {
8198 - (id) initWithDatabase:(Database *)database {
8199 if ((self = [super init]) != nil) {
8200 database_ = database;
8201 sources_ = [NSMutableArray arrayWithCapacity:16];
8205 - (void) reloadData {
8209 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8212 [sources_ removeAllObjects];
8213 [sources_ addObjectsFromArray:[database_ sources]];
8215 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8218 int count([sources_ count]);
8220 for (int i = 0; i != count; i++) {
8221 if ([[sources_ objectAtIndex:i] record] == nil)
8226 [list_ setEditing:NO];
8227 [self updateButtonsForEditingStatus:NO animated:NO];
8231 - (void) showAddSourcePrompt {
8232 UIAlertView *alert = [[[UIAlertView alloc]
8233 initWithTitle:UCLocalize("ENTER_APT_URL")
8236 cancelButtonTitle:UCLocalize("CANCEL")
8238 UCLocalize("ADD_SOURCE"),
8242 [alert setContext:@"source"];
8244 [alert setNumberOfRows:1];
8245 [alert addTextFieldWithValue:@"http://" label:@""];
8247 UITextInputTraits *traits = [[alert textField] textInputTraits];
8248 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8249 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8250 [traits setKeyboardType:UIKeyboardTypeURL];
8251 // XXX: UIReturnKeyDone
8252 [traits setReturnKeyType:UIReturnKeyNext];
8257 - (void) addButtonClicked {
8258 [self showAddSourcePrompt];
8261 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8262 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8263 initWithTitle:UCLocalize("ADD")
8264 style:UIBarButtonItemStylePlain
8266 action:@selector(addButtonClicked)
8267 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8269 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8270 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8271 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8273 action:@selector(editButtonClicked)
8274 ] autorelease] animated:animated];
8276 if (IsWildcat_ && !editing)
8277 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8278 initWithTitle:UCLocalize("SETTINGS")
8279 style:UIBarButtonItemStylePlain
8281 action:@selector(settingsButtonClicked)
8285 - (void) settingsButtonClicked {
8286 [delegate_ showSettings];
8289 - (void) editButtonClicked {
8290 [list_ setEditing:![list_ isEditing] animated:YES];
8292 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8298 /* Settings Controller {{{ */
8299 @interface SettingsController : CyteViewController <
8300 UITableViewDataSource,
8303 _transient Database *database_;
8304 // XXX: ok, "roledelegate_"?...
8305 _transient id roledelegate_;
8306 _H<UITableView> table_;
8307 _H<UISegmentedControl> segment_;
8308 _H<UIView> container_;
8311 - (void) showDoneButton;
8312 - (void) resizeSegmentedControl;
8316 @implementation SettingsController
8319 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8321 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8322 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8323 [table_ setDelegate:self];
8324 [(UITableView *) table_ setDataSource:self];
8325 [[self view] addSubview:table_];
8327 NSArray *items = [NSArray arrayWithObjects:
8329 UCLocalize("HACKER"),
8330 UCLocalize("DEVELOPER"),
8332 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8333 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8334 [container_ addSubview:segment_];
8337 - (void) viewDidLoad {
8338 [super viewDidLoad];
8340 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8343 if ([Role_ isEqualToString:@"User"]) index = 0;
8344 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8345 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8347 [segment_ setSelectedSegmentIndex:index];
8348 [self showDoneButton];
8351 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8352 [self resizeSegmentedControl];
8355 - (void) releaseSubviews {
8361 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8362 if ((self = [super init]) != nil) {
8363 database_ = database;
8364 roledelegate_ = delegate;
8368 - (void) resizeSegmentedControl {
8369 CGFloat width = [[self view] frame].size.width;
8370 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8373 - (void) viewWillAppear:(BOOL)animated {
8374 [super viewWillAppear:animated];
8376 [self resizeSegmentedControl];
8379 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8380 [self resizeSegmentedControl];
8383 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8384 [self resizeSegmentedControl];
8388 NSString *role(nil);
8390 switch ([segment_ selectedSegmentIndex]) {
8391 case 0: role = @"User"; break;
8392 case 1: role = @"Hacker"; break;
8393 case 2: role = @"Developer"; break;
8398 if (![role isEqualToString:Role_]) {
8399 bool rolling(Role_ == nil);
8402 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8406 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8410 [roledelegate_ loadData];
8412 [roledelegate_ updateData];
8416 - (void) segmentChanged:(UISegmentedControl *)control {
8417 [self showDoneButton];
8420 - (void) saveAndClose {
8423 [[self navigationItem] setRightBarButtonItem:nil];
8424 [[self navigationController] dismissModalViewControllerAnimated:YES];
8427 - (void) doneButtonClicked {
8428 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8429 [spinner startAnimating];
8430 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8431 [[self navigationItem] setRightBarButtonItem:spinItem];
8433 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8436 - (void) showDoneButton {
8437 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8438 initWithTitle:UCLocalize("DONE")
8439 style:UIBarButtonItemStyleDone
8441 action:@selector(doneButtonClicked)
8442 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8445 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8446 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8450 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8454 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8455 return nil; // This method is required by the protocol.
8458 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8460 return UCLocalize("ROLE_EX");
8462 return [NSString stringWithFormat:
8463 @"%@: %@\n%@: %@\n%@: %@",
8464 UCLocalize("USER"), UCLocalize("USER_EX"),
8465 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8466 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8471 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8472 return section == 3 ? 44.0f : 0;
8475 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8476 return section == 3 ? container_ : nil;
8479 - (void) reloadData {
8482 [table_ reloadData];
8487 /* Stash Controller {{{ */
8488 @interface StashController : CyteViewController {
8489 _H<UIActivityIndicatorView> spinner_;
8490 _H<UILabel> status_;
8491 _H<UILabel> caption_;
8496 @implementation StashController
8499 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8500 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8502 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8503 CGRect spinrect = [spinner_ frame];
8504 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8505 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8506 [spinner_ setFrame:spinrect];
8507 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8508 [[self view] addSubview:spinner_];
8509 [spinner_ startAnimating];
8512 captrect.size.width = [[self view] frame].size.width;
8513 captrect.size.height = 40.0f;
8514 captrect.origin.x = 0;
8515 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8516 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8517 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8518 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8519 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8520 [caption_ setTextColor:[UIColor whiteColor]];
8521 [caption_ setBackgroundColor:[UIColor clearColor]];
8522 [caption_ setShadowColor:[UIColor blackColor]];
8523 [caption_ setTextAlignment:UITextAlignmentCenter];
8524 [[self view] addSubview:caption_];
8527 statusrect.size.width = [[self view] frame].size.width;
8528 statusrect.size.height = 30.0f;
8529 statusrect.origin.x = 0;
8530 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8531 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8532 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8533 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8534 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8535 [status_ setTextColor:[UIColor whiteColor]];
8536 [status_ setBackgroundColor:[UIColor clearColor]];
8537 [status_ setShadowColor:[UIColor blackColor]];
8538 [status_ setTextAlignment:UITextAlignmentCenter];
8539 [[self view] addSubview:status_];
8545 @interface CYURLCache : SDURLCache {
8550 @implementation CYURLCache
8552 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8555 else if ([event isEqualToString:@"no-cache"])
8557 else if ([event isEqualToString:@"store"])
8559 else if ([event isEqualToString:@"invalid"])
8561 else if ([event isEqualToString:@"memory"])
8563 else if ([event isEqualToString:@"disk"])
8565 else if ([event isEqualToString:@"miss"])
8568 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8574 @interface Cydia : UIApplication <
8575 ConfirmationControllerDelegate,
8578 UINavigationControllerDelegate,
8579 UITabBarControllerDelegate
8581 _H<UIWindow> window_;
8582 _H<CYTabBarController> tabbar_;
8583 _H<CYEmulatedLoadingController> emulated_;
8585 _H<NSMutableArray> essential_;
8586 _H<NSMutableArray> broken_;
8588 Database *database_;
8590 _H<NSURL> starturl_;
8595 _H<StashController> stash_;
8604 @implementation Cydia
8606 - (void) beginUpdate {
8607 [tabbar_ beginUpdate];
8611 return [tabbar_ updating];
8615 if ([broken_ count] != 0) {
8616 int count = [broken_ count];
8618 UIAlertView *alert = [[[UIAlertView alloc]
8619 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8620 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8622 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8624 UCLocalize("TEMPORARY_IGNORE"),
8628 [alert setContext:@"fixhalf"];
8629 [alert setNumberOfRows:2];
8631 } else if (!Ignored_ && [essential_ count] != 0) {
8632 int count = [essential_ count];
8634 UIAlertView *alert = [[[UIAlertView alloc]
8635 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8636 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8638 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8640 UCLocalize("UPGRADE_ESSENTIAL"),
8641 UCLocalize("COMPLETE_UPGRADE"),
8645 [alert setContext:@"upgrade"];
8650 - (void) _saveConfig {
8656 NSString *error(nil);
8658 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8660 NSError *error(nil);
8661 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8662 NSLog(@"failure to save metadata data: %@", error);
8667 NSLog(@"failure to serialize metadata: %@", error);
8672 // Navigation controller for the queuing badge.
8673 - (UINavigationController *) queueNavigationController {
8674 NSArray *controllers = [tabbar_ viewControllers];
8675 return [controllers objectAtIndex:3];
8678 - (void) unloadData {
8679 [tabbar_ unloadData];
8682 - (void) _updateData {
8687 UINavigationController *navigation = [self queueNavigationController];
8689 id queuedelegate = nil;
8690 if ([[navigation viewControllers] count] > 0)
8691 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8693 [queuedelegate queueStatusDidChange];
8694 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8697 - (void) _refreshIfPossible:(NSDate *)update {
8698 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8700 bool recently = false;
8701 if (update != nil) {
8702 NSTimeInterval interval([update timeIntervalSinceNow]);
8703 if (interval <= 0 && interval > -(15*60))
8707 // Don't automatic refresh if:
8708 // - We already refreshed recently.
8709 // - We already auto-refreshed this launch.
8710 // - Auto-refresh is disabled.
8711 if (recently || loaded_ || ManualRefresh) {
8712 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8714 // If we are cancelling, we need to make sure it knows it's already loaded.
8718 // We are going to load, so remember that.
8722 SCNetworkReachabilityFlags flags; {
8723 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8724 SCNetworkReachabilityGetFlags(reachability, &flags);
8725 CFRelease(reachability);
8728 // XXX: this elaborate mess is what Apple is using to determine this? :(
8729 // XXX: do we care if the user has to intervene? maybe that's ok?
8731 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8732 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8733 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8734 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8735 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8736 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8740 // If we can reach the server, auto-refresh!
8742 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8747 - (void) refreshIfPossible {
8748 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8751 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8752 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8753 [hud setText:UCLocalize("RELOADING_DATA")];
8755 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8758 [self removeProgressHUD:hud];
8762 [essential_ removeAllObjects];
8763 [broken_ removeAllObjects];
8765 NSArray *packages([database_ packages]);
8766 for (Package *package in packages) {
8768 [broken_ addObject:package];
8769 if ([package upgradableAndEssential:NO]) {
8770 if ([package essential])
8771 [essential_ addObject:package];
8776 NSLog(@"changes:#%u", changes);
8778 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8781 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8782 [changesItem setBadgeValue:badge];
8783 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8784 [self setApplicationIconBadgeNumber:changes];
8787 [changesItem setBadgeValue:nil];
8788 [changesItem setAnimatedBadge:NO];
8789 [self setApplicationIconBadgeNumber:0];
8794 [self refreshIfPossible];
8797 - (void) updateData {
8806 @synchronized (self) {
8807 [self _reloadDataWithInvocation:nil];
8811 - (void) disemulate {
8812 if (emulated_ == nil)
8815 [window_ addSubview:[tabbar_ view]];
8816 [[emulated_ view] removeFromSuperview];
8818 [window_ setUserInteractionEnabled:YES];
8821 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8822 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8824 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8826 UIViewController *parent;
8827 if (emulated_ == nil)
8836 [parent presentModalViewController:navigation animated:YES];
8839 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8840 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8842 if (navigation != nil)
8843 [navigation pushViewController:progress animated:YES];
8845 [self presentModalViewController:progress force:YES];
8847 [progress invoke:invocation withTitle:title];
8851 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8852 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8855 - (void) repairWithInvocation:(NSInvocation *)invocation {
8857 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8861 - (void) repairWithSelector:(SEL)selector {
8862 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8868 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8869 _assert(file != NULL);
8871 for (NSString *key in [Sources_ allKeys]) {
8872 NSDictionary *source([Sources_ objectForKey:key]);
8874 fprintf(file, "%s %s %s\n",
8875 [[source objectForKey:@"Type"] UTF8String],
8876 [[source objectForKey:@"URI"] UTF8String],
8877 [[source objectForKey:@"Distribution"] UTF8String]
8883 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8888 - (void) addTrivialSource:(NSString *)href {
8889 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8892 @"./", @"Distribution",
8893 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8898 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8899 @synchronized (self) {
8900 [self _reloadDataWithInvocation:invocation];
8904 - (void) reloadData {
8905 [self reloadDataWithInvocation:nil];
8909 pkgProblemResolver *resolver = [database_ resolver];
8911 resolver->InstallProtect();
8912 if (!resolver->Resolve(true))
8917 // XXX: this is a really crappy way of doing this.
8918 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8919 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8920 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8921 if ([tabbar_ updating])
8922 [tabbar_ cancelUpdate];
8924 if (![database_ prepare])
8927 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8928 [page setDelegate:self];
8929 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8932 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8933 [tabbar_ presentModalViewController:confirm_ animated:YES];
8939 @synchronized (self) {
8944 - (void) clearPackage:(Package *)package {
8945 @synchronized (self) {
8952 - (void) installPackages:(NSArray *)packages {
8953 @synchronized (self) {
8954 for (Package *package in packages)
8961 - (void) installPackage:(Package *)package {
8962 @synchronized (self) {
8969 - (void) removePackage:(Package *)package {
8970 @synchronized (self) {
8977 - (void) distUpgrade {
8978 @synchronized (self) {
8979 if (![database_ upgrade])
8985 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8988 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
8993 - (void) showSettings {
8994 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
8997 - (void) retainNetworkActivityIndicator {
8998 if (activity_++ == 0)
8999 [self setNetworkActivityIndicatorVisible:YES];
9002 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9006 - (void) releaseNetworkActivityIndicator {
9007 if (--activity_ == 0)
9008 [self setNetworkActivityIndicatorVisible:NO];
9011 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9016 - (void) cancelAndClear:(bool)clear {
9017 @synchronized (self) {
9029 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9030 NSString *context([alert context]);
9032 if ([context isEqualToString:@"conffile"]) {
9033 FILE *input = [database_ input];
9034 if (button == [alert cancelButtonIndex])
9035 fprintf(input, "N\n");
9036 else if (button == [alert firstOtherButtonIndex])
9037 fprintf(input, "Y\n");
9040 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9041 } else if ([context isEqualToString:@"fixhalf"]) {
9042 if (button == [alert cancelButtonIndex]) {
9043 @synchronized (self) {
9044 for (Package *broken in (id) broken_) {
9047 NSString *id = [broken id];
9048 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9049 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9050 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9051 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9057 } else if (button == [alert firstOtherButtonIndex]) {
9058 [broken_ removeAllObjects];
9062 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9063 } else if ([context isEqualToString:@"upgrade"]) {
9064 if (button == [alert firstOtherButtonIndex]) {
9065 @synchronized (self) {
9066 for (Package *essential in (id) essential_)
9067 [essential install];
9072 } else if (button == [alert firstOtherButtonIndex] + 1) {
9074 } else if (button == [alert cancelButtonIndex]) {
9078 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9082 - (void) system:(NSString *)command { _pooled
9084 system([command UTF8String]);
9088 - (void) applicationWillSuspend {
9090 [super applicationWillSuspend];
9093 - (BOOL) isSafeToSuspend {
9096 NSLog(@"isSafeToSuspend: locked_ != 0");
9101 // Use external process status API internally.
9102 // This is probably a really bad idea.
9103 // XXX: what is the point of this? does this solve anything at all?
9104 uint64_t status = 0;
9106 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9107 notify_get_state(notify_token, &status);
9108 notify_cancel(notify_token);
9113 NSLog(@"isSafeToSuspend: status != 0");
9119 NSLog(@"isSafeToSuspend: -> true");
9124 - (void) applicationSuspend:(__GSEvent *)event {
9125 if ([self isSafeToSuspend])
9126 [super applicationSuspend:event];
9129 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9130 if ([self isSafeToSuspend])
9131 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9134 - (void) _setSuspended:(BOOL)value {
9135 if ([self isSafeToSuspend])
9136 [super _setSuspended:value];
9139 - (UIProgressHUD *) addProgressHUD {
9140 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9141 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9143 [window_ setUserInteractionEnabled:NO];
9145 UIViewController *target(tabbar_);
9146 if (UIViewController *modal = [target modalViewController])
9149 UIView *view([target view]);
9150 [view addSubview:hud];
9158 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9161 [hud removeFromSuperview];
9162 [window_ setUserInteractionEnabled:YES];
9165 - (CyteViewController *) pageForPackage:(NSString *)name {
9166 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9169 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9170 NSString *scheme([[url scheme] lowercaseString]);
9171 if ([[url absoluteString] length] <= [scheme length] + 3)
9173 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9174 NSArray *components([path pathComponents]);
9176 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9177 return [self pageForPackage:[components objectAtIndex:1]];
9179 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9182 NSString *base([components objectAtIndex:0]);
9184 CyteViewController *controller = nil;
9186 if ([base isEqualToString:@"url"]) {
9187 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9188 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9189 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9190 } else if (!external && [components count] == 1) {
9191 if ([base isEqualToString:@"manage"]) {
9192 controller = [[[ManageController alloc] init] autorelease];
9195 if ([base isEqualToString:@"sources"]) {
9196 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9199 if ([base isEqualToString:@"home"]) {
9200 controller = [[[HomeController alloc] init] autorelease];
9203 if ([base isEqualToString:@"sections"]) {
9204 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9207 if ([base isEqualToString:@"search"]) {
9208 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9211 if ([base isEqualToString:@"changes"]) {
9212 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9215 if ([base isEqualToString:@"installed"]) {
9216 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9218 } else if ([components count] == 2) {
9219 NSString *argument = [components objectAtIndex:1];
9221 if ([base isEqualToString:@"package"]) {
9222 controller = [self pageForPackage:argument];
9225 if (!external && [base isEqualToString:@"search"]) {
9226 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9229 if (!external && [base isEqualToString:@"sections"]) {
9230 if ([argument isEqualToString:@"all"])
9232 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9235 if (!external && [base isEqualToString:@"sources"]) {
9236 if ([argument isEqualToString:@"add"]) {
9237 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9238 [(SourcesController *)controller showAddSourcePrompt];
9240 Source *source = [database_ sourceWithKey:argument];
9241 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9245 if (!external && [base isEqualToString:@"launch"]) {
9246 [self launchApplicationWithIdentifier:argument suspended:NO];
9249 } else if (!external && [components count] == 3) {
9250 NSString *arg1 = [components objectAtIndex:1];
9251 NSString *arg2 = [components objectAtIndex:2];
9253 if ([base isEqualToString:@"package"]) {
9254 if ([arg2 isEqualToString:@"settings"]) {
9255 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9256 } else if ([arg2 isEqualToString:@"files"]) {
9257 if (Package *package = [database_ packageWithName:arg1]) {
9258 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9259 [(FileTable *)controller setPackage:package];
9265 [controller setDelegate:self];
9269 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9270 CyteViewController *page([self pageForURL:url forExternal:external]);
9273 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9274 [nav setViewControllers:[NSArray arrayWithObject:page]];
9275 [tabbar_ setUnselectedViewController:nav];
9281 - (void) applicationOpenURL:(NSURL *)url {
9282 [super applicationOpenURL:url];
9287 [self openCydiaURL:url forExternal:YES];
9290 - (void) applicationWillResignActive:(UIApplication *)application {
9291 // Stop refreshing if you get a phone call or lock the device.
9292 if ([tabbar_ updating])
9293 [tabbar_ cancelUpdate];
9295 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9296 [super applicationWillResignActive:application];
9299 - (void) applicationWillTerminate:(UIApplication *)application {
9301 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9302 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9303 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9308 - (void) setConfigurationData:(NSString *)data {
9309 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9311 if (!conffile_r(data)) {
9312 lprintf("E:invalid conffile\n");
9316 NSString *ofile = conffile_r[1];
9317 //NSString *nfile = conffile_r[2];
9319 UIAlertView *alert = [[[UIAlertView alloc]
9320 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9321 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9323 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9325 UCLocalize("ACCEPT_NEW_COPY"),
9326 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9330 [alert setContext:@"conffile"];
9331 [alert setNumberOfRows:2];
9335 - (void) addStashController {
9337 stash_ = [[[StashController alloc] init] autorelease];
9338 [window_ addSubview:[stash_ view]];
9341 - (void) removeStashController {
9342 [[stash_ view] removeFromSuperview];
9348 [self setIdleTimerDisabled:YES];
9350 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9351 UpdateExternalStatus(1);
9352 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9353 UpdateExternalStatus(0);
9355 [self removeStashController];
9357 if (ExecFork() == 0) {
9358 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9359 perror("launchctl stop");
9363 - (void) setupViewControllers {
9364 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9366 NSMutableArray *items([NSMutableArray arrayWithObjects:
9367 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9368 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9369 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9370 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9374 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9375 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9377 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9380 NSMutableArray *controllers([NSMutableArray array]);
9381 for (UITabBarItem *item in items) {
9382 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9383 [controller setTabBarItem:item];
9384 [controllers addObject:controller];
9386 [tabbar_ setViewControllers:controllers];
9388 [tabbar_ setUpdateDelegate:self];
9391 - (void) applicationDidFinishLaunching:(id)unused {
9393 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9394 [self setApplicationSupportsShakeToEdit:NO];
9396 @synchronized (HostConfig_) {
9397 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9400 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9401 initWithMemoryCapacity:524288
9402 diskCapacity:10485760
9403 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9406 [CydiaWebViewController _initialize];
9408 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9410 // this would disallow http{,s} URLs from accessing this data
9411 //[WebView registerURLSchemeAsLocal:@"cydia"];
9413 Font12_ = [UIFont systemFontOfSize:12];
9414 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9415 Font14_ = [UIFont systemFontOfSize:14];
9416 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9417 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9419 essential_ = [NSMutableArray arrayWithCapacity:4];
9420 broken_ = [NSMutableArray arrayWithCapacity:4];
9422 // XXX: I really need this thing... like, seriously... I'm sorry
9423 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9425 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9426 [window_ orderFront:self];
9427 [window_ makeKey:self];
9428 [window_ setHidden:NO];
9431 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9432 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9433 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9434 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9435 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9436 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9437 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9438 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9439 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9442 [self addStashController];
9443 // XXX: this would be much cleaner as a yieldToSelector:
9444 // that way the removeStashController could happen right here inline
9445 // we also could no longer require the useless stash_ field anymore
9446 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9450 database_ = [Database sharedInstance];
9451 [database_ setDelegate:self];
9453 [window_ setUserInteractionEnabled:NO];
9454 [self setupViewControllers];
9456 emulated_ = [[[CYEmulatedLoadingController alloc] initWithDatabase:database_] autorelease];
9457 [window_ addSubview:[emulated_ view]];
9459 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9463 - (NSArray *) defaultStartPages {
9464 NSMutableArray *standard = [NSMutableArray array];
9465 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9466 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9467 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9469 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9471 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9472 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9474 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9481 [window_ setUserInteractionEnabled:YES];
9482 [self showSettings];
9485 if ([emulated_ modalViewController] != nil)
9486 [emulated_ dismissModalViewControllerAnimated:YES];
9487 [window_ setUserInteractionEnabled:NO];
9495 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9496 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9497 int standardIndex = 0;
9498 NSArray *standard = [self defaultStartPages];
9505 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9506 if (valid && closed != nil) {
9507 NSTimeInterval interval([closed timeIntervalSinceNow]);
9508 // XXX: Is 15 minutes the optimal time here?
9509 if (interval > 0 && interval <= -(15*60))
9513 if (valid && [saved count] != [standard count])
9517 for (unsigned int i = 0; i < [standard count]; i++) {
9518 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9519 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9520 // but it's good enough for now.
9521 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9528 NSArray *items = nil;
9530 [tabbar_ setSelectedIndex:savedIndex];
9533 [tabbar_ setSelectedIndex:standardIndex];
9537 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9538 NSArray *stack = [items objectAtIndex:tab];
9539 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9540 NSMutableArray *current = [NSMutableArray array];
9542 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9543 NSString *addr = [stack objectAtIndex:nav];
9544 NSURL *url = [NSURL URLWithString:addr];
9545 CyteViewController *page = [self pageForURL:url forExternal:NO];
9547 [current addObject:page];
9550 [navigation setViewControllers:current];
9553 // (Try to) show the startup URL.
9554 if (starturl_ != nil) {
9555 [self openCydiaURL:starturl_ forExternal:NO];
9560 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9561 if (item != nil && IsWildcat_) {
9562 [sheet showFromBarButtonItem:item animated:YES];
9564 [sheet showInView:window_];
9568 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9569 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9570 [progress setTitle:task];
9571 [progress addProgressEvent:event];
9574 - (void) addProgressEventForTask:(NSArray *)data {
9575 CydiaProgressEvent *event([data objectAtIndex:0]);
9576 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9577 [self addProgressEvent:event forTask:task];
9580 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9581 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9587 id Alloc_(id self, SEL selector) {
9588 id object = alloc_(self, selector);
9589 lprintf("[%s]A-%p\n", self->isa->name, object);
9594 id Dealloc_(id self, SEL selector) {
9595 id object = dealloc_(self, selector);
9596 lprintf("[%s]D-%p\n", self->isa->name, object);
9600 Class $WebDefaultUIKitDelegate;
9602 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9603 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9604 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9605 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9608 static NSSet *MobilizedFiles_;
9610 static NSURL *MobilizeURL(NSURL *url) {
9611 NSString *path([url path]);
9612 if ([path hasPrefix:@"/var/root/"]) {
9613 NSString *file([path substringFromIndex:10]);
9614 if ([MobilizedFiles_ containsObject:file])
9615 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9621 Class $CFXPreferencesPropertyListSource;
9622 @class CFXPreferencesPropertyListSource;
9624 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9625 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9626 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9627 url = MobilizeURL(url);
9628 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9629 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9635 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9636 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9637 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9638 url = MobilizeURL(url);
9639 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9640 //NSLog(@"%@ %@", [url absoluteString], value);
9646 Class $NSURLConnection;
9648 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9649 NSMutableURLRequest *copy([request mutableCopy]);
9651 NSURL *url([copy URL]);
9652 NSString *host([url host]);
9653 NSString *scheme([[url scheme] lowercaseString]);
9655 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9657 @synchronized (HostConfig_) {
9658 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9659 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9660 [copy setHTTPShouldUsePipelining:YES];
9663 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9667 int main(int argc, char *argv[]) { _pooled
9670 UpdateExternalStatus(0);
9672 if (Class $UIDevice = objc_getClass("UIDevice")) {
9673 UIDevice *device([$UIDevice currentDevice]);
9674 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9678 UIScreen *screen([UIScreen mainScreen]);
9679 if ([screen respondsToSelector:@selector(scale)])
9680 ScreenScale_ = [screen scale];
9684 UIDevice *device([UIDevice currentDevice]);
9685 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9688 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9689 if (idiom == UIUserInterfaceIdiomPhone)
9691 else if (idiom == UIUserInterfaceIdiomPad)
9694 NSLog(@"unknown UIUserInterfaceIdiom!");
9697 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9699 HostConfig_ = [[[NSObject alloc] init] autorelease];
9700 @synchronized (HostConfig_) {
9701 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9702 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9705 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9707 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9709 MobilizedFiles_ = [NSMutableSet setWithObjects:
9710 @"Library/Preferences/com.apple.Accessibility.plist",
9711 @"Library/Preferences/com.apple.preferences.sounds.plist",
9714 /* Library Hacks {{{ */
9715 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9717 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9719 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9720 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9721 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9722 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9725 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9726 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9727 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9728 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9731 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9732 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9733 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9734 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9735 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9738 $NSURLConnection = objc_getClass("NSURLConnection");
9739 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9740 if (NSURLConnection$init$ != NULL) {
9741 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9742 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9745 /* Set Locale {{{ */
9746 Locale_ = CFLocaleCopyCurrent();
9747 Languages_ = [NSLocale preferredLanguages];
9749 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9750 //NSLog(@"%@", [Languages_ description]);
9753 if (Locale_ != NULL)
9754 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9755 else if (Languages_ != nil && [Languages_ count] != 0)
9756 lang = [[Languages_ objectAtIndex:0] UTF8String];
9758 // XXX: consider just setting to C and then falling through?
9762 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9763 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9766 NSLog(@"Setting Language: %s", lang);
9769 setenv("LANG", lang, true);
9770 std::setlocale(LC_ALL, lang);
9774 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9776 /* Parse Arguments {{{ */
9777 bool substrate(false);
9783 for (int argi(1); argi != argc; ++argi)
9784 if (strcmp(argv[argi], "--") == 0) {
9786 argv[argi] = argv[0];
9792 for (int argi(1); argi != arge; ++argi)
9793 if (strcmp(args[argi], "--substrate") == 0)
9796 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9800 App_ = [[NSBundle mainBundle] bundlePath];
9806 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9807 alloc_ = alloc->method_imp;
9808 alloc->method_imp = (IMP) &Alloc_;*/
9810 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9811 dealloc_ = dealloc->method_imp;
9812 dealloc->method_imp = (IMP) &Dealloc_;*/
9814 /* System Information {{{ */
9818 size = sizeof(maxproc);
9819 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9820 perror("sysctlbyname(\"kern.maxproc\", ?)");
9821 else if (maxproc < 64) {
9823 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9824 perror("sysctlbyname(\"kern.maxproc\", #)");
9827 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9828 char *osversion = new char[size];
9829 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9830 perror("sysctlbyname(\"kern.osversion\", ?)");
9832 System_ = [NSString stringWithUTF8String:osversion];
9834 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9835 char *machine = new char[size];
9836 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9837 perror("sysctlbyname(\"hw.machine\", ?)");
9841 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9842 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9843 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9845 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9847 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9848 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9849 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9851 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9852 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9853 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9855 if (mcc != NULL && mnc != NULL)
9856 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9863 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9864 Build_ = [system objectForKey:@"ProductBuildVersion"];
9865 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9866 Product_ = [info objectForKey:@"SafariProductVersion"];
9867 Safari_ = [info objectForKey:@"CFBundleVersion"];
9870 /* Load Database {{{ */
9872 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9874 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9876 if (Metadata_ == NULL)
9877 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9879 Settings_ = [Metadata_ objectForKey:@"Settings"];
9881 Packages_ = [Metadata_ objectForKey:@"Packages"];
9882 Sections_ = [Metadata_ objectForKey:@"Sections"];
9883 Sources_ = [Metadata_ objectForKey:@"Sources"];
9885 Token_ = [Metadata_ objectForKey:@"Token"];
9888 if (Settings_ != nil)
9889 Role_ = [Settings_ objectForKey:@"Role"];
9891 if (Sections_ == nil) {
9892 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9893 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9896 if (Sources_ == nil) {
9897 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9898 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9903 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9906 if (Packages_ != nil) {
9908 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9912 [Metadata_ removeObjectForKey:@"Packages"];
9918 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9920 #define MobileSubstrate_(name) \
9921 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
9922 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
9923 if (handle == NULL) \
9924 NSLog(@"%s", dlerror()); \
9927 MobileSubstrate_(Activator)
9928 MobileSubstrate_(libstatusbar)
9929 MobileSubstrate_(SimulatedKeyEvents)
9930 MobileSubstrate_(WinterBoard)
9932 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9933 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9935 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9937 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9938 unlink("/tmp/.cydia.fw");
9940 } else if (access("/User", F_OK) != 0 || version < 4) {
9943 system("/usr/libexec/cydia/firmware.sh");
9947 _assert([[NSFileManager defaultManager]
9948 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9949 withIntermediateDirectories:YES
9954 if (access("/tmp/cydia.chk", F_OK) == 0) {
9955 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9956 _assert(errno == ENOENT);
9957 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9958 _assert(errno == ENOENT);
9961 /* APT Initialization {{{ */
9962 _assert(pkgInitConfig(*_config));
9963 _assert(pkgInitSystem(*_config, _system));
9966 _config->Set("APT::Acquire::Translation", lang);
9968 // XXX: this timeout might be important :(
9969 //_config->Set("Acquire::http::Timeout", 15);
9971 _config->Set("Acquire::http::MaxParallel", 3);
9973 /* Color Choices {{{ */
9974 space_ = CGColorSpaceCreateDeviceRGB();
9976 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9977 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9978 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9979 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9980 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9981 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9982 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9983 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9984 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9986 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9987 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9989 /* UIKit Configuration {{{ */
9990 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9991 if ($GSFontSetUseLegacyFontMetrics != NULL)
9992 $GSFontSetUseLegacyFontMetrics(YES);
9994 // XXX: I have a feeling this was important
9995 //UIKeyboardDisableAutomaticAppearance();
9998 Colon_ = UCLocalize("COLON_DELIMITED");
9999 Elision_ = UCLocalize("ELISION");
10000 Error_ = UCLocalize("ERROR");
10001 Warning_ = UCLocalize("WARNING");
10004 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10006 CGColorSpaceRelease(space_);
10007 CFRelease(Locale_);