1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
210 #define Cydia_ CYDIA_VERSION
212 #define lprintf(args...) fprintf(stderr, args)
215 #define TraceLogging (1 && !ForRelease)
216 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
217 #define ProfileTimes (0 && !ForRelease)
218 #define ForSaurik (0 && !ForRelease)
219 #define LogBrowser (0 && !ForRelease)
220 #define TrackResize (0 && !ForRelease)
221 #define ManualRefresh (1 && !ForRelease)
222 #define ShowInternals (0 && !ForRelease)
223 #define AlwaysReload (0 && !ForRelease)
224 #define TryIndexedCollation (0 && !ForRelease)
228 #define _trace(args...)
233 #define _profile(name) {
236 #define PrintTimes() do {} while (false)
239 // Hash Functions/Structures {{{
240 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248 static NSString *Colon_;
250 static NSString *Error_;
251 static NSString *Warning_;
253 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
255 static _finline NSString *CydiaURL(NSString *path) {
257 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
258 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
259 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
260 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
261 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
263 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
266 static _finline void UpdateExternalStatus(uint64_t newStatus) {
268 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
269 notify_set_state(notify_token, newStatus);
270 notify_cancel(notify_token);
272 notify_post("com.saurik.Cydia.status");
275 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
276 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
277 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
280 /* NSForcedOrderingSearch doesn't work on the iPhone */
281 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
282 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
283 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
285 /* Insertion Sort {{{ */
287 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
288 const char *ptr = (const char *)list;
290 CFIndex half = count / 2;
291 const char *probe = ptr + elementSize * half;
292 CFComparisonResult cr = comparator(element, probe, context);
293 if (0 == cr) return (probe - (const char *)list) / elementSize;
294 ptr = (cr < 0) ? ptr : probe + elementSize;
295 count = (cr < 0) ? half : (half + (count & 1) - 1);
297 return (ptr - (const char *)list) / elementSize;
300 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
301 const char *ptr = (const char *)list;
303 CFIndex half = count / 2;
304 const char *probe = ptr + elementSize * half;
305 CFComparisonResult cr = comparator(element, probe, context);
306 if (0 == cr) return (probe - (const char *)list) / elementSize;
307 ptr = (cr < 0) ? ptr : probe + elementSize;
308 count = (cr < 0) ? half : (half + (count & 1) - 1);
310 return (ptr - (const char *)list) / elementSize;
313 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
314 if (range.length == 0)
316 const void **values(new const void *[range.length]);
317 CFArrayGetValues(array, range, values);
319 #if HistogramInsertionSort > 0
320 uint32_t total(0), *offsets(new uint32_t[range.length]);
323 for (CFIndex index(1); index != range.length; ++index) {
324 const void *value(values[index]);
325 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
326 CFIndex correct(index);
327 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
328 #if HistogramInsertionSort > 1
329 NSLog(@"%@ < %@", value, values[correct - 1]);
334 if (correct != index) {
335 size_t offset(index - correct);
336 #if HistogramInsertionSort
340 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
342 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
343 values[correct] = value;
347 CFArrayReplaceValues(array, range, values, range.length);
350 #if HistogramInsertionSort > 0
351 for (CFIndex index(0); index != range.length; ++index)
352 if (offsets[index] != 0)
353 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
354 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
361 /* Apple Bug Fixes {{{ */
362 @implementation UIWebDocumentView (Cydia)
364 - (void) _setScrollerOffset:(CGPoint)offset {
365 UIScroller *scroller([self _scroller]);
367 CGSize size([scroller contentSize]);
368 CGSize bounds([scroller bounds].size);
371 max.x = size.width - bounds.width;
372 max.y = size.height - bounds.height;
380 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
381 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
383 [scroller setOffset:offset];
389 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
390 size_t length([self length] - state->state);
393 else if (length > count)
395 for (size_t i(0); i != length; ++i)
396 objects[i] = [self item:state->state++];
397 state->itemsPtr = objects;
398 state->mutationsPtr = (unsigned long *) self;
402 /* Cydia NSString Additions {{{ */
403 @interface NSString (Cydia)
404 - (NSComparisonResult) compareByPath:(NSString *)other;
405 - (NSString *) stringByCachingURLWithCurrentCDN;
406 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
409 @implementation NSString (Cydia)
411 - (NSComparisonResult) compareByPath:(NSString *)other {
412 NSString *prefix = [self commonPrefixWithString:other options:0];
413 size_t length = [prefix length];
415 NSRange lrange = NSMakeRange(length, [self length] - length);
416 NSRange rrange = NSMakeRange(length, [other length] - length);
418 lrange = [self rangeOfString:@"/" options:0 range:lrange];
419 rrange = [other rangeOfString:@"/" options:0 range:rrange];
421 NSComparisonResult value;
423 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
424 value = NSOrderedSame;
425 else if (lrange.location == NSNotFound)
426 value = NSOrderedAscending;
427 else if (rrange.location == NSNotFound)
428 value = NSOrderedDescending;
430 value = NSOrderedSame;
432 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
433 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
434 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
435 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
437 NSComparisonResult result = [lpath compare:rpath];
438 return result == NSOrderedSame ? value : result;
441 - (NSString *) stringByCachingURLWithCurrentCDN {
443 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
444 withString:@"://cache.cydia.saurik.com/"
448 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
449 return [(id)CFURLCreateStringByAddingPercentEscapes(
454 kCFStringEncodingUTF8
461 /* C++ NSString Wrapper Cache {{{ */
462 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
463 return size == 0 ? NULL :
464 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
465 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
468 static _finline CFStringRef CYStringCreate(const char *data) {
469 return CYStringCreate(data, strlen(data));
478 _finline void clear_() {
479 if (cache_ != NULL) {
486 _finline bool empty() const {
490 _finline size_t size() const {
494 _finline char *data() const {
498 _finline void clear() {
503 _finline CYString() :
510 _finline ~CYString() {
514 void operator =(const CYString &rhs) {
518 if (rhs.cache_ == nil)
521 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
524 void copy(apr_pool_t *pool) {
525 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
526 memcpy(temp, data_, size_);
531 void set(apr_pool_t *pool, const char *data, size_t size) {
537 data_ = const_cast<char *>(data);
545 _finline void set(apr_pool_t *pool, const char *data) {
546 set(pool, data, data == NULL ? 0 : strlen(data));
549 _finline void set(apr_pool_t *pool, const std::string &rhs) {
550 set(pool, rhs.data(), rhs.size());
553 bool operator ==(const CYString &rhs) const {
554 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
557 _finline operator CFStringRef() {
559 cache_ = CYStringCreate(data_, size_);
563 _finline operator id() {
564 return (NSString *) static_cast<CFStringRef>(*this);
567 _finline operator const char *() {
568 return reinterpret_cast<const char *>(data_);
572 /* C++ NSString Algorithm Adapters {{{ */
574 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
577 struct NSStringMapHash :
578 std::unary_function<NSString *, size_t>
580 _finline size_t operator ()(NSString *value) const {
581 return CFStringHashNSString((CFStringRef) value);
585 struct NSStringMapLess :
586 std::binary_function<NSString *, NSString *, bool>
588 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
589 return [lhs compare:rhs] == NSOrderedAscending;
593 struct NSStringMapEqual :
594 std::binary_function<NSString *, NSString *, bool>
596 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
597 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
598 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
599 //[lhs isEqualToString:rhs];
604 /* CoreGraphics Primitives {{{ */
609 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
610 CGFloat color[] = {red, green, blue, alpha};
611 return CGColorCreate(space, color);
620 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
621 color_(Create_(space, red, green, blue, alpha))
623 Set(space, red, green, blue, alpha);
628 CGColorRelease(color_);
635 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
637 color_ = Create_(space, red, green, blue, alpha);
640 operator CGColorRef() {
646 /* Random Global Variables {{{ */
647 static const int PulseInterval_ = 50000;
649 static const NSString *UI_;
652 static bool RestartSubstrate_;
653 static NSArray *Finishes_;
655 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
656 #define NotifyConfig_ "/etc/notify.conf"
658 static bool Queuing_;
660 static CYColor Blue_;
661 static CYColor Blueish_;
662 static CYColor Black_;
664 static CYColor White_;
665 static CYColor Gray_;
666 static CYColor Green_;
667 static CYColor Purple_;
668 static CYColor Purplish_;
670 static UIColor *InstallingColor_;
671 static UIColor *RemovingColor_;
673 static NSString *App_;
675 static BOOL Advanced_;
676 static BOOL Ignored_;
678 static _H<UIFont> Font12_;
679 static _H<UIFont> Font12Bold_;
680 static _H<UIFont> Font14_;
681 static _H<UIFont> Font18Bold_;
682 static _H<UIFont> Font22Bold_;
684 static const char *Machine_ = NULL;
685 static NSString *System_ = nil;
686 static NSString *SerialNumber_ = nil;
687 static NSString *ChipID_ = nil;
688 static NSString *BBSNum_ = nil;
689 static _H<NSString> Token_;
690 static NSString *UniqueID_ = nil;
691 static NSString *PLMN_ = nil;
692 static NSString *Build_ = nil;
693 static NSString *Product_ = nil;
694 static NSString *Safari_ = nil;
696 static CFLocaleRef Locale_;
697 static NSArray *Languages_;
698 static CGColorSpaceRef space_;
700 static NSDictionary *SectionMap_;
701 static NSMutableDictionary *Metadata_;
702 static _transient NSMutableDictionary *Settings_;
703 static _transient NSString *Role_;
704 static _transient NSMutableDictionary *Packages_;
705 static _transient NSMutableDictionary *Values_;
706 static _transient NSMutableDictionary *Sections_;
707 static _transient NSMutableDictionary *Sources_;
708 static _transient NSNumber *Version_;
709 static _transient _H<NSString> CydiaSource_;
710 static bool Changed_;
714 static CGFloat ScreenScale_;
715 static NSString *Idiom_;
716 static NSString *Firmware_;
718 static _H<NSMutableDictionary> SessionData_;
719 static _H<NSObject> HostConfig_;
720 static _H<NSMutableSet> BridgedHosts_;
721 static _H<NSMutableSet> TokenHosts_;
722 static _H<NSMutableSet> InsecureHosts_;
723 static _H<NSMutableSet> PipelinedHosts_;
724 static _H<NSMutableSet> CachedURLs_;
726 static NSString *kCydiaProgressEventTypeError = @"Error";
727 static NSString *kCydiaProgressEventTypeInformation = @"Information";
728 static NSString *kCydiaProgressEventTypeStatus = @"Status";
729 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
732 static void AddSource(NSDictionary *source) {
733 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
737 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
738 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
741 distribution, @"Distribution",
742 sections ?: [NSMutableArray array], @"Sections",
746 static void WriteSources() {
747 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
748 _assert(file != NULL);
750 fprintf(file, "deb http://%s/ tangelo-3.7 main\n",
751 [CydiaSource_ UTF8String]
754 for (NSString *key in [Sources_ allKeys]) {
755 NSDictionary *source([Sources_ objectForKey:key]);
757 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
759 fprintf(file, "%s %s %s%s%s\n",
760 [[source objectForKey:@"Type"] UTF8String],
761 [[source objectForKey:@"URI"] UTF8String],
762 [[source objectForKey:@"Distribution"] UTF8String],
763 [sections count] == 0 ? "" : " ",
764 [[sections componentsJoinedByString:@" "] UTF8String]
771 /* Display Helpers {{{ */
772 inline float Interpolate(float begin, float end, float fraction) {
773 return (end - begin) * fraction + begin;
776 static _finline const char *StripVersion_(const char *version) {
777 const char *colon(strchr(version, ':'));
778 return colon == NULL ? version : colon + 1;
781 NSString *LocalizeSection(NSString *section) {
782 static Pcre title_r("^(.*?) \\((.*)\\)$");
783 if (title_r(section)) {
784 NSString *parent(title_r[1]);
785 NSString *child(title_r[2]);
787 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
788 LocalizeSection(parent),
789 LocalizeSection(child)
793 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
796 NSString *Simplify(NSString *title) {
797 const char *data = [title UTF8String];
798 size_t size = [title length];
800 static Pcre square_r("^\\[(.*)\\]$");
801 if (square_r(data, size))
802 return Simplify(square_r[1]);
804 static Pcre paren_r("^\\((.*)\\)$");
805 if (paren_r(data, size))
806 return Simplify(paren_r[1]);
808 static Pcre title_r("^(.*?) \\((.*)\\)$");
809 if (title_r(data, size))
810 return Simplify(title_r[1]);
816 NSString *GetLastUpdate() {
817 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
820 return UCLocalize("NEVER_OR_UNKNOWN");
822 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
823 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
825 CFRelease(formatter);
827 return [(NSString *) formatted autorelease];
830 bool isSectionVisible(NSString *section) {
831 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
832 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
833 return hidden == nil || ![hidden boolValue];
836 static NSObject *CYIOGetValue(const char *path, NSString *property) {
837 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
838 if (entry == MACH_PORT_NULL)
841 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
842 IOObjectRelease(entry);
846 return [(id) value autorelease];
849 static NSString *CYHex(NSData *data, bool reverse = false) {
853 size_t length([data length]);
854 uint8_t bytes[length];
855 [data getBytes:bytes];
857 char string[length * 2 + 1];
858 for (size_t i(0); i != length; ++i)
859 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
861 return [NSString stringWithUTF8String:string];
866 /* Delegate Prototypes {{{ */
869 @class CydiaProgressEvent;
871 @protocol DatabaseDelegate
872 - (void) repairWithSelector:(SEL)selector;
873 - (void) setConfigurationData:(NSString *)data;
874 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
877 @class CYPackageController;
879 @protocol CydiaDelegate
880 - (void) returnToCydia;
882 - (void) retainNetworkActivityIndicator;
883 - (void) releaseNetworkActivityIndicator;
884 - (void) clearPackage:(Package *)package;
885 - (void) installPackage:(Package *)package;
886 - (void) installPackages:(NSArray *)packages;
887 - (void) removePackage:(Package *)package;
888 - (void) beginUpdate;
890 - (void) distUpgrade;
894 - (void) addSource:(NSDictionary *)source;
895 - (void) addTrivialSource:(NSString *)href;
896 - (void) showSettings;
897 - (UIProgressHUD *) addProgressHUD;
898 - (void) removeProgressHUD:(UIProgressHUD *)hud;
899 - (CyteViewController *) pageForPackage:(NSString *)name;
900 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
901 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
905 /* Status Delegation {{{ */
907 public pkgAcquireStatus
910 _transient NSObject<ProgressDelegate> *delegate_;
920 void setDelegate(NSObject<ProgressDelegate> *delegate) {
921 delegate_ = delegate;
924 NSObject<ProgressDelegate> *getDelegate() const {
928 virtual bool MediaChange(std::string media, std::string drive) {
932 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
936 virtual void Fetch(pkgAcquire::ItemDesc &item) {
937 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
938 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
939 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
942 virtual void Done(pkgAcquire::ItemDesc &item) {
943 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
944 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
945 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
948 virtual void Fail(pkgAcquire::ItemDesc &item) {
950 item.Owner->Status == pkgAcquire::Item::StatIdle ||
951 item.Owner->Status == pkgAcquire::Item::StatDone
955 std::string &error(item.Owner->ErrorText);
959 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
960 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
963 virtual bool Pulse(pkgAcquire *Owner) {
964 bool value = pkgAcquireStatus::Pulse(Owner);
967 double(CurrentBytes + CurrentItems) /
968 double(TotalBytes + TotalItems)
971 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
972 [NSNumber numberWithDouble:percent], @"Percent",
974 [NSNumber numberWithDouble:CurrentBytes], @"Current",
975 [NSNumber numberWithDouble:TotalBytes], @"Total",
976 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
977 nil] waitUntilDone:YES];
979 if (value && ![delegate_ isProgressCancelled])
987 _finline bool WasCancelled() const {
991 virtual void Start() {
992 pkgAcquireStatus::Start();
993 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
996 virtual void Stop() {
997 pkgAcquireStatus::Stop();
998 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
999 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1003 /* Database Interface {{{ */
1004 typedef std::map< unsigned long, _H<Source> > SourceMap;
1006 @interface Database : NSObject {
1012 pkgCacheFile cache_;
1013 pkgDepCache::Policy *policy_;
1014 pkgRecords *records_;
1015 pkgProblemResolver *resolver_;
1016 pkgAcquire *fetcher_;
1018 SPtr<pkgPackageManager> manager_;
1019 pkgSourceList *list_;
1021 SourceMap sourceMap_;
1022 _H<NSMutableArray> sourceList_;
1024 CFMutableArrayRef packages_;
1026 _transient NSObject<DatabaseDelegate> *delegate_;
1027 _transient NSObject<ProgressDelegate> *progress_;
1035 std::map<const char *, _H<NSString> > sections_;
1038 + (Database *) sharedInstance;
1041 - (void) _readCydia:(NSNumber *)fd;
1042 - (void) _readStatus:(NSNumber *)fd;
1043 - (void) _readOutput:(NSNumber *)fd;
1047 - (Package *) packageWithName:(NSString *)name;
1049 - (pkgCacheFile &) cache;
1050 - (pkgDepCache::Policy *) policy;
1051 - (pkgRecords *) records;
1052 - (pkgProblemResolver *) resolver;
1053 - (pkgAcquire &) fetcher;
1054 - (pkgSourceList &) list;
1055 - (NSArray *) packages;
1056 - (NSArray *) sources;
1057 - (Source *) sourceWithKey:(NSString *)key;
1058 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1066 - (void) updateWithStatus:(Status &)status;
1068 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1070 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1071 - (NSObject<ProgressDelegate> *) progressDelegate;
1073 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1075 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1079 /* ProgressEvent Implementation {{{ */
1080 @implementation CydiaProgressEvent
1082 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1083 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1086 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1087 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1088 [event setPackage:package];
1092 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1093 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1095 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1096 NSArray *fields([description componentsSeparatedByString:@" "]);
1097 [event setItem:fields];
1099 if ([fields count] > 3) {
1100 [event setPackage:[fields objectAtIndex:2]];
1101 [event setVersion:[fields objectAtIndex:3]];
1104 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1109 + (NSArray *) _attributeKeys {
1110 return [NSArray arrayWithObjects:
1120 - (NSArray *) attributeKeys {
1121 return [[self class] _attributeKeys];
1124 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1125 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1128 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1129 if ((self = [super init]) != nil) {
1135 - (NSString *) message {
1139 - (NSString *) type {
1143 - (NSArray *) item {
1144 return (id) item_ ?: [NSNull null];
1147 - (void) setItem:(NSArray *)item {
1151 - (NSString *) package {
1152 return (id) package_ ?: [NSNull null];
1155 - (void) setPackage:(NSString *)package {
1159 - (NSString *) url {
1160 return (id) url_ ?: [NSNull null];
1163 - (void) setURL:(NSString *)url {
1167 - (void) setVersion:(NSString *)version {
1171 - (NSString *) version {
1172 return (id) version_ ?: [NSNull null];
1175 - (NSString *) compound:(NSString *)value {
1177 NSString *mode(nil); {
1178 NSString *type([self type]);
1179 if ([type isEqualToString:kCydiaProgressEventTypeError])
1180 mode = UCLocalize("ERROR");
1181 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1182 mode = UCLocalize("WARNING");
1186 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1192 - (NSString *) compoundMessage {
1193 return [self compound:[self message]];
1196 - (NSString *) compoundTitle {
1199 if (package_ == nil)
1201 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1202 title = [package name];
1206 return [self compound:title];
1212 // Cytore Definitions {{{
1213 struct PackageValue :
1216 Cytore::Offset<PackageValue> next_;
1218 uint32_t index_ : 23;
1219 uint32_t subscribed_ : 1;
1236 Cytore::Offset<PackageValue> packages_[1 << 16];
1239 static Cytore::File<MetaValue> MetaFile_;
1241 // Cytore Helper Functions {{{
1242 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1243 SplitHash nhash = { hashlittle(name, length) };
1245 PackageValue *metadata;
1247 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1248 offset: if (offset->IsNull()) {
1249 *offset = MetaFile_.New<PackageValue>(length + 1);
1250 metadata = &MetaFile_.Get(*offset);
1252 if (metadata == NULL) {
1256 metadata = new PackageValue();
1257 memset(metadata, 0, sizeof(*metadata));
1260 memcpy(metadata->name_, name, length + 1);
1261 metadata->nhash_ = nhash.u16[1];
1263 metadata = &MetaFile_.Get(*offset);
1265 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1266 offset = &metadata->next_;
1274 static void PackageImport(const void *key, const void *value, void *context) {
1275 bool &fail(*reinterpret_cast<bool *>(context));
1278 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1279 NSLog(@"failed to import package %@", key);
1283 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1284 NSDictionary *package((NSDictionary *) value);
1286 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1287 if ([subscribed boolValue] && !metadata->subscribed_)
1288 metadata->subscribed_ = true;
1290 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1291 time_t time([date timeIntervalSince1970]);
1292 if (metadata->first_ > time || metadata->first_ == 0)
1293 metadata->first_ = time;
1296 NSDate *date([package objectForKey:@"LastSeen"]);
1297 NSString *version([package objectForKey:@"LastVersion"]);
1299 if (date != nil && version != nil) {
1300 time_t time([date timeIntervalSince1970]);
1301 if (metadata->last_ < time || metadata->last_ == 0)
1302 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1303 size_t length(strlen(buffer));
1304 uint16_t vhash(hashlittle(buffer, length));
1306 size_t capped(std::min<size_t>(8, length));
1307 char *latest(buffer + length - capped);
1309 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1310 metadata->vhash_ = vhash;
1312 metadata->last_ = time;
1318 /* Source Class {{{ */
1319 @interface Source : NSObject {
1321 Database *database_;
1324 CYString depiction_;
1325 CYString description_;
1331 CYString distribution_;
1337 _H<NSString> authority_;
1339 CYString defaultIcon_;
1341 _H<NSDictionary> record_;
1345 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1347 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1349 - (NSString *) depictionForPackage:(NSString *)package;
1350 - (NSString *) supportForPackage:(NSString *)package;
1352 - (NSDictionary *) record;
1356 - (NSString *) distribution;
1357 - (NSString *) type;
1359 - (NSString *) base;
1362 - (NSString *) host;
1364 - (NSString *) name;
1365 - (NSString *) shortDescription;
1366 - (NSString *) label;
1367 - (NSString *) origin;
1368 - (NSString *) version;
1370 - (NSString *) defaultIcon;
1374 @implementation Source
1378 distribution_.clear();
1383 description_.clear();
1389 defaultIcon_.clear();
1396 + (NSString *) webScriptNameForSelector:(SEL)selector {
1398 else if (selector == @selector(addSection:))
1399 return @"addSection";
1400 else if (selector == @selector(getField:))
1402 else if (selector == @selector(removeSection:))
1403 return @"removeSection";
1404 else if (selector == @selector(remove))
1410 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1411 return [self webScriptNameForSelector:selector] == nil;
1414 + (NSArray *) _attributeKeys {
1415 return [NSArray arrayWithObjects:
1423 @"shortDescription",
1431 - (NSArray *) attributeKeys {
1432 return [[self class] _attributeKeys];
1435 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1436 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1439 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1442 trusted_ = index->IsTrusted();
1444 uri_.set(pool, index->GetURI());
1445 distribution_.set(pool, index->GetDist());
1446 type_.set(pool, index->GetType());
1448 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1449 if (dindex != NULL) {
1450 base_.set(pool, dindex->MetaIndexURI(""));
1453 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1456 pkgTagFile tags(&fd);
1458 pkgTagSection section;
1465 {"default-icon", &defaultIcon_},
1466 {"depiction", &depiction_},
1467 {"description", &description_},
1469 {"origin", &origin_},
1470 {"support", &support_},
1471 {"version", &version_},
1474 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1475 const char *start, *end;
1477 if (section.Find(names[i].name_, start, end)) {
1478 CYString &value(*names[i].value_);
1479 value.set(pool, start, end - start);
1485 record_ = [Sources_ objectForKey:[self key]];
1487 NSURL *url([NSURL URLWithString:uri_]);
1491 host_ = [host_ lowercaseString];
1496 authority_ = [url path];
1499 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1500 if ((self = [super init]) != nil) {
1501 era_ = [database era];
1502 database_ = database;
1505 [self setMetaIndex:index inPool:pool];
1509 - (NSString *) getField:(NSString *)name {
1510 @synchronized (database_) {
1511 if ([database_ era] != era_ || index_ == NULL)
1514 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1519 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1524 pkgTagFile tags(&fd);
1526 pkgTagSection section;
1529 const char *start, *end;
1530 if (!section.Find([name UTF8String], start, end))
1531 return (NSString *) [NSNull null];
1533 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1536 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1537 NSDictionary *lhr = [self record];
1538 NSDictionary *rhr = [source record];
1540 if ((lhr == nil) != (rhr == nil))
1541 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1543 NSString *lhs = [self name];
1544 NSString *rhs = [source name];
1546 if ([lhs length] != 0 && [rhs length] != 0) {
1547 unichar lhc = [lhs characterAtIndex:0];
1548 unichar rhc = [rhs characterAtIndex:0];
1550 if (isalpha(lhc) && !isalpha(rhc))
1551 return NSOrderedAscending;
1552 else if (!isalpha(lhc) && isalpha(rhc))
1553 return NSOrderedDescending;
1556 return [lhs compare:rhs options:LaxCompareOptions_];
1559 - (NSString *) depictionForPackage:(NSString *)package {
1560 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1563 - (NSString *) supportForPackage:(NSString *)package {
1564 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1567 - (NSArray *) sections {
1568 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1571 - (void) _addSection:(NSString *)section {
1574 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1575 if (![sections containsObject:section]) {
1576 [sections addObject:section];
1580 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1585 - (bool) addSection:(NSString *)section {
1589 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1593 - (void) _removeSection:(NSString *)section {
1597 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1598 if ([sections containsObject:section]) {
1599 [sections removeObject:section];
1604 - (bool) removeSection:(NSString *)section {
1608 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1613 [Sources_ removeObjectForKey:[self key]];
1618 bool value(record_ != nil);
1619 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1623 - (NSDictionary *) record {
1631 - (NSString *) uri {
1635 - (NSString *) distribution {
1636 return distribution_;
1639 - (NSString *) type {
1643 - (NSString *) base {
1647 - (NSString *) key {
1648 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1651 - (NSString *) host {
1655 - (NSString *) name {
1656 return origin_.empty() ? (id) authority_ : origin_;
1659 - (NSString *) shortDescription {
1660 return description_;
1663 - (NSString *) label {
1664 return label_.empty() ? (id) authority_ : label_;
1667 - (NSString *) origin {
1671 - (NSString *) version {
1675 - (NSString *) defaultIcon {
1676 return defaultIcon_;
1681 /* CydiaOperation Class {{{ */
1682 @interface CydiaOperation : NSObject {
1683 _H<NSString> operator_;
1684 _H<NSString> value_;
1687 - (NSString *) operator;
1688 - (NSString *) value;
1692 @implementation CydiaOperation
1694 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1695 if ((self = [super init]) != nil) {
1696 operator_ = [NSString stringWithUTF8String:_operator];
1697 value_ = [NSString stringWithUTF8String:value];
1701 + (NSArray *) _attributeKeys {
1702 return [NSArray arrayWithObjects:
1708 - (NSArray *) attributeKeys {
1709 return [[self class] _attributeKeys];
1712 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1713 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1716 - (NSString *) operator {
1720 - (NSString *) value {
1726 /* CydiaClause Class {{{ */
1727 @interface CydiaClause : NSObject {
1728 _H<NSString> package_;
1729 _H<CydiaOperation> version_;
1732 - (NSString *) package;
1733 - (CydiaOperation *) version;
1737 @implementation CydiaClause
1739 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1740 if ((self = [super init]) != nil) {
1741 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1743 if (const char *version = dep.TargetVer())
1744 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1746 version_ = (id) [NSNull null];
1750 + (NSArray *) _attributeKeys {
1751 return [NSArray arrayWithObjects:
1757 - (NSArray *) attributeKeys {
1758 return [[self class] _attributeKeys];
1761 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1762 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1765 - (NSString *) package {
1769 - (CydiaOperation *) version {
1775 /* CydiaRelation Class {{{ */
1776 @interface CydiaRelation : NSObject {
1777 _H<NSString> relationship_;
1778 _H<NSMutableArray> clauses_;
1781 - (NSString *) relationship;
1782 - (NSArray *) clauses;
1786 @implementation CydiaRelation
1788 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1789 if ((self = [super init]) != nil) {
1790 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1791 clauses_ = [NSMutableArray arrayWithCapacity:8];
1793 pkgCache::DepIterator start;
1794 pkgCache::DepIterator end;
1795 dep.GlobOr(start, end); // ++dep
1798 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1800 // yes, seriously. (wtf?)
1808 + (NSArray *) _attributeKeys {
1809 return [NSArray arrayWithObjects:
1815 - (NSArray *) attributeKeys {
1816 return [[self class] _attributeKeys];
1819 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1820 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1823 - (NSString *) relationship {
1824 return relationship_;
1827 - (NSArray *) clauses {
1831 - (void) addClause:(CydiaClause *)clause {
1832 [clauses_ addObject:clause];
1837 /* Package Class {{{ */
1838 struct ParsedPackage {
1841 CYString architecture_;
1844 CYString depiction_;
1854 @interface Package : NSObject {
1857 uint32_t essential_ : 1;
1858 uint32_t obsolete_ : 1;
1859 uint32_t ignored_ : 1;
1865 _transient Database *database_;
1867 pkgCache::VerIterator version_;
1868 pkgCache::PkgIterator iterator_;
1869 pkgCache::VerFileIterator file_;
1875 CYString installed_;
1877 const char *section_;
1878 _transient NSString *section$_;
1882 PackageValue *metadata_;
1883 ParsedPackage *parsed_;
1885 _H<NSMutableArray> tags_;
1888 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1889 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1891 - (pkgCache::PkgIterator) iterator;
1894 - (NSString *) section;
1895 - (NSString *) simpleSection;
1897 - (NSString *) longSection;
1898 - (NSString *) shortSection;
1902 - (MIMEAddress *) maintainer;
1904 - (NSString *) longDescription;
1905 - (NSString *) shortDescription;
1908 - (PackageValue *) metadata;
1911 - (bool) subscribed;
1912 - (bool) setSubscribed:(bool)subscribed;
1916 - (NSString *) latest;
1917 - (NSString *) installed;
1918 - (BOOL) uninstalled;
1921 - (BOOL) upgradableAndEssential:(BOOL)essential;
1924 - (BOOL) unfiltered;
1928 - (BOOL) halfConfigured;
1929 - (BOOL) halfInstalled;
1931 - (NSString *) mode;
1934 - (NSString *) name;
1936 - (NSString *) homepage;
1937 - (NSString *) depiction;
1938 - (MIMEAddress *) author;
1940 - (NSString *) support;
1942 - (NSArray *) files;
1943 - (NSArray *) warnings;
1944 - (NSArray *) applications;
1946 - (Source *) source;
1949 - (BOOL) matches:(NSArray *)query;
1951 - (bool) hasSupportingRole;
1952 - (BOOL) hasTag:(NSString *)tag;
1953 - (NSString *) primaryPurpose;
1954 - (NSArray *) purposes;
1955 - (bool) isCommercial;
1957 - (void) setIndex:(size_t)index;
1959 - (CYString &) cyname;
1961 - (uint32_t) compareBySection:(NSArray *)sections;
1966 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1967 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1968 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1969 - (bool) isVisibleInSection:(NSString *)section;
1970 - (bool) isVisibleInSource:(Source *)source;
1974 uint32_t PackageChangesRadix(Package *self, void *) {
1979 uint32_t timestamp : 30;
1980 uint32_t ignored : 1;
1981 uint32_t upgradable : 1;
1985 bool upgradable([self upgradableAndEssential:YES]);
1986 value.bits.upgradable = upgradable ? 1 : 0;
1989 value.bits.timestamp = 0;
1990 value.bits.ignored = [self ignored] ? 0 : 1;
1991 value.bits.upgradable = 1;
1993 value.bits.timestamp = [self seen] >> 2;
1994 value.bits.ignored = 0;
1995 value.bits.upgradable = 0;
1998 return _not(uint32_t) - value.key;
2001 uint32_t PackagePrefixRadix(Package *self, void *context) {
2002 size_t offset(reinterpret_cast<size_t>(context));
2003 CYString &name([self cyname]);
2005 size_t size(name.size());
2008 char *text(name.data());
2011 if (!isdigit(text[0]))
2015 while (size != digits && isdigit(text[digits]))
2023 if (offset == 0 && zeros != 0) {
2024 memset(data, '0', zeros);
2025 memcpy(data + zeros, text, 4 - zeros);
2027 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2028 if (size <= offset - zeros)
2031 text += offset - zeros;
2032 size -= offset - zeros;
2035 memcpy(data, text, 4);
2037 memcpy(data, text, size);
2038 memset(data + size, 0, 4 - size);
2041 for (size_t i(0); i != 4; ++i)
2042 if (isalpha(data[i]))
2050 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2052 /* XXX: ntohl may be more honest */
2053 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2056 CYString &(*PackageName)(Package *self, SEL sel);
2058 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2059 _profile(PackageNameCompare)
2060 CYString &lhi(PackageName(lhs, @selector(cyname)));
2061 CYString &rhi(PackageName(rhs, @selector(cyname)));
2062 CFStringRef lhn(lhi), rhn(rhi);
2065 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2066 else if (rhn == NULL)
2067 return NSOrderedDescending;
2069 _profile(PackageNameCompare$NumbersLast)
2070 if (!lhi.empty() && !rhi.empty()) {
2071 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2072 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2073 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2074 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2075 return lha ? NSOrderedAscending : NSOrderedDescending;
2079 CFIndex length = CFStringGetLength(lhn);
2081 _profile(PackageNameCompare$Compare)
2082 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2087 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2088 return PackageNameCompare(*lhs, *rhs, context);
2091 struct PackageNameOrdering :
2092 std::binary_function<Package *, Package *, bool>
2094 _finline bool operator ()(Package *lhs, Package *rhs) const {
2095 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2099 @implementation Package
2101 - (NSString *) description {
2102 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2106 if (parsed_ != NULL)
2111 + (NSString *) webScriptNameForSelector:(SEL)selector {
2113 else if (selector == @selector(clear))
2115 else if (selector == @selector(getField:))
2117 else if (selector == @selector(hasTag:))
2119 else if (selector == @selector(install))
2121 else if (selector == @selector(remove))
2127 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2128 return [self webScriptNameForSelector:selector] == nil;
2131 + (NSArray *) _attributeKeys {
2132 return [NSArray arrayWithObjects:
2152 @"shortDescription",
2165 - (NSArray *) attributeKeys {
2166 return [[self class] _attributeKeys];
2169 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2170 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2173 - (NSArray *) relations {
2174 @synchronized (database_) {
2175 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2176 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2177 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2181 - (NSString *) architecture {
2183 @synchronized (database_) {
2184 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2187 - (NSString *) getField:(NSString *)name {
2188 @synchronized (database_) {
2189 if ([database_ era] != era_ || file_.end())
2192 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2194 const char *start, *end;
2195 if (!parser.Find([name UTF8String], start, end))
2196 return (NSString *) [NSNull null];
2198 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2202 if (parsed_ != NULL)
2204 @synchronized (database_) {
2205 if ([database_ era] != era_ || file_.end())
2208 ParsedPackage *parsed(new ParsedPackage);
2211 _profile(Package$parse)
2212 pkgRecords::Parser *parser;
2214 _profile(Package$parse$Lookup)
2215 parser = &[database_ records]->Lookup(file_);
2220 _profile(Package$parse$Find)
2225 {"architecture", &parsed->architecture_},
2226 {"icon", &parsed->icon_},
2227 {"depiction", &parsed->depiction_},
2228 {"homepage", &parsed->homepage_},
2229 {"website", &website},
2230 {"bugs", &parsed->bugs_},
2231 {"support", &parsed->support_},
2232 {"sponsor", &parsed->sponsor_},
2233 {"author", &parsed->author_},
2236 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2237 const char *start, *end;
2239 if (parser->Find(names[i].name_, start, end)) {
2240 CYString &value(*names[i].value_);
2241 _profile(Package$parse$Value)
2242 value.set(pool_, start, end - start);
2248 _profile(Package$parse$Tagline)
2249 const char *start, *end;
2250 if (parser->ShortDesc(start, end)) {
2251 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2254 while (stop != start && stop[-1] == '\r')
2256 parsed->tagline_.set(pool_, start, stop - start);
2260 _profile(Package$parse$Retain)
2261 if (parsed->homepage_.empty())
2262 parsed->homepage_ = website;
2263 if (parsed->homepage_ == parsed->depiction_)
2264 parsed->homepage_.clear();
2269 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2270 if ((self = [super init]) != nil) {
2271 _profile(Package$initWithVersion)
2274 database_ = database;
2275 era_ = [database era];
2279 pkgCache::PkgIterator iterator(version.ParentPkg());
2280 iterator_ = iterator;
2282 _profile(Package$initWithVersion$Version)
2283 if (!version_.end())
2284 file_ = version_.FileList();
2286 pkgCache &cache([database_ cache]);
2287 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2291 _profile(Package$initWithVersion$Cache)
2292 name_.set(NULL, iterator.Display());
2294 latest_.set(NULL, StripVersion_(version_.VerStr()));
2296 pkgCache::VerIterator current(iterator.CurrentVer());
2298 installed_.set(NULL, StripVersion_(current.VerStr()));
2301 _profile(Package$initWithVersion$Tags)
2302 pkgCache::TagIterator tag(iterator.TagList());
2304 tags_ = [NSMutableArray arrayWithCapacity:8];
2306 const char *name(tag.Name());
2307 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2309 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2310 if (strcmp(name + 6, "enduser") == 0)
2312 else if (strcmp(name + 6, "hacker") == 0)
2314 else if (strcmp(name + 6, "developer") == 0)
2316 else if (strcmp(name + 6, "cydia") == 0)
2322 if (strncmp(name, "cydia::", 7) == 0) {
2323 if (strcmp(name + 7, "essential") == 0)
2325 else if (strcmp(name + 7, "obsolete") == 0)
2330 } while (!tag.end());
2334 _profile(Package$initWithVersion$Metadata)
2335 const char *mixed(iterator.Name());
2336 size_t size(strlen(mixed));
2337 char lower[size + 1];
2339 for (size_t i(0); i != size; ++i)
2340 lower[i] = mixed[i] | 0x20;
2343 PackageValue *metadata(PackageFind(lower, size));
2344 metadata_ = metadata;
2346 id_.set(NULL, metadata->name_, size);
2348 const char *latest(version_.VerStr());
2349 size_t length(strlen(latest));
2351 uint16_t vhash(hashlittle(latest, length));
2353 size_t capped(std::min<size_t>(8, length));
2354 latest = latest + length - capped;
2356 if (metadata->first_ == 0)
2357 metadata->first_ = now_;
2359 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2360 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2361 metadata->vhash_ = vhash;
2362 metadata->last_ = now_;
2363 } else if (metadata->last_ == 0)
2364 metadata->last_ = metadata->first_;
2367 _profile(Package$initWithVersion$Section)
2368 section_ = iterator.Section();
2371 _profile(Package$initWithVersion$Flags)
2372 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2373 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2378 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2379 pkgCache::VerIterator version;
2381 _profile(Package$packageWithIterator$GetCandidateVer)
2382 version = [database policy]->GetCandidateVer(iterator);
2390 _profile(Package$packageWithIterator$Allocate)
2391 package = [Package allocWithZone:zone];
2394 _profile(Package$packageWithIterator$Initialize)
2396 initWithVersion:version
2403 _profile(Package$packageWithIterator$Autorelease)
2404 package = [package autorelease];
2410 - (pkgCache::PkgIterator) iterator {
2414 - (NSString *) section {
2415 if (section$_ == nil) {
2416 if (section_ == NULL)
2419 _profile(Package$section$mappedSectionForPointer)
2420 section$_ = [database_ mappedSectionForPointer:section_];
2425 - (NSString *) simpleSection {
2426 if (NSString *section = [self section])
2427 return Simplify(section);
2432 - (NSString *) longSection {
2433 return LocalizeSection([self section]);
2436 - (NSString *) shortSection {
2437 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2440 - (NSString *) uri {
2443 pkgIndexFile *index;
2444 pkgCache::PkgFileIterator file(file_.File());
2445 if (![database_ list].FindIndex(file, index))
2447 return [NSString stringWithUTF8String:iterator_->Path];
2448 //return [NSString stringWithUTF8String:file.Site()];
2449 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2453 - (MIMEAddress *) maintainer {
2454 @synchronized (database_) {
2455 if ([database_ era] != era_ || file_.end())
2458 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2459 const std::string &maintainer(parser->Maintainer());
2460 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2464 @synchronized (database_) {
2465 if ([database_ era] != era_ || version_.end())
2468 return version_->InstalledSize;
2471 - (NSString *) longDescription {
2472 @synchronized (database_) {
2473 if ([database_ era] != era_ || file_.end())
2476 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2477 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2479 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2480 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2481 if ([lines count] < 2)
2484 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2485 for (size_t i(1), e([lines count]); i != e; ++i) {
2486 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2487 [trimmed addObject:trim];
2490 return [trimmed componentsJoinedByString:@"\n"];
2493 - (NSString *) shortDescription {
2494 if (parsed_ != NULL)
2495 return static_cast<NSString *>(parsed_->tagline_);
2497 @synchronized (database_) {
2498 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2500 const char *start, *end;
2501 if (!parser.ShortDesc(start, end))
2504 if (end - start > 200)
2508 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2511 while (end != start && end[-1] == '\r')
2515 return [(id) CYStringCreate(start, end - start) autorelease];
2519 _profile(Package$index)
2520 CFStringRef name((CFStringRef) [self name]);
2521 if (CFStringGetLength(name) == 0)
2523 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2524 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2526 return toupper(character);
2530 - (PackageValue *) metadata {
2535 PackageValue *metadata([self metadata]);
2536 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2539 - (bool) subscribed {
2540 return [self metadata]->subscribed_;
2543 - (bool) setSubscribed:(bool)subscribed {
2544 PackageValue *metadata([self metadata]);
2545 if (metadata->subscribed_ == subscribed)
2547 metadata->subscribed_ = subscribed;
2555 - (NSString *) latest {
2559 - (NSString *) installed {
2563 - (BOOL) uninstalled {
2564 return installed_.empty();
2568 return !version_.end();
2571 - (BOOL) upgradableAndEssential:(BOOL)essential {
2572 _profile(Package$upgradableAndEssential)
2573 pkgCache::VerIterator current(iterator_.CurrentVer());
2575 return essential && essential_;
2577 return !version_.end() && version_ != current;
2581 - (BOOL) essential {
2586 return [database_ cache][iterator_].InstBroken();
2589 - (BOOL) unfiltered {
2590 _profile(Package$unfiltered$obsolete)
2591 if (_unlikely(obsolete_))
2595 _profile(Package$unfiltered$hasSupportingRole)
2596 if (_unlikely(![self hasSupportingRole]))
2604 if (![self unfiltered])
2609 _profile(Package$visible$section)
2610 section = [self section];
2613 _profile(Package$visible$isSectionVisible)
2614 if (!isSectionVisible(section))
2622 unsigned char current(iterator_->CurrentState);
2623 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2626 - (BOOL) halfConfigured {
2627 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2630 - (BOOL) halfInstalled {
2631 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2635 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2636 return state.Mode != pkgDepCache::ModeKeep;
2639 - (NSString *) mode {
2640 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2642 switch (state.Mode) {
2643 case pkgDepCache::ModeDelete:
2644 if ((state.iFlags & pkgDepCache::Purge) != 0)
2648 case pkgDepCache::ModeKeep:
2649 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2650 return @"REINSTALL";
2651 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2655 case pkgDepCache::ModeInstall:
2656 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2657 return @"REINSTALL";
2658 else*/ switch (state.Status) {
2660 return @"DOWNGRADE";
2666 return @"NEW_INSTALL";
2677 - (NSString *) name {
2678 return name_.empty() ? id_ : name_;
2681 - (UIImage *) icon {
2682 NSString *section = [self simpleSection];
2685 if (parsed_ != NULL)
2686 if (NSString *href = parsed_->icon_)
2687 if ([href hasPrefix:@"file:///"])
2688 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2689 if (icon == nil) if (section != nil)
2690 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2691 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2692 if ([dicon hasPrefix:@"file:///"])
2693 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2695 icon = [UIImage applicationImageNamed:@"unknown.png"];
2699 - (NSString *) homepage {
2700 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2703 - (NSString *) depiction {
2704 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2707 - (MIMEAddress *) sponsor {
2708 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2711 - (MIMEAddress *) author {
2712 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2715 - (NSString *) support {
2716 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2719 - (NSArray *) files {
2720 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2721 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2724 fin.open([path UTF8String]);
2729 while (std::getline(fin, line))
2730 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2735 - (NSString *) state {
2736 @synchronized (database_) {
2737 if ([database_ era] != era_ || file_.end())
2740 switch (iterator_->CurrentState) {
2741 case pkgCache::State::NotInstalled:
2742 return @"NotInstalled";
2743 case pkgCache::State::UnPacked:
2745 case pkgCache::State::HalfConfigured:
2746 return @"HalfConfigured";
2747 case pkgCache::State::HalfInstalled:
2748 return @"HalfInstalled";
2749 case pkgCache::State::ConfigFiles:
2750 return @"ConfigFiles";
2751 case pkgCache::State::Installed:
2752 return @"Installed";
2753 case pkgCache::State::TriggersAwaited:
2754 return @"TriggersAwaited";
2755 case pkgCache::State::TriggersPending:
2756 return @"TriggersPending";
2759 return (NSString *) [NSNull null];
2762 - (NSString *) selection {
2763 @synchronized (database_) {
2764 if ([database_ era] != era_ || file_.end())
2767 switch (iterator_->SelectedState) {
2768 case pkgCache::State::Unknown:
2770 case pkgCache::State::Install:
2772 case pkgCache::State::Hold:
2774 case pkgCache::State::DeInstall:
2775 return @"DeInstall";
2776 case pkgCache::State::Purge:
2780 return (NSString *) [NSNull null];
2783 - (NSArray *) warnings {
2784 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2785 const char *name(iterator_.Name());
2787 size_t length(strlen(name));
2788 if (length < 2) invalid:
2789 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2790 else for (size_t i(0); i != length; ++i)
2792 /* XXX: technically this is not allowed */
2793 (name[i] < 'A' || name[i] > 'Z') &&
2794 (name[i] < 'a' || name[i] > 'z') &&
2795 (name[i] < '0' || name[i] > '9') &&
2796 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2799 if (strcmp(name, "cydia") != 0) {
2802 bool _private = false;
2805 bool repository = [[self section] isEqualToString:@"Repositories"];
2807 if (NSArray *files = [self files])
2808 for (NSString *file in files)
2809 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2811 else if (!user && [file isEqualToString:@"/User"])
2813 else if (!_private && [file isEqualToString:@"/private"])
2815 else if (!stash && [file isEqualToString:@"/var/stash"])
2818 /* XXX: this is not sensitive enough. only some folders are valid. */
2819 if (cydia && !repository)
2820 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2822 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2824 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2826 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2829 return [warnings count] == 0 ? nil : warnings;
2832 - (NSArray *) applications {
2833 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2835 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2837 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2838 if (NSArray *files = [self files])
2839 for (NSString *file in files)
2840 if (application_r(file)) {
2841 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2842 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2843 if ([id isEqualToString:me])
2846 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2848 display = application_r[1];
2850 NSString *bundle([file stringByDeletingLastPathComponent]);
2851 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2852 if (icon == nil || [icon length] == 0)
2854 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2856 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2857 [applications addObject:application];
2859 [application addObject:id];
2860 [application addObject:display];
2861 [application addObject:url];
2864 return [applications count] == 0 ? nil : applications;
2867 - (Source *) source {
2868 if (source_ == nil) {
2869 @synchronized (database_) {
2870 if ([database_ era] != era_ || file_.end())
2871 source_ = (Source *) [NSNull null];
2873 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2877 return source_ == (Source *) [NSNull null] ? nil : source_;
2884 - (BOOL) matches:(NSArray *)query {
2885 if (query == nil || [query count] == 0)
2894 string = [self name];
2895 length = [string length];
2897 for (NSString *term in query) {
2898 range = [string rangeOfString:term options:MatchCompareOptions_];
2899 if (range.location != NSNotFound)
2900 rank_ -= 6 * 1000000 / length;
2905 length = [string length];
2907 for (NSString *term in query) {
2908 range = [string rangeOfString:term options:MatchCompareOptions_];
2909 if (range.location != NSNotFound)
2910 rank_ -= 6 * 1000000 / length;
2914 string = [self shortDescription];
2915 length = [string length];
2916 NSUInteger stop(std::min<NSUInteger>(length, 200));
2918 for (NSString *term in query) {
2919 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2920 if (range.location != NSNotFound)
2921 rank_ -= 2 * 100000;
2927 - (bool) hasSupportingRole {
2932 if ([Role_ isEqualToString:@"User"])
2936 if ([Role_ isEqualToString:@"Hacker"])
2940 if ([Role_ isEqualToString:@"Developer"])
2945 - (NSArray *) tags {
2949 - (BOOL) hasTag:(NSString *)tag {
2950 return tags_ == nil ? NO : [tags_ containsObject:tag];
2953 - (NSString *) primaryPurpose {
2954 for (NSString *tag in (NSArray *) tags_)
2955 if ([tag hasPrefix:@"purpose::"])
2956 return [tag substringFromIndex:9];
2960 - (NSArray *) purposes {
2961 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2962 for (NSString *tag in (NSArray *) tags_)
2963 if ([tag hasPrefix:@"purpose::"])
2964 [purposes addObject:[tag substringFromIndex:9]];
2965 return [purposes count] == 0 ? nil : purposes;
2968 - (bool) isCommercial {
2969 return [self hasTag:@"cydia::commercial"];
2972 - (void) setIndex:(size_t)index {
2973 if (metadata_->index_ != index)
2974 metadata_->index_ = index;
2977 - (CYString &) cyname {
2978 return name_.empty() ? id_ : name_;
2981 - (uint32_t) compareBySection:(NSArray *)sections {
2982 NSString *section([self section]);
2983 for (size_t i(0), e([sections count]); i != e; ++i) {
2984 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2988 return _not(uint32_t);
2992 @synchronized (database_) {
2993 pkgProblemResolver *resolver = [database_ resolver];
2994 resolver->Clear(iterator_);
2996 pkgCacheFile &cache([database_ cache]);
2997 cache->SetReInstall(iterator_, false);
2998 cache->MarkKeep(iterator_, false);
3002 @synchronized (database_) {
3003 pkgProblemResolver *resolver = [database_ resolver];
3004 resolver->Clear(iterator_);
3005 resolver->Protect(iterator_);
3007 pkgCacheFile &cache([database_ cache]);
3008 cache->SetReInstall(iterator_, false);
3009 cache->MarkInstall(iterator_, false);
3011 pkgDepCache::StateCache &state((*cache)[iterator_]);
3012 if (!state.Install())
3013 cache->SetReInstall(iterator_, true);
3017 @synchronized (database_) {
3018 pkgProblemResolver *resolver = [database_ resolver];
3019 resolver->Clear(iterator_);
3020 resolver->Remove(iterator_);
3021 resolver->Protect(iterator_);
3023 pkgCacheFile &cache([database_ cache]);
3024 cache->SetReInstall(iterator_, false);
3025 cache->MarkDelete(iterator_, true);
3028 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3029 _profile(Package$isUnfilteredAndSearchedForBy)
3032 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3033 value &= [self unfiltered];
3036 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3037 value &= [self matches:query];
3044 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3045 if ([search length] == 0)
3048 _profile(Package$isUnfilteredAndSelectedForBy)
3051 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3052 value &= [self unfiltered];
3055 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3056 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3063 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3064 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3067 - (bool) isVisibleInSection:(NSString *)name {
3068 NSString *section([self section]);
3072 section == nil && [name length] == 0 ||
3073 [name isEqualToString:section]
3074 ) && [self visible];
3077 - (bool) isVisibleInSource:(Source *)source {
3078 return [self source] == source && [self visible];
3083 /* Section Class {{{ */
3084 @interface Section : NSObject {
3089 _H<NSString> localized_;
3092 - (NSComparisonResult) compareByLocalized:(Section *)section;
3093 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3094 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3095 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3096 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3097 - (NSString *) name;
3104 - (void) addToCount;
3106 - (void) setCount:(size_t)count;
3107 - (NSString *) localized;
3111 @implementation Section
3113 - (NSComparisonResult) compareByLocalized:(Section *)section {
3114 NSString *lhs(localized_);
3115 NSString *rhs([section localized]);
3117 /*if ([lhs length] != 0 && [rhs length] != 0) {
3118 unichar lhc = [lhs characterAtIndex:0];
3119 unichar rhc = [rhs characterAtIndex:0];
3121 if (isalpha(lhc) && !isalpha(rhc))
3122 return NSOrderedAscending;
3123 else if (!isalpha(lhc) && isalpha(rhc))
3124 return NSOrderedDescending;
3127 return [lhs compare:rhs options:LaxCompareOptions_];
3130 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3131 if ((self = [self initWithName:name localize:NO]) != nil) {
3132 if (localized != nil)
3133 localized_ = localized;
3137 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3138 return [self initWithName:name row:0 localize:localize];
3141 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3142 if ((self = [super init]) != nil) {
3147 localized_ = LocalizeSection(name_);
3151 /* XXX: localize the index thingees */
3152 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3153 if ((self = [super init]) != nil) {
3154 name_ = [NSString stringWithCharacters:&index length:1];
3160 - (NSString *) name {
3180 - (void) addToCount {
3184 - (void) setCount:(size_t)count {
3188 - (NSString *) localized {
3195 class CydiaLogCleaner :
3196 public pkgArchiveCleaner
3199 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3204 /* Database Implementation {{{ */
3205 @implementation Database
3207 + (Database *) sharedInstance {
3208 static _H<Database> instance;
3209 if (instance == nil)
3210 instance = [[[Database alloc] init] autorelease];
3218 - (void) releasePackages {
3219 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3220 CFArrayRemoveAllValues(packages_);
3224 // XXX: actually implement this thing
3226 [self releasePackages];
3227 apr_pool_destroy(pool_);
3228 NSRecycleZone(zone_);
3232 - (void) _readCydia:(NSNumber *)fd {
3233 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3234 std::istream is(&ib);
3237 static Pcre finish_r("^finish:([^:]*)$");
3239 while (std::getline(is, line)) {
3240 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3242 const char *data(line.c_str());
3243 size_t size = line.size();
3244 lprintf("C:%s\n", data);
3246 if (finish_r(data, size)) {
3247 NSString *finish = finish_r[1];
3248 int index = [Finishes_ indexOfObject:finish];
3249 if (index != INT_MAX && index > Finish_)
3259 - (void) _readStatus:(NSNumber *)fd {
3260 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3261 std::istream is(&ib);
3264 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3265 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3267 while (std::getline(is, line)) {
3268 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3270 const char *data(line.c_str());
3271 size_t size(line.size());
3272 lprintf("S:%s\n", data);
3274 if (conffile_r(data, size)) {
3275 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3276 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3277 } else if (strncmp(data, "status: ", 8) == 0) {
3278 // status: <package>: {unpacked,half-configured,installed}
3279 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3280 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3281 } else if (strncmp(data, "processing: ", 12) == 0) {
3282 // processing: configure: config-test
3283 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3284 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3285 } else if (pmstatus_r(data, size)) {
3286 std::string type([pmstatus_r[1] UTF8String]);
3288 NSString *package = pmstatus_r[2];
3289 if ([package isEqualToString:@"dpkg-exec"])
3292 float percent([pmstatus_r[3] floatValue]);
3293 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3295 NSString *string = pmstatus_r[4];
3297 if (type == "pmerror") {
3298 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3299 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3300 } else if (type == "pmstatus") {
3301 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3302 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3303 } else if (type == "pmconffile")
3304 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3306 lprintf("E:unknown pmstatus\n");
3308 lprintf("E:unknown status\n");
3316 - (void) _readOutput:(NSNumber *)fd {
3317 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3318 std::istream is(&ib);
3321 while (std::getline(is, line)) {
3322 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3324 lprintf("O:%s\n", line.c_str());
3326 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3327 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3339 - (Package *) packageWithName:(NSString *)name {
3342 @synchronized (self) {
3343 if (static_cast<pkgDepCache *>(cache_) == NULL)
3345 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3346 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3350 if ((self = [super init]) != nil) {
3357 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3358 apr_pool_create(&pool_, NULL);
3360 size_t capacity(MetaFile_->active_);
3366 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3367 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3371 _assert(pipe(fds) != -1);
3374 _config->Set("APT::Keep-Fds::", cydiafd_);
3375 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3378 detachNewThreadSelector:@selector(_readCydia:)
3380 withObject:[NSNumber numberWithInt:fds[0]]
3383 _assert(pipe(fds) != -1);
3387 detachNewThreadSelector:@selector(_readStatus:)
3389 withObject:[NSNumber numberWithInt:fds[0]]
3392 _assert(pipe(fds) != -1);
3393 _assert(dup2(fds[0], 0) != -1);
3394 _assert(close(fds[0]) != -1);
3396 input_ = fdopen(fds[1], "a");
3398 _assert(pipe(fds) != -1);
3399 _assert(dup2(fds[1], 1) != -1);
3400 _assert(close(fds[1]) != -1);
3403 detachNewThreadSelector:@selector(_readOutput:)
3405 withObject:[NSNumber numberWithInt:fds[0]]
3410 - (pkgCacheFile &) cache {
3414 - (pkgDepCache::Policy *) policy {
3418 - (pkgRecords *) records {
3422 - (pkgProblemResolver *) resolver {
3426 - (pkgAcquire &) fetcher {
3430 - (pkgSourceList &) list {
3434 - (NSArray *) packages {
3435 return (NSArray *) packages_;
3438 - (NSArray *) sources {
3442 - (Source *) sourceWithKey:(NSString *)key {
3443 for (Source *source in [self sources]) {
3444 if ([[source key] isEqualToString:key])
3449 - (bool) popErrorWithTitle:(NSString *)title {
3452 while (!_error->empty()) {
3454 bool warning(!_error->PopMessage(error));
3459 size_t size(error.size());
3460 if (size == 0 || error[size - 1] != '\n')
3462 error.resize(size - 1);
3465 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3467 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3473 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3474 return [self popErrorWithTitle:title] || !success;
3477 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3478 @synchronized (self) {
3481 [self releasePackages];
3484 [sourceList_ removeAllObjects];
3504 apr_pool_clear(pool_);
3506 NSRecycleZone(zone_);
3507 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3509 int chk(creat("/tmp/cydia.chk", 0644));
3513 if (invocation != nil)
3514 [invocation invoke];
3516 NSString *title(UCLocalize("DATABASE"));
3519 OpProgress progress;
3520 while (!cache_.Open(progress, true)) { pop:
3522 bool warning(!_error->PopMessage(error));
3523 lprintf("cache_.Open():[%s]\n", error.c_str());
3525 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3526 [delegate_ repairWithSelector:@selector(configure)];
3527 else if (error == "The package lists or status file could not be parsed or opened.")
3528 [delegate_ repairWithSelector:@selector(update)];
3529 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3530 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3531 // else if (error == "Malformed Status line")
3532 // else if (error == "The list of sources could not be read.")
3534 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3544 unlink("/tmp/cydia.chk");
3546 now_ = [[NSDate date] timeIntervalSince1970];
3548 policy_ = new pkgDepCache::Policy();
3549 records_ = new pkgRecords(cache_);
3550 resolver_ = new pkgProblemResolver(cache_);
3551 fetcher_ = new pkgAcquire(&status_);
3554 list_ = new pkgSourceList();
3555 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3558 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3559 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3563 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3566 if (cache_->BrokenCount() != 0) {
3567 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3570 if (cache_->BrokenCount() != 0) {
3571 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3575 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3579 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3580 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3581 [sourceList_ addObject:object];
3583 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3584 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3585 // XXX: this could be more intelligent
3586 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3587 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3589 sourceMap_[cached->ID] = object;
3594 /*std::vector<Package *> packages;
3595 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3600 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3601 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3602 //packages.push_back(package);
3603 CFArrayAppendValue(packages_, CFRetain(package));
3607 /*if (packages.empty())
3608 packages_ = [[NSArray alloc] init];
3610 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3613 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3614 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3615 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3623 /*if (!packages.empty())
3624 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3625 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3627 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3629 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3631 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3635 size_t count(CFArrayGetCount(packages_));
3636 MetaFile_->active_ = count;
3638 for (size_t index(0); index != count; ++index)
3639 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3646 @synchronized (self) {
3648 resolver_ = new pkgProblemResolver(cache_);
3650 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3651 if (!cache_[iterator].Keep())
3652 cache_->MarkKeep(iterator, false);
3653 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3654 cache_->SetReInstall(iterator, false);
3657 - (void) configure {
3658 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3660 system([dpkg UTF8String]);
3665 // XXX: I don't remember this condition
3670 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3672 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3674 if ([self popErrorWithTitle:title])
3678 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3680 CydiaLogCleaner cleaner;
3681 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3688 fetcher_->Shutdown();
3690 pkgRecords records(cache_);
3692 lock_ = new FileFd();
3693 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3695 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3697 if ([self popErrorWithTitle:title])
3701 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3704 manager_ = (_system->CreatePM(cache_));
3705 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3712 bool substrate(RestartSubstrate_);
3713 RestartSubstrate_ = false;
3715 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3717 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3719 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3721 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3722 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3725 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3727 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3729 [self popErrorWithTitle:title];
3733 bool failed = false;
3734 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3735 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3737 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3743 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3751 RestartSubstrate_ = true;
3754 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3756 if (_error->PendingError()) {
3761 if (result == pkgPackageManager::Failed) {
3766 if (result != pkgPackageManager::Completed) {
3771 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3773 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3775 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3776 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3779 if (![before isEqualToArray:after])
3784 NSString *title(UCLocalize("UPGRADE"));
3785 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3791 [self updateWithStatus:status_];
3794 - (void) updateWithStatus:(Status &)status {
3795 NSString *title(UCLocalize("REFRESHING_DATA"));
3798 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3802 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3803 if ([self popErrorWithTitle:title])
3806 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3808 bool success(ListUpdate(status, list, PulseInterval_));
3809 if (status.WasCancelled())
3812 [self popErrorWithTitle:title forOperation:success];
3813 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3817 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3820 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3821 delegate_ = delegate;
3824 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3825 progress_ = delegate;
3826 status_.setDelegate(delegate);
3829 - (NSObject<ProgressDelegate> *) progressDelegate {
3833 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3834 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3835 return i == sourceMap_.end() ? nil : i->second;
3838 - (NSString *) mappedSectionForPointer:(const char *)section {
3839 _H<NSString> *mapped;
3841 _profile(Database$mappedSectionForPointer$Cache)
3842 mapped = §ions_[section];
3845 if (*mapped == NULL) {
3846 size_t length(strlen(section));
3847 char spaced[length + 1];
3849 _profile(Database$mappedSectionForPointer$Replace)
3850 for (size_t index(0); index != length; ++index)
3851 spaced[index] = section[index] == '_' ? ' ' : section[index];
3852 spaced[length] = '\0';
3857 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3858 string = [NSString stringWithUTF8String:spaced];
3861 _profile(Database$mappedSectionForPointer$Map)
3862 string = [SectionMap_ objectForKey:string] ?: string;
3872 static _H<NSMutableSet> Diversions_;
3874 @interface Diversion : NSObject {
3877 _H<NSString> format_;
3882 @implementation Diversion
3884 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3885 if ((self = [super init]) != nil) {
3886 pattern_ = [from UTF8String];
3892 - (NSString *) divert:(NSString *)url {
3893 return !pattern_(url) ? nil : pattern_->*format_;
3896 + (NSURL *) divertURL:(NSURL *)url {
3898 NSString *href([url absoluteString]);
3900 for (Diversion *diversion in (id) Diversions_)
3901 if (NSString *diverted = [diversion divert:href]) {
3903 NSLog(@"div: %@", diverted);
3905 url = [NSURL URLWithString:diverted];
3912 - (NSString *) key {
3916 - (NSUInteger) hash {
3920 - (BOOL) isEqual:(Diversion *)object {
3921 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3926 @interface CydiaObject : NSObject {
3927 _H<IndirectDelegate> indirect_;
3928 _transient id delegate_;
3931 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3935 @interface CydiaWebViewController : CyteWebViewController {
3936 _H<CydiaObject> cydia_;
3939 + (void) addDiversion:(Diversion *)diversion;
3943 /* Web Scripting {{{ */
3944 @implementation CydiaObject
3946 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3947 if ((self = [super init]) != nil) {
3948 indirect_ = indirect;
3952 - (void) setDelegate:(id)delegate {
3953 delegate_ = delegate;
3956 + (NSArray *) _attributeKeys {
3957 return [NSArray arrayWithObjects:
3974 - (NSArray *) attributeKeys {
3975 return [[self class] _attributeKeys];
3978 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3979 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3982 - (NSString *) version {
3986 - (NSString *) device {
3987 return [[UIDevice currentDevice] uniqueIdentifier];
3990 - (NSString *) firmware {
3991 return [[UIDevice currentDevice] systemVersion];
3994 - (NSString *) hostname {
3995 return [[UIDevice currentDevice] name];
3998 - (NSString *) idiom {
3999 return (id) Idiom_ ?: [NSNull null];
4002 - (NSString *) plmn {
4003 return (id) PLMN_ ?: [NSNull null];
4006 - (NSString *) bbsnum {
4007 return (id) BBSNum_ ?: [NSNull null];
4010 - (NSString *) ecid {
4011 return (id) ChipID_ ?: [NSNull null];
4014 - (NSString *) serial {
4015 return SerialNumber_;
4018 - (NSString *) role {
4019 return (id) Role_ ?: [NSNull null];
4022 - (NSString *) model {
4023 return [NSString stringWithUTF8String:Machine_];
4026 - (NSString *) token {
4027 return (id) Token_ ?: [NSNull null];
4030 + (NSString *) webScriptNameForSelector:(SEL)selector {
4032 else if (selector == @selector(addBridgedHost:))
4033 return @"addBridgedHost";
4034 else if (selector == @selector(addInsecureHost:))
4035 return @"addInsecureHost";
4036 else if (selector == @selector(addInternalRedirect::))
4037 return @"addInternalRedirect";
4038 else if (selector == @selector(addPipelinedHost:scheme:))
4039 return @"addPipelinedHost";
4040 else if (selector == @selector(addSource:::))
4041 return @"addSource";
4042 else if (selector == @selector(addTokenHost:))
4043 return @"addTokenHost";
4044 else if (selector == @selector(addTrivialSource:))
4045 return @"addTrivialSource";
4046 else if (selector == @selector(close))
4048 else if (selector == @selector(du:))
4050 else if (selector == @selector(stringWithFormat:arguments:))
4052 else if (selector == @selector(getAllSources))
4053 return @"getAllSourcs";
4054 else if (selector == @selector(getKernelNumber:))
4055 return @"getKernelNumber";
4056 else if (selector == @selector(getKernelString:))
4057 return @"getKernelString";
4058 else if (selector == @selector(getInstalledPackages))
4059 return @"getInstalledPackages";
4060 else if (selector == @selector(getIORegistryEntry::))
4061 return @"getIORegistryEntry";
4062 else if (selector == @selector(getLocaleIdentifier))
4063 return @"getLocaleIdentifier";
4064 else if (selector == @selector(getPreferredLanguages))
4065 return @"getPreferredLanguages";
4066 else if (selector == @selector(getPackageById:))
4067 return @"getPackageById";
4068 else if (selector == @selector(getMetadataKeys))
4069 return @"getMetadataKeys";
4070 else if (selector == @selector(getMetadataValue:))
4071 return @"getMetadataValue";
4072 else if (selector == @selector(getSessionValue:))
4073 return @"getSessionValue";
4074 else if (selector == @selector(installPackages:))
4075 return @"installPackages";
4076 else if (selector == @selector(localizedStringForKey:value:table:))
4078 else if (selector == @selector(popViewController:))
4079 return @"popViewController";
4080 else if (selector == @selector(refreshSources))
4081 return @"refreshSources";
4082 else if (selector == @selector(removeButton))
4083 return @"removeButton";
4084 else if (selector == @selector(saveConfig))
4085 return @"saveConfig";
4086 else if (selector == @selector(setCydiaSource:))
4087 return @"setCydiaSource";
4088 else if (selector == @selector(setMetadataValue::))
4089 return @"setMetadataValue";
4090 else if (selector == @selector(setSessionValue::))
4091 return @"setSessionValue";
4092 else if (selector == @selector(substitutePackageNames:))
4093 return @"substitutePackageNames";
4094 else if (selector == @selector(scrollToBottom:))
4095 return @"scrollToBottom";
4096 else if (selector == @selector(setAllowsNavigationAction:))
4097 return @"setAllowsNavigationAction";
4098 else if (selector == @selector(setBadgeValue:))
4099 return @"setBadgeValue";
4100 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4101 return @"setButtonImage";
4102 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4103 return @"setButtonTitle";
4104 else if (selector == @selector(setHidesBackButton:))
4105 return @"setHidesBackButton";
4106 else if (selector == @selector(setHidesNavigationBar:))
4107 return @"setHidesNavigationBar";
4108 else if (selector == @selector(setNavigationBarStyle:))
4109 return @"setNavigationBarStyle";
4110 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4111 return @"setNavigationBarTintColor";
4112 else if (selector == @selector(setPasteboardString:))
4113 return @"setPasteboardString";
4114 else if (selector == @selector(setPasteboardURL:))
4115 return @"setPasteboardURL";
4116 else if (selector == @selector(setToken:))
4118 else if (selector == @selector(setViewportWidth:))
4119 return @"setViewportWidth";
4120 else if (selector == @selector(statfs:))
4122 else if (selector == @selector(supports:))
4124 else if (selector == @selector(unload))
4130 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4131 return [self webScriptNameForSelector:selector] == nil;
4134 - (BOOL) supports:(NSString *)feature {
4135 return [feature isEqualToString:@"window.open"];
4139 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4142 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4143 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4146 - (NSNumber *) getKernelNumber:(NSString *)name {
4147 const char *string([name UTF8String]);
4150 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4151 return (id) [NSNull null];
4153 if (size != sizeof(int))
4154 return (id) [NSNull null];
4157 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4158 return (id) [NSNull null];
4160 return [NSNumber numberWithInt:value];
4163 - (NSString *) getKernelString:(NSString *)name {
4164 const char *string([name UTF8String]);
4167 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4168 return (id) [NSNull null];
4170 char value[size + 1];
4171 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4172 return (id) [NSNull null];
4174 // XXX: just in case you request something ludicrous
4177 return [NSString stringWithCString:value];
4180 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4181 NSObject *value(CYIOGetValue([path UTF8String], entry));
4184 if ([value isKindOfClass:[NSData class]])
4185 value = CYHex((NSData *) value);
4190 - (void) _setCydiaSource:(NSString *)source {
4191 @synchronized (HostConfig_) {
4192 CydiaSource_ = source;
4193 [Metadata_ setObject:source forKey:@"CydiaSource"];
4199 - (void) setCydiaSource:(NSString *)source {
4200 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4203 - (NSString *) cydiaSource {
4204 @synchronized (HostConfig_) {
4205 return (id) CydiaSource_ ?: [NSNull null];
4209 - (NSArray *) getMetadataKeys {
4210 @synchronized (Values_) {
4211 return [Values_ allKeys];
4214 - (id) getMetadataValue:(NSString *)key {
4215 @synchronized (Values_) {
4216 return [Values_ objectForKey:key];
4219 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4220 @synchronized (Values_) {
4221 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4222 [Values_ removeObjectForKey:key];
4224 [Values_ setObject:value forKey:key];
4226 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4229 - (id) getSessionValue:(NSString *)key {
4230 @synchronized (SessionData_) {
4231 return [SessionData_ objectForKey:key];
4234 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4235 @synchronized (SessionData_) {
4236 if (value == (id) [WebUndefined undefined])
4237 [SessionData_ removeObjectForKey:key];
4239 [SessionData_ setObject:value forKey:key];
4242 - (void) addBridgedHost:(NSString *)host {
4243 @synchronized (HostConfig_) {
4244 [BridgedHosts_ addObject:host];
4247 - (void) addInsecureHost:(NSString *)host {
4248 @synchronized (HostConfig_) {
4249 [InsecureHosts_ addObject:host];
4252 - (void) addTokenHost:(NSString *)host {
4253 @synchronized (HostConfig_) {
4254 [TokenHosts_ addObject:host];
4257 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4258 @synchronized (HostConfig_) {
4259 if (scheme != (id) [WebUndefined undefined])
4260 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4262 [PipelinedHosts_ addObject:host];
4265 - (void) popViewController:(NSNumber *)value {
4266 if (value == (id) [WebUndefined undefined])
4267 value = [NSNumber numberWithBool:YES];
4268 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4271 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4272 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4274 for (NSString *section in sections)
4275 [array addObject:section];
4277 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4280 distribution, @"Distribution",
4282 nil] waitUntilDone:NO];
4285 - (void) addTrivialSource:(NSString *)href {
4286 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4289 - (void) refreshSources {
4290 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4293 - (void) saveConfig {
4294 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4297 - (NSArray *) getAllSources {
4298 return [[Database sharedInstance] sources];
4301 - (NSArray *) getInstalledPackages {
4302 Database *database([Database sharedInstance]);
4303 @synchronized (database) {
4304 NSArray *packages([database packages]);
4305 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4306 for (Package *package in packages)
4307 if (![package uninstalled])
4308 [installed addObject:package];
4312 - (Package *) getPackageById:(NSString *)id {
4313 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4317 return (Package *) [NSNull null];
4320 - (NSString *) getLocaleIdentifier {
4321 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4324 - (NSArray *) getPreferredLanguages {
4328 - (NSArray *) statfs:(NSString *)path {
4331 if (path == nil || statfs([path UTF8String], &stat) == -1)
4334 return [NSArray arrayWithObjects:
4335 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4336 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4337 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4341 - (NSNumber *) du:(NSString *)path {
4342 NSNumber *value(nil);
4345 _assert(pipe(fds) != -1);
4347 pid_t pid(ExecFork());
4349 _assert(dup2(fds[1], 1) != -1);
4350 _assert(close(fds[0]) != -1);
4351 _assert(close(fds[1]) != -1);
4352 /* XXX: this should probably not use du */
4353 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4358 _assert(close(fds[1]) != -1);
4360 if (FILE *du = fdopen(fds[0], "r")) {
4362 while (fgets(line, sizeof(line), du) != NULL) {
4363 size_t length(strlen(line));
4364 while (length != 0 && line[length - 1] == '\n')
4365 line[--length] = '\0';
4366 if (char *tab = strchr(line, '\t')) {
4368 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4373 } else _assert(close(fds[0]));
4377 if (waitpid(pid, &status, 0) == -1)
4380 else _assert(false);
4386 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4389 - (void) installPackages:(NSArray *)packages {
4390 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4393 - (NSString *) substitutePackageNames:(NSString *)message {
4394 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4395 for (size_t i(0), e([words count]); i != e; ++i) {
4396 NSString *word([words objectAtIndex:i]);
4397 if (Package *package = [[Database sharedInstance] packageWithName:word])
4398 [words replaceObjectAtIndex:i withObject:[package name]];
4401 return [words componentsJoinedByString:@" "];
4404 - (void) removeButton {
4405 [indirect_ removeButton];
4408 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4409 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4412 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4413 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4416 - (void) setBadgeValue:(id)value {
4417 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4420 - (void) setAllowsNavigationAction:(NSString *)value {
4421 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4424 - (void) setHidesBackButton:(NSString *)value {
4425 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4428 - (void) setHidesNavigationBar:(NSString *)value {
4429 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4432 - (void) setNavigationBarStyle:(NSString *)value {
4433 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4436 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4437 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4438 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4439 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4442 - (void) setPasteboardString:(NSString *)value {
4443 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4446 - (void) setPasteboardURL:(NSString *)value {
4447 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4450 - (void) _setToken:(NSString *)token {
4454 [Metadata_ removeObjectForKey:@"Token"];
4456 [Metadata_ setObject:Token_ forKey:@"Token"];
4461 - (void) setToken:(NSString *)token {
4462 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4465 - (void) scrollToBottom:(NSNumber *)animated {
4466 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4469 - (void) setViewportWidth:(float)width {
4470 [indirect_ setViewportWidthOnMainThread:width];
4473 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4474 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4475 unsigned count([arguments count]);
4477 for (unsigned i(0); i != count; ++i)
4478 values[i] = [arguments objectAtIndex:i];
4479 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4482 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4483 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4485 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4487 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4493 @interface NSURL (CydiaSecure)
4496 @implementation NSURL (CydiaSecure)
4498 - (bool) isCydiaSecure {
4499 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4502 @synchronized (HostConfig_) {
4503 if ([InsecureHosts_ containsObject:[self host]])
4512 /* Cydia Browser Controller {{{ */
4513 @implementation CydiaWebViewController
4515 - (NSURL *) navigationURL {
4516 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4519 + (void) initialize {
4520 Diversions_ = [NSMutableSet setWithCapacity:0];
4523 + (void) addDiversion:(Diversion *)diversion {
4524 [Diversions_ addObject:diversion];
4527 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4528 [super webView:view didClearWindowObject:window forFrame:frame];
4530 WebDataSource *source([frame dataSource]);
4531 NSURLResponse *response([source response]);
4532 NSURL *url([response URL]);
4533 NSString *scheme([[url scheme] lowercaseString]);
4535 bool bridged(false);
4537 @synchronized (HostConfig_) {
4538 if ([scheme isEqualToString:@"file"])
4540 else if ([scheme isEqualToString:@"https"])
4541 if ([BridgedHosts_ containsObject:[url host]])
4546 [window setValue:cydia_ forKey:@"cydia"];
4549 - (void) _setupMail:(MFMailComposeViewController *)controller {
4550 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4552 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4553 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4556 - (NSURL *) URLWithURL:(NSURL *)url {
4557 return [Diversion divertURL:url];
4560 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4561 NSURL *url([request URL]);
4562 NSString *host([url host]);
4564 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4566 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4567 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4568 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4569 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4572 @synchronized (HostConfig_) {
4573 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4576 if ([url isCydiaSecure] && token) {
4577 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4578 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4584 - (void) setDelegate:(id)delegate {
4585 [super setDelegate:delegate];
4586 [cydia_ setDelegate:delegate];
4589 - (NSString *) applicationNameForUserAgent {
4590 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4593 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4595 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4596 if (Product_ != nil)
4597 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4603 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4604 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4610 @interface AppCacheController : CydiaWebViewController {
4615 @implementation AppCacheController
4617 - (void) didReceiveMemoryWarning {
4624 @interface NSObject (CydiaScript)
4625 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4628 @implementation NSObject (CydiaScript)
4630 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4636 @implementation NSArray (CydiaScript)
4638 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4639 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4640 for (size_t i(0), e([self count]); i != e; ++i)
4641 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4647 @implementation NSDictionary (CydiaScript)
4649 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4650 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4652 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4659 /* Confirmation Controller {{{ */
4660 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4661 if (!iterator.end())
4662 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4663 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4665 pkgCache::PkgIterator package(dep.TargetPkg());
4668 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4675 @protocol ConfirmationControllerDelegate
4676 - (void) cancelAndClear:(bool)clear;
4677 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4681 @interface ConfirmationController : CydiaWebViewController {
4682 _transient Database *database_;
4684 _H<UIAlertView> essential_;
4686 _H<NSDictionary> changes_;
4687 _H<NSMutableArray> issues_;
4688 _H<NSDictionary> sizes_;
4693 - (id) initWithDatabase:(Database *)database;
4697 @implementation ConfirmationController
4701 RestartSubstrate_ = true;
4702 [delegate_ confirmWithNavigationController:[self navigationController]];
4705 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4706 NSString *context([alert context]);
4708 if ([context isEqualToString:@"remove"]) {
4709 if (button == [alert cancelButtonIndex])
4710 [self dismissModalViewControllerAnimated:YES];
4711 else if (button == [alert firstOtherButtonIndex]) {
4715 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4716 } else if ([context isEqualToString:@"unable"]) {
4717 [self dismissModalViewControllerAnimated:YES];
4718 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4720 [super alertView:alert clickedButtonAtIndex:button];
4724 - (void) _doContinue {
4725 [delegate_ cancelAndClear:NO];
4726 [self dismissModalViewControllerAnimated:YES];
4729 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4730 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4734 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4735 [super webView:view didClearWindowObject:window forFrame:frame];
4737 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4738 (id) changes_, @"changes",
4739 (id) issues_, @"issues",
4740 (id) sizes_, @"sizes",
4742 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4745 - (id) initWithDatabase:(Database *)database {
4746 if ((self = [super init]) != nil) {
4747 database_ = database;
4749 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4750 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4751 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4752 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4753 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4757 pkgCacheFile &cache([database_ cache]);
4758 NSArray *packages([database_ packages]);
4759 pkgDepCache::Policy *policy([database_ policy]);
4761 issues_ = [NSMutableArray arrayWithCapacity:4];
4763 for (Package *package in packages) {
4764 pkgCache::PkgIterator iterator([package iterator]);
4765 NSString *name([package id]);
4767 if ([package broken]) {
4768 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4770 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4772 reasons, @"reasons",
4775 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4779 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4780 pkgCache::DepIterator start;
4781 pkgCache::DepIterator end;
4782 dep.GlobOr(start, end); // ++dep
4784 if (!cache->IsImportantDep(end))
4786 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4789 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4791 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4792 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4793 clauses, @"clauses",
4797 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4799 pkgCache::PkgIterator target(start.TargetPkg());
4800 if (target->ProvidesList != 0)
4801 reason = @"missing";
4803 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4805 reason = @"installed";
4806 installed = [NSString stringWithUTF8String:ver.VerStr()];
4807 } else if (!cache[target].CandidateVerIter(cache).end())
4808 reason = @"uninstalled";
4809 else if (target->ProvidesList == 0)
4810 reason = @"uninstallable";
4812 reason = @"virtual";
4815 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4816 [NSString stringWithUTF8String:start.CompType()], @"operator",
4817 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4820 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4821 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4822 version, @"version",
4824 installed, @"installed",
4827 // yes, seriously. (wtf?)
4835 pkgDepCache::StateCache &state(cache[iterator]);
4837 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4839 if (state.NewInstall())
4840 [installs addObject:name];
4841 // XXX: else if (state.Install())
4842 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4843 [reinstalls addObject:name];
4844 // XXX: move before previous if
4845 else if (state.Upgrade())
4846 [upgrades addObject:name];
4847 else if (state.Downgrade())
4848 [downgrades addObject:name];
4849 else if (!state.Delete())
4850 // XXX: _assert(state.Keep());
4852 else if (special_r(name))
4853 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4854 [NSNull null], @"package",
4855 [NSArray arrayWithObjects:
4856 [NSDictionary dictionaryWithObjectsAndKeys:
4857 @"Conflicts", @"relationship",
4858 [NSArray arrayWithObjects:
4859 [NSDictionary dictionaryWithObjectsAndKeys:
4861 [NSNull null], @"version",
4862 @"installed", @"reason",
4869 if ([package essential])
4871 [removes addObject:name];
4874 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4875 substrate_ |= DepSubstrate(iterator.CurrentVer());
4880 else if (Advanced_) {
4881 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4883 essential_ = [[[UIAlertView alloc]
4884 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4885 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4887 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4889 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4893 [essential_ setContext:@"remove"];
4895 essential_ = [[[UIAlertView alloc]
4896 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4897 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4899 cancelButtonTitle:UCLocalize("OKAY")
4900 otherButtonTitles:nil
4903 [essential_ setContext:@"unable"];
4906 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4907 installs, @"installs",
4908 reinstalls, @"reinstalls",
4909 upgrades, @"upgrades",
4910 downgrades, @"downgrades",
4911 removes, @"removes",
4914 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4915 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4916 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4919 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4923 - (UIBarButtonItem *) leftButton {
4924 return [[[UIBarButtonItem alloc]
4925 initWithTitle:UCLocalize("CANCEL")
4926 style:UIBarButtonItemStylePlain
4928 action:@selector(cancelButtonClicked)
4933 - (void) applyRightButton {
4934 if ([issues_ count] == 0 && ![self isLoading])
4935 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4936 initWithTitle:UCLocalize("CONFIRM")
4937 style:UIBarButtonItemStyleDone
4939 action:@selector(confirmButtonClicked)
4942 [[self navigationItem] setRightBarButtonItem:nil];
4946 - (void) cancelButtonClicked {
4947 [self dismissModalViewControllerAnimated:YES];
4948 [delegate_ cancelAndClear:YES];
4952 - (void) confirmButtonClicked {
4953 if (essential_ != nil)
4963 /* Progress Data {{{ */
4964 @interface CydiaProgressData : NSObject {
4965 _transient id delegate_;
4974 _H<NSMutableArray> events_;
4975 _H<NSString> title_;
4977 _H<NSString> status_;
4978 _H<NSString> finish_;
4983 @implementation CydiaProgressData
4985 + (NSArray *) _attributeKeys {
4986 return [NSArray arrayWithObjects:
4998 - (NSArray *) attributeKeys {
4999 return [[self class] _attributeKeys];
5002 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5003 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5007 if ((self = [super init]) != nil) {
5008 events_ = [NSMutableArray arrayWithCapacity:32];
5012 - (void) setDelegate:(id)delegate {
5013 delegate_ = delegate;
5016 - (void) setPercent:(float)value {
5020 - (NSNumber *) percent {
5021 return [NSNumber numberWithFloat:percent_];
5024 - (void) setCurrent:(float)value {
5028 - (NSNumber *) current {
5029 return [NSNumber numberWithFloat:current_];
5032 - (void) setTotal:(float)value {
5036 - (NSNumber *) total {
5037 return [NSNumber numberWithFloat:total_];
5040 - (void) setSpeed:(float)value {
5044 - (NSNumber *) speed {
5045 return [NSNumber numberWithFloat:speed_];
5048 - (NSArray *) events {
5052 - (void) removeAllEvents {
5053 [events_ removeAllObjects];
5056 - (void) addEvent:(CydiaProgressEvent *)event {
5057 [events_ addObject:event];
5060 - (void) setTitle:(NSString *)text {
5064 - (NSString *) title {
5068 - (void) setFinish:(NSString *)text {
5072 - (NSString *) finish {
5073 return (id) finish_ ?: [NSNull null];
5076 - (void) setRunning:(bool)running {
5080 - (NSNumber *) running {
5081 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5086 /* Progress Controller {{{ */
5087 @interface ProgressController : CydiaWebViewController <
5090 _transient Database *database_;
5091 _H<CydiaProgressData, 1> progress_;
5095 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5097 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5099 - (void) setTitle:(NSString *)title;
5100 - (void) setCancellable:(bool)cancellable;
5104 @implementation ProgressController
5107 [database_ setProgressDelegate:nil];
5111 - (UIBarButtonItem *) leftButton {
5112 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5113 initWithTitle:UCLocalize("CANCEL")
5114 style:UIBarButtonItemStylePlain
5116 action:@selector(cancel)
5117 ] autorelease] : nil;
5120 - (void) updateCancel {
5121 [super applyLeftButton];
5124 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5125 if ((self = [super init]) != nil) {
5126 database_ = database;
5127 delegate_ = delegate;
5129 [database_ setProgressDelegate:self];
5131 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5132 [progress_ setDelegate:self];
5134 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5136 [scroller_ setBackgroundColor:[UIColor blackColor]];
5138 [[self navigationItem] setHidesBackButton:YES];
5140 [self updateCancel];
5144 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5145 [super webView:view didClearWindowObject:window forFrame:frame];
5146 [window setValue:progress_ forKey:@"cydiaProgress"];
5149 - (void) updateProgress {
5150 [self dispatchEvent:@"CydiaProgressUpdate"];
5153 - (void) viewWillAppear:(BOOL)animated {
5154 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5155 [super viewWillAppear:animated];
5159 UpdateExternalStatus(0);
5162 [delegate_ saveState];
5166 [delegate_ returnToCydia];
5170 [delegate_ terminateWithSuccess];
5171 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5172 [delegate_ suspendWithAnimation:YES];
5174 [delegate_ suspend];*/
5186 system("/usr/bin/sbreload");
5192 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5193 SBReboot(SBSSpringBoardServerPort());
5195 reboot2(RB_AUTOBOOT);
5202 - (void) setTitle:(NSString *)title {
5203 [progress_ setTitle:title];
5204 [self updateProgress];
5207 - (UIBarButtonItem *) rightButton {
5208 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5209 initWithTitle:UCLocalize("CLOSE")
5210 style:UIBarButtonItemStylePlain
5212 action:@selector(close)
5216 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5217 UpdateExternalStatus(1);
5219 [progress_ setRunning:true];
5220 [self setTitle:title];
5221 // implicit updateProgress
5223 SHA1SumValue notifyconf; {
5225 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5228 MMap mmap(file, MMap::ReadOnly);
5230 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5231 notifyconf = sha1.Result();
5235 SHA1SumValue springlist; {
5237 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5240 MMap mmap(file, MMap::ReadOnly);
5242 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5243 springlist = sha1.Result();
5247 if (invocation != nil) {
5248 [invocation yieldToSelector:@selector(invoke)];
5249 [self setTitle:@"COMPLETE"];
5254 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5257 MMap mmap(file, MMap::ReadOnly);
5259 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5260 if (!(notifyconf == sha1.Result()))
5267 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5270 MMap mmap(file, MMap::ReadOnly);
5272 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5273 if (!(springlist == sha1.Result()))
5279 if (RestartSubstrate_)
5283 RestartSubstrate_ = false;
5286 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5287 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5288 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5289 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5290 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5294 system("su -c /usr/bin/uicache mobile");
5297 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5299 [progress_ setRunning:false];
5300 [self updateProgress];
5302 [self applyRightButton];
5305 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5306 [progress_ addEvent:event];
5307 [self updateProgress];
5310 - (bool) isProgressCancelled {
5311 return cancel_ == 2;
5316 [self updateCancel];
5319 - (void) setCancellable:(bool)cancellable {
5320 unsigned cancel(cancel_);
5324 else if (cancel_ == 0)
5327 if (cancel != cancel_)
5328 [self updateCancel];
5331 - (void) setProgressCancellable:(NSNumber *)cancellable {
5332 [self setCancellable:[cancellable boolValue]];
5335 - (void) setProgressPercent:(NSNumber *)percent {
5336 [progress_ setPercent:[percent floatValue]];
5337 [self updateProgress];
5340 - (void) setProgressStatus:(NSDictionary *)status {
5341 if (status == nil) {
5342 [progress_ setCurrent:0];
5343 [progress_ setTotal:0];
5344 [progress_ setSpeed:0];
5346 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5348 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5349 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5350 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5353 [self updateProgress];
5359 /* Package Cell {{{ */
5360 @interface PackageCell : CyteTableViewCell <
5361 CyteTableViewCellDelegate
5365 _H<NSString> description_;
5367 _H<NSString> source_;
5369 _H<UIImage> placard_;
5373 - (PackageCell *) init;
5374 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5376 - (void) drawContentRect:(CGRect)rect;
5380 @implementation PackageCell
5382 - (PackageCell *) init {
5383 CGRect frame(CGRectMake(0, 0, 320, 74));
5384 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5385 UIView *content([self contentView]);
5386 CGRect bounds([content bounds]);
5388 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5389 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5390 [content addSubview:content_];
5392 [content_ setDelegate:self];
5393 [content_ setOpaque:YES];
5397 - (NSString *) accessibilityLabel {
5398 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5401 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5402 summarized_ = summary;
5412 [content_ setBackgroundColor:[UIColor whiteColor]];
5416 Source *source = [package source];
5418 icon_ = [package icon];
5420 if (NSString *name = [package name])
5421 name_ = [NSString stringWithString:name];
5423 NSString *description(nil);
5425 if (description == nil && IsWildcat_)
5426 description = [package longDescription];
5427 if (description == nil)
5428 description = [package shortDescription];
5430 if (description != nil)
5431 description_ = [NSString stringWithString:description];
5433 commercial_ = [package isCommercial];
5435 NSString *label = nil;
5436 bool trusted = false;
5438 if (source != nil) {
5439 label = [source label];
5440 trusted = [source trusted];
5441 } else if ([[package id] isEqualToString:@"firmware"])
5442 label = UCLocalize("APPLE");
5444 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5446 NSString *from(label);
5448 NSString *section = [package simpleSection];
5449 if (section != nil && ![section isEqualToString:label]) {
5450 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5451 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5454 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5456 if (NSString *purpose = [package primaryPurpose])
5457 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5462 if (NSString *mode = [package mode]) {
5463 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5464 color = RemovingColor_;
5465 //placard = @"removing";
5467 color = InstallingColor_;
5468 //placard = @"installing";
5471 // XXX: the removing/installing placards are not @2x
5474 color = [UIColor whiteColor];
5476 if ([package installed] != nil)
5477 placard = @"installed";
5482 [content_ setBackgroundColor:color];
5485 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5488 [self setNeedsDisplay];
5489 [content_ setNeedsDisplay];
5492 - (void) drawSummaryContentRect:(CGRect)rect {
5493 bool highlighted(highlighted_);
5494 float width([self bounds].size.width);
5498 rect.size = [(UIImage *) icon_ size];
5500 rect.size.width /= 4;
5501 rect.size.height /= 4;
5503 rect.origin.x = 14 - rect.size.width / 4;
5504 rect.origin.y = 14 - rect.size.height / 4;
5506 [icon_ drawInRect:rect];
5509 if (badge_ != nil) {
5511 rect.size = [(UIImage *) badge_ size];
5513 rect.size.width /= 4;
5514 rect.size.height /= 4;
5516 rect.origin.x = 20 - rect.size.width / 4;
5517 rect.origin.y = 20 - rect.size.height / 4;
5519 [badge_ drawInRect:rect];
5526 UISetColor(commercial_ ? Purple_ : Black_);
5527 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5529 if (placard_ != nil)
5530 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5533 - (void) drawNormalContentRect:(CGRect)rect {
5534 bool highlighted(highlighted_);
5535 float width([self bounds].size.width);
5539 rect.size = [(UIImage *) icon_ size];
5541 rect.size.width /= 2;
5542 rect.size.height /= 2;
5544 rect.origin.x = 25 - rect.size.width / 2;
5545 rect.origin.y = 25 - rect.size.height / 2;
5547 [icon_ drawInRect:rect];
5550 if (badge_ != nil) {
5552 rect.size = [(UIImage *) badge_ size];
5554 rect.size.width /= 2;
5555 rect.size.height /= 2;
5557 rect.origin.x = 36 - rect.size.width / 2;
5558 rect.origin.y = 36 - rect.size.height / 2;
5560 [badge_ drawInRect:rect];
5567 UISetColor(commercial_ ? Purple_ : Black_);
5568 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5569 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5572 UISetColor(commercial_ ? Purplish_ : Gray_);
5573 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5575 if (placard_ != nil)
5576 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5579 - (void) drawContentRect:(CGRect)rect {
5581 [self drawSummaryContentRect:rect];
5583 [self drawNormalContentRect:rect];
5588 /* Section Cell {{{ */
5589 @interface SectionCell : CyteTableViewCell <
5590 CyteTableViewCellDelegate
5592 _H<NSString> basic_;
5593 _H<NSString> section_;
5595 _H<NSString> count_;
5597 _H<UISwitch> switch_;
5601 - (void) setSection:(Section *)section editing:(BOOL)editing;
5605 @implementation SectionCell
5607 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5608 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5609 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5610 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5611 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5613 UIView *content([self contentView]);
5614 CGRect bounds([content bounds]);
5616 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5617 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5618 [content addSubview:content_];
5619 [content_ setBackgroundColor:[UIColor whiteColor]];
5621 [content_ setDelegate:self];
5625 - (void) onSwitch:(id)sender {
5626 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5627 if (metadata == nil) {
5628 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5629 [Sections_ setObject:metadata forKey:basic_];
5632 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5636 - (void) setSection:(Section *)section editing:(BOOL)editing {
5637 if (editing != editing_) {
5639 [switch_ removeFromSuperview];
5641 [self addSubview:switch_];
5650 if (section == nil) {
5651 name_ = UCLocalize("ALL_PACKAGES");
5654 basic_ = [section name];
5655 section_ = [section localized];
5657 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5658 count_ = [NSString stringWithFormat:@"%d", [section count]];
5661 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5664 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5665 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5667 [content_ setNeedsDisplay];
5670 - (void) setFrame:(CGRect)frame {
5671 [super setFrame:frame];
5673 CGRect rect([switch_ frame]);
5674 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5677 - (NSString *) accessibilityLabel {
5681 - (void) drawContentRect:(CGRect)rect {
5682 bool highlighted(highlighted_ && !editing_);
5684 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5689 float width(rect.size.width);
5695 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5697 CGSize size = [count_ sizeWithFont:Font14_];
5701 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5707 /* File Table {{{ */
5708 @interface FileTable : CyteViewController <
5709 UITableViewDataSource,
5712 _transient Database *database_;
5713 _H<Package> package_;
5715 _H<NSMutableArray> files_;
5716 _H<UITableView, 2> list_;
5719 - (id) initWithDatabase:(Database *)database;
5720 - (void) setPackage:(Package *)package;
5724 @implementation FileTable
5726 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5727 return files_ == nil ? 0 : [files_ count];
5730 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5734 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5735 static NSString *reuseIdentifier = @"Cell";
5737 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5739 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5740 [cell setFont:[UIFont systemFontOfSize:16]];
5742 [cell setText:[files_ objectAtIndex:indexPath.row]];
5743 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5748 - (NSURL *) navigationURL {
5749 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5753 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5755 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5756 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5757 [list_ setRowHeight:24.0f];
5758 [(UITableView *) list_ setDataSource:self];
5759 [list_ setDelegate:self];
5760 [[self view] addSubview:list_];
5763 - (void) viewDidLoad {
5764 [super viewDidLoad];
5766 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5769 - (void) releaseSubviews {
5775 [super releaseSubviews];
5778 - (id) initWithDatabase:(Database *)database {
5779 if ((self = [super init]) != nil) {
5780 database_ = database;
5784 - (void) setPackage:(Package *)package {
5788 files_ = [NSMutableArray arrayWithCapacity:32];
5790 if (package != nil) {
5792 name_ = [package id];
5794 if (NSArray *files = [package files])
5795 [files_ addObjectsFromArray:files];
5797 if ([files_ count] != 0) {
5798 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5799 [files_ removeObjectAtIndex:0];
5800 [files_ sortUsingSelector:@selector(compareByPath:)];
5802 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5803 [stack addObject:@"/"];
5805 for (int i(0), e([files_ count]); i != e; ++i) {
5806 NSString *file = [files_ objectAtIndex:i];
5807 while (![file hasPrefix:[stack lastObject]])
5808 [stack removeLastObject];
5809 NSString *directory = [stack lastObject];
5810 [stack addObject:[file stringByAppendingString:@"/"]];
5811 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5812 ([stack count] - 2) * 3, "",
5813 [file substringFromIndex:[directory length]]
5822 - (void) reloadData {
5825 [self setPackage:[database_ packageWithName:name_]];
5830 /* Package Controller {{{ */
5831 @interface CYPackageController : CydiaWebViewController <
5832 UIActionSheetDelegate
5834 _transient Database *database_;
5835 _H<Package> package_;
5838 _H<NSMutableArray> buttons_;
5839 _H<UIBarButtonItem> button_;
5842 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5846 @implementation CYPackageController
5848 - (NSURL *) navigationURL {
5849 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5852 /* XXX: this is not safe at all... localization of /fail/ */
5853 - (void) _clickButtonWithName:(NSString *)name {
5854 if ([name isEqualToString:UCLocalize("CLEAR")])
5855 [delegate_ clearPackage:package_];
5856 else if ([name isEqualToString:UCLocalize("INSTALL")])
5857 [delegate_ installPackage:package_];
5858 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5859 [delegate_ installPackage:package_];
5860 else if ([name isEqualToString:UCLocalize("REMOVE")])
5861 [delegate_ removePackage:package_];
5862 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5863 [delegate_ installPackage:package_];
5864 else _assert(false);
5867 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5868 NSString *context([sheet context]);
5870 if ([context isEqualToString:@"modify"]) {
5871 if (button != [sheet cancelButtonIndex]) {
5872 NSString *buttonName = [buttons_ objectAtIndex:button];
5873 [self _clickButtonWithName:buttonName];
5876 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5880 - (bool) _allowJavaScriptPanel {
5885 - (void) _customButtonClicked {
5886 int count([buttons_ count]);
5891 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5893 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5894 [buttons addObjectsFromArray:buttons_];
5896 UIActionSheet *sheet = [[[UIActionSheet alloc]
5899 cancelButtonTitle:nil
5900 destructiveButtonTitle:nil
5901 otherButtonTitles:nil
5904 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5906 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5907 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5909 [sheet setContext:@"modify"];
5911 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5915 // We don't want to allow non-commercial packages to do custom things to the install button,
5916 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5917 - (void) customButtonClicked {
5919 [super customButtonClicked];
5921 [self _customButtonClicked];
5924 - (void) reloadButtonClicked {
5925 // Don't reload a commerical package by tapping the loading button,
5926 // but if it's not an Install button, we should forward it on.
5927 if (![package_ uninstalled])
5928 [self _customButtonClicked];
5931 - (void) applyLoadingTitle {
5932 // Don't show "Loading" as the title. Ever.
5935 - (UIBarButtonItem *) rightButton {
5940 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5941 if ((self = [super init]) != nil) {
5942 database_ = database;
5943 buttons_ = [NSMutableArray arrayWithCapacity:4];
5944 name_ = name == nil ? @"" : [NSString stringWithString:name];
5945 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5949 - (void) reloadData {
5952 package_ = [database_ packageWithName:name_];
5954 [buttons_ removeAllObjects];
5956 if (package_ != nil) {
5957 [(Package *) package_ parse];
5959 commercial_ = [package_ isCommercial];
5961 if ([package_ mode] != nil)
5962 [buttons_ addObject:UCLocalize("CLEAR")];
5963 if ([package_ source] == nil);
5964 else if ([package_ upgradableAndEssential:NO])
5965 [buttons_ addObject:UCLocalize("UPGRADE")];
5966 else if ([package_ uninstalled])
5967 [buttons_ addObject:UCLocalize("INSTALL")];
5969 [buttons_ addObject:UCLocalize("REINSTALL")];
5970 if (![package_ uninstalled])
5971 [buttons_ addObject:UCLocalize("REMOVE")];
5975 switch ([buttons_ count]) {
5976 case 0: title = nil; break;
5977 case 1: title = [buttons_ objectAtIndex:0]; break;
5978 default: title = UCLocalize("MODIFY"); break;
5981 button_ = [[[UIBarButtonItem alloc]
5983 style:UIBarButtonItemStylePlain
5985 action:@selector(customButtonClicked)
5989 - (bool) isLoading {
5990 return commercial_ ? [super isLoading] : false;
5996 /* Package List Controller {{{ */
5997 @interface PackageListController : CyteViewController <
5998 UITableViewDataSource,
6001 _transient Database *database_;
6003 _H<NSArray> packages_;
6004 _H<NSMutableArray> sections_;
6005 _H<UITableView, 2> list_;
6006 _H<NSMutableArray> index_;
6007 _H<NSMutableDictionary> indices_;
6008 _H<NSString> title_;
6009 unsigned reloading_;
6012 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6013 - (void) setDelegate:(id)delegate;
6014 - (void) resetCursor;
6019 @implementation PackageListController
6021 - (bool) isSummarized {
6025 - (bool) showsSections {
6029 - (void) deselectWithAnimation:(BOOL)animated {
6030 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6033 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6034 CGRect base = [[self view] bounds];
6035 base.size.height -= bounds.size.height;
6036 base.origin = [list_ frame].origin;
6038 [UIView beginAnimations:nil context:NULL];
6039 [UIView setAnimationBeginsFromCurrentState:YES];
6040 [UIView setAnimationCurve:curve];
6041 [UIView setAnimationDuration:duration];
6042 [list_ setFrame:base];
6043 [UIView commitAnimations];
6046 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6047 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6050 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6051 [self resizeForKeyboardBounds:bounds duration:0];
6054 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6055 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6056 *curve = UIViewAnimationCurveEaseInOut;
6058 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6060 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6063 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6066 - (void) keyboardWillShow:(NSNotification *)notification {
6069 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6070 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6072 NSTimeInterval duration;
6073 UIViewAnimationCurve curve;
6074 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6076 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);
6077 UIViewController *base = self;
6078 while ([base parentViewController] != nil)
6079 base = [base parentViewController];
6080 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6081 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6083 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6084 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6086 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6089 - (void) keyboardWillHide:(NSNotification *)notification {
6090 NSTimeInterval duration;
6091 UIViewAnimationCurve curve;
6092 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6094 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6097 - (void) viewWillAppear:(BOOL)animated {
6098 [super viewWillAppear:animated];
6100 [self resizeForKeyboardBounds:CGRectZero];
6101 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6102 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6105 - (void) viewWillDisappear:(BOOL)animated {
6106 [super viewWillDisappear:animated];
6108 [self resizeForKeyboardBounds:CGRectZero];
6109 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6110 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6113 - (void) viewDidAppear:(BOOL)animated {
6114 [super viewDidAppear:animated];
6115 [self deselectWithAnimation:animated];
6118 - (void) didSelectPackage:(Package *)package {
6119 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6120 [view setDelegate:delegate_];
6121 [[self navigationController] pushViewController:view animated:YES];
6124 #if TryIndexedCollation
6125 + (BOOL) hasIndexedCollation {
6126 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6130 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6131 NSInteger count([sections_ count]);
6132 return count == 0 ? 1 : count;
6135 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6136 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6138 return [[sections_ objectAtIndex:section] name];
6141 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6142 if ([sections_ count] == 0)
6144 return [[sections_ objectAtIndex:section] count];
6147 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6148 @synchronized (database_) {
6149 if ([database_ era] != era_)
6152 Section *section([sections_ objectAtIndex:[path section]]);
6153 NSInteger row([path row]);
6154 Package *package([packages_ objectAtIndex:([section row] + row)]);
6155 return [[package retain] autorelease];
6158 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6159 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6161 cell = [[[PackageCell alloc] init] autorelease];
6163 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6164 [cell setPackage:package asSummary:[self isSummarized]];
6168 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6169 Package *package([self packageAtIndexPath:path]);
6170 package = [database_ packageWithName:[package id]];
6171 [self didSelectPackage:package];
6174 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6175 if (![self showsSections])
6181 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6182 #if TryIndexedCollation
6183 if ([[self class] hasIndexedCollation]) {
6184 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6191 - (void) updateHeight {
6192 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6195 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6196 if ((self = [super init]) != nil) {
6197 database_ = database;
6198 title_ = [title copy];
6199 [[self navigationItem] setTitle:title_];
6204 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6206 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6207 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6208 [[self view] addSubview:list_];
6210 // XXX: is 20 the most optimal number here?
6211 [list_ setSectionIndexMinimumDisplayRowCount:20];
6213 [(UITableView *) list_ setDataSource:self];
6214 [list_ setDelegate:self];
6216 [self updateHeight];
6219 - (void) releaseSubviews {
6227 [super releaseSubviews];
6230 - (void) setDelegate:(id)delegate {
6231 delegate_ = delegate;
6234 - (bool) shouldYield {
6238 - (bool) shouldBlock {
6242 - (NSMutableArray *) _reloadPackages {
6243 @synchronized (database_) {
6244 era_ = [database_ era];
6245 NSArray *packages([database_ packages]);
6247 return [NSMutableArray arrayWithArray:packages];
6250 - (void) _reloadData {
6251 if (reloading_ != 0) {
6258 if ([self shouldYield]) {
6262 if (![self shouldBlock])
6265 hud = [delegate_ addProgressHUD];
6266 [hud setText:UCLocalize("LOADING")];
6270 packages = [self yieldToSelector:@selector(_reloadPackages)];
6273 [delegate_ removeProgressHUD:hud];
6274 } while (reloading_ == 2);
6278 packages = [self _reloadPackages];
6281 packages_ = packages;
6283 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6284 sections_ = [NSMutableArray arrayWithCapacity:16];
6286 Section *section = nil;
6288 #if TryIndexedCollation
6289 if ([[self class] hasIndexedCollation]) {
6290 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6292 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6293 NSArray *titles = [collation sectionIndexTitles];
6296 _profile(PackageTable$reloadData$Section)
6297 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6301 _profile(PackageTable$reloadData$Section$Package)
6302 package = [packages_ objectAtIndex:offset];
6303 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6306 while (secidx < index) {
6309 _profile(PackageTable$reloadData$Section$Allocate)
6310 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6313 _profile(PackageTable$reloadData$Section$Add)
6314 [sections_ addObject:section];
6318 [section addToCount];
6324 index_ = [NSMutableArray arrayWithCapacity:32];
6326 bool sectioned([self showsSections]);
6328 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6329 [sections_ addObject:section];
6332 _profile(PackageTable$reloadData$Section)
6333 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6337 _profile(PackageTable$reloadData$Section$Package)
6338 package = [packages_ objectAtIndex:offset];
6339 index = [package index];
6342 if (sectioned && (section == nil || [section index] != index)) {
6343 _profile(PackageTable$reloadData$Section$Allocate)
6344 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6347 [index_ addObject:[section name]];
6348 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6350 _profile(PackageTable$reloadData$Section$Add)
6351 [sections_ addObject:section];
6355 [section addToCount];
6360 [self updateHeight];
6362 _profile(PackageTable$reloadData$List)
6363 [(UITableView *) list_ setDataSource:self];
6368 - (void) reloadData {
6371 if ([self shouldYield])
6372 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6377 - (void) resetCursor {
6378 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6381 - (void) clearData {
6382 [self updateHeight];
6384 [list_ setDataSource:nil];
6392 /* Filtered Package List Controller {{{ */
6393 @interface FilteredPackageListController : PackageListController {
6396 _H<NSObject> object_;
6399 - (void) setObject:(id)object;
6400 - (void) setObject:(id)object forFilter:(SEL)filter;
6403 - (void) setFilter:(SEL)filter;
6405 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6409 @implementation FilteredPackageListController
6415 - (void) setFilter:(SEL)filter {
6416 @synchronized (self) {
6419 /* XXX: this is an unsafe optimization of doomy hell */
6420 Method method(class_getInstanceMethod([Package class], filter));
6421 _assert(method != NULL);
6422 imp_ = method_getImplementation(method);
6423 _assert(imp_ != NULL);
6426 - (void) setObject:(id)object {
6427 @synchronized (self) {
6431 - (void) setObject:(id)object forFilter:(SEL)filter {
6432 @synchronized (self) {
6433 [self setFilter:filter];
6434 [self setObject:object];
6437 - (NSMutableArray *) _reloadPackages {
6438 @synchronized (database_) {
6439 era_ = [database_ era];
6440 NSArray *packages([database_ packages]);
6442 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6446 _H<NSObject> object;
6448 @synchronized (self) {
6454 _profile(PackageTable$reloadData$Filter)
6455 for (Package *package in packages)
6456 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6457 [filtered addObject:package];
6463 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6464 if ((self = [super initWithDatabase:database title:title]) != nil) {
6465 [self setFilter:filter];
6466 [self setObject:object];
6473 /* Home Controller {{{ */
6474 @interface HomeController : CydiaWebViewController {
6479 @implementation HomeController
6482 if ((self = [super init]) != nil) {
6483 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6488 - (NSURL *) navigationURL {
6489 return [NSURL URLWithString:@"cydia://home"];
6492 - (void) didReceiveMemoryWarning {
6495 - (void) aboutButtonClicked {
6496 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6498 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6499 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6500 [alert setCancelButtonIndex:0];
6503 @"Copyright \u00a9 2008-2011\n"
6506 "Jay Freeman (saurik)\n"
6507 "saurik@saurik.com\n"
6508 "http://www.saurik.com/"
6514 - (UIBarButtonItem *) leftButton {
6515 return [[[UIBarButtonItem alloc]
6516 initWithTitle:UCLocalize("ABOUT")
6517 style:UIBarButtonItemStylePlain
6519 action:@selector(aboutButtonClicked)
6525 /* Manage Controller {{{ */
6526 @interface ManageController : CydiaWebViewController {
6529 - (void) queueStatusDidChange;
6533 @implementation ManageController
6536 if ((self = [super init]) != nil) {
6537 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6541 - (NSURL *) navigationURL {
6542 return [NSURL URLWithString:@"cydia://manage"];
6545 - (UIBarButtonItem *) leftButton {
6546 return [[[UIBarButtonItem alloc]
6547 initWithTitle:UCLocalize("SETTINGS")
6548 style:UIBarButtonItemStylePlain
6550 action:@selector(settingsButtonClicked)
6554 - (void) settingsButtonClicked {
6555 [delegate_ showSettings];
6558 - (void) queueButtonClicked {
6562 - (UIBarButtonItem *) customButton {
6563 return Queuing_ ? [[[UIBarButtonItem alloc]
6564 initWithTitle:UCLocalize("QUEUE")
6565 style:UIBarButtonItemStyleDone
6567 action:@selector(queueButtonClicked)
6568 ] autorelease] : [super customButton];
6571 - (void) queueStatusDidChange {
6572 [self applyRightButton];
6575 - (bool) isLoading {
6576 return !Queuing_ && [super isLoading];
6582 /* Refresh Bar {{{ */
6583 @interface RefreshBar : UINavigationBar {
6584 _H<UIProgressIndicator> indicator_;
6585 _H<UITextLabel> prompt_;
6586 _H<UIProgressBar> progress_;
6587 _H<UINavigationButton> cancel_;
6592 @implementation RefreshBar
6594 - (void) positionViews {
6595 CGRect frame = [cancel_ frame];
6596 frame.size = [cancel_ sizeThatFits:frame.size];
6597 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6598 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6599 [cancel_ setFrame:frame];
6601 CGSize prgsize = {75, 100};
6603 [self frame].size.width - prgsize.width - 10,
6604 ([self frame].size.height - prgsize.height) / 2
6606 [progress_ setFrame:prgrect];
6608 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6609 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6610 CGRect indrect = {{indoffset, indoffset}, indsize};
6611 [indicator_ setFrame:indrect];
6613 CGSize prmsize = {215, indsize.height + 4};
6615 indoffset * 2 + indsize.width,
6616 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6618 [prompt_ setFrame:prmrect];
6621 - (void) setFrame:(CGRect)frame {
6622 [super setFrame:frame];
6623 [self positionViews];
6626 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6627 if ((self = [super initWithFrame:frame]) != nil) {
6628 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6630 [self setBarStyle:UIBarStyleBlack];
6632 UIBarStyle barstyle([self _barStyle:NO]);
6633 bool ugly(barstyle == UIBarStyleDefault);
6635 UIProgressIndicatorStyle style = ugly ?
6636 UIProgressIndicatorStyleMediumBrown :
6637 UIProgressIndicatorStyleMediumWhite;
6639 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6640 [(UIProgressIndicator *) indicator_ setStyle:style];
6641 [indicator_ startAnimation];
6642 [self addSubview:indicator_];
6644 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6645 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6646 [prompt_ setBackgroundColor:[UIColor clearColor]];
6647 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6648 [self addSubview:prompt_];
6650 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6651 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6652 [(UIProgressBar *) progress_ setStyle:0];
6653 [self addSubview:progress_];
6655 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6656 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6657 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6658 [cancel_ setBarStyle:barstyle];
6660 [self positionViews];
6664 - (void) setCancellable:(bool)cancellable {
6666 [self addSubview:cancel_];
6668 [cancel_ removeFromSuperview];
6672 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6673 [progress_ setProgress:0];
6677 [self setCancellable:NO];
6680 - (void) setPrompt:(NSString *)prompt {
6681 [prompt_ setText:prompt];
6684 - (void) setProgress:(float)progress {
6685 [progress_ setProgress:progress];
6691 /* Cydia Navigation Controller Interface {{{ */
6692 @interface UINavigationController (Cydia)
6694 - (NSArray *) navigationURLCollection;
6695 - (void) unloadData;
6700 /* Cydia Tab Bar Controller {{{ */
6701 @interface CYTabBarController : UITabBarController <
6702 UITabBarControllerDelegate,
6705 _transient Database *database_;
6706 _H<RefreshBar, 1> refreshbar_;
6710 // XXX: ok, "updatedelegate_"?...
6711 _transient NSObject<CydiaDelegate> *updatedelegate_;
6713 _H<UIViewController> remembered_;
6714 _transient UIViewController *transient_;
6717 - (NSArray *) navigationURLCollection;
6718 - (void) dropBar:(BOOL)animated;
6719 - (void) beginUpdate;
6720 - (void) raiseBar:(BOOL)animated;
6722 - (void) unloadData;
6726 @implementation CYTabBarController
6728 - (void) setUnselectedViewController:(UIViewController *)transient {
6729 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6730 if (transient != nil) {
6731 if (transient_ == nil)
6732 remembered_ = [controllers objectAtIndex:0];
6733 transient_ = transient;
6734 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6735 [controllers replaceObjectAtIndex:0 withObject:transient_];
6736 [self setSelectedIndex:0];
6737 [self setViewControllers:controllers];
6738 [self concealTabBarSelection];
6739 } else if (remembered_ != nil) {
6740 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6741 transient_ = transient;
6742 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6744 [self setViewControllers:controllers];
6745 [self revealTabBarSelection];
6749 - (UIViewController *) unselectedViewController {
6753 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6754 if ([self unselectedViewController])
6755 [self setUnselectedViewController:nil];
6758 - (NSArray *) navigationURLCollection {
6759 NSMutableArray *items([NSMutableArray array]);
6761 // XXX: Should this deal with transient view controllers?
6762 for (id navigation in [self viewControllers]) {
6763 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6765 [items addObject:stack];
6771 - (void) unloadData {
6774 for (UINavigationController *controller in [self viewControllers])
6775 [controller unloadData];
6777 if (UIViewController *selected = [self selectedViewController])
6778 [selected reloadData];
6780 if (UIViewController *unselected = [self unselectedViewController]) {
6781 [unselected unloadData];
6782 [unselected reloadData];
6787 [[NSNotificationCenter defaultCenter] removeObserver:self];
6792 - (id) initWithDatabase:(Database *)database {
6793 if ((self = [super init]) != nil) {
6794 database_ = database;
6795 [self setDelegate:self];
6797 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6798 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6800 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6804 - (void) setUpdate:(NSDate *)date {
6808 - (void) beginUpdate {
6809 [(RefreshBar *) refreshbar_ start];
6812 [updatedelegate_ retainNetworkActivityIndicator];
6816 detachNewThreadSelector:@selector(performUpdate)
6822 - (void) performUpdate {
6823 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6826 status.setDelegate(self);
6827 [database_ updateWithStatus:status];
6830 performSelectorOnMainThread:@selector(completeUpdate)
6838 - (void) stopUpdateWithSelector:(SEL)selector {
6840 [updatedelegate_ releaseNetworkActivityIndicator];
6842 [self raiseBar:YES];
6845 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6848 - (void) completeUpdate {
6851 [self stopUpdateWithSelector:@selector(reloadData)];
6854 - (void) cancelUpdate {
6855 [self stopUpdateWithSelector:@selector(updateData)];
6858 - (void) cancelPressed {
6859 [self cancelUpdate];
6866 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6867 [refreshbar_ setPrompt:[event compoundMessage]];
6870 - (bool) isProgressCancelled {
6874 - (void) setProgressCancellable:(NSNumber *)cancellable {
6875 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6878 - (void) setProgressPercent:(NSNumber *)percent {
6879 [refreshbar_ setProgress:[percent floatValue]];
6882 - (void) setProgressStatus:(NSDictionary *)status {
6884 [self setProgressPercent:[status objectForKey:@"Percent"]];
6887 - (void) setUpdateDelegate:(id)delegate {
6888 updatedelegate_ = delegate;
6891 - (UIView *) transitionView {
6892 if ([self respondsToSelector:@selector(_transitionView)])
6893 return [self _transitionView];
6895 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6898 - (void) dropBar:(BOOL)animated {
6903 UIView *transition([self transitionView]);
6904 [[self view] addSubview:refreshbar_];
6906 CGRect barframe([refreshbar_ frame]);
6908 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6909 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6911 barframe.origin.y = 0;
6913 [refreshbar_ setFrame:barframe];
6916 [UIView beginAnimations:nil context:NULL];
6918 CGRect viewframe = [transition frame];
6919 viewframe.origin.y += barframe.size.height;
6920 viewframe.size.height -= barframe.size.height;
6921 [transition setFrame:viewframe];
6924 [UIView commitAnimations];
6926 // Ensure bar has the proper width for our view, it might have changed
6927 barframe.size.width = viewframe.size.width;
6928 [refreshbar_ setFrame:barframe];
6931 - (void) raiseBar:(BOOL)animated {
6936 UIView *transition([self transitionView]);
6937 [refreshbar_ removeFromSuperview];
6939 CGRect barframe([refreshbar_ frame]);
6942 [UIView beginAnimations:nil context:NULL];
6944 CGRect viewframe = [transition frame];
6945 viewframe.origin.y -= barframe.size.height;
6946 viewframe.size.height += barframe.size.height;
6947 [transition setFrame:viewframe];
6950 [UIView commitAnimations];
6953 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6954 bool dropped(dropped_);
6959 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6965 - (void) statusBarFrameChanged:(NSNotification *)notification {
6975 /* Cydia Navigation Controller Implementation {{{ */
6976 @implementation UINavigationController (Cydia)
6978 - (NSArray *) navigationURLCollection {
6979 NSMutableArray *stack([NSMutableArray array]);
6981 for (CyteViewController *controller in [self viewControllers]) {
6982 NSString *url = [[controller navigationURL] absoluteString];
6984 [stack addObject:url];
6990 - (void) reloadData {
6993 UIViewController *visible([self visibleViewController]);
6995 [visible reloadData];
6997 // on the iPad, this view controller is ALSO visible. :(
6999 if (UIViewController *top = [self topViewController])
7004 - (void) unloadData {
7005 for (CyteViewController *page in [self viewControllers])
7014 /* Cydia:// Protocol {{{ */
7015 @interface CydiaURLProtocol : NSURLProtocol {
7020 @implementation CydiaURLProtocol
7022 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7023 NSURL *url([request URL]);
7027 NSString *scheme([[url scheme] lowercaseString]);
7028 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7030 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7036 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7040 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7041 id<NSURLProtocolClient> client([self client]);
7043 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7045 NSData *data(UIImagePNGRepresentation(icon));
7047 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7048 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7049 [client URLProtocol:self didLoadData:data];
7050 [client URLProtocolDidFinishLoading:self];
7054 - (void) startLoading {
7055 id<NSURLProtocolClient> client([self client]);
7056 NSURLRequest *request([self request]);
7058 NSURL *url([request URL]);
7059 NSString *href([url absoluteString]);
7060 NSString *scheme([[url scheme] lowercaseString]);
7064 if ([scheme isEqualToString:@"cydia"])
7065 path = [href substringFromIndex:8];
7066 else if ([scheme isEqualToString:@"about"])
7067 path = [href substringFromIndex:12];
7068 else _assert(false);
7070 NSRange slash([path rangeOfString:@"/"]);
7073 if (slash.location == NSNotFound) {
7077 command = [path substringToIndex:slash.location];
7078 path = [path substringFromIndex:(slash.location + 1)];
7081 Database *database([Database sharedInstance]);
7083 if ([command isEqualToString:@"package-icon"]) {
7086 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7087 Package *package([database packageWithName:path]);
7091 UIImage *icon([package icon]);
7092 [self _returnPNGWithImage:icon forRequest:request];
7093 } else if ([command isEqualToString:@"source-icon"]) {
7096 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7097 NSString *source(Simplify(path));
7098 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7100 icon = [UIImage applicationImageNamed:@"unknown.png"];
7101 [self _returnPNGWithImage:icon forRequest:request];
7102 } else if ([command isEqualToString:@"uikit-image"]) {
7105 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7106 UIImage *icon(_UIImageWithName(path));
7107 [self _returnPNGWithImage:icon forRequest:request];
7108 } else if ([command isEqualToString:@"section-icon"]) {
7111 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7112 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7114 icon = [UIImage applicationImageNamed:@"unknown.png"];
7115 [self _returnPNGWithImage:icon forRequest:request];
7117 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7121 - (void) stopLoading {
7127 /* Section Controller {{{ */
7128 @interface SectionController : FilteredPackageListController {
7129 _H<NSString> section_;
7132 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7136 @implementation SectionController
7138 - (NSURL *) navigationURL {
7139 NSString *name = section_;
7143 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7146 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7149 title = UCLocalize("ALL_PACKAGES");
7150 else if (![name isEqual:@""])
7151 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7153 title = UCLocalize("NO_SECTION");
7155 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7162 /* Sections Controller {{{ */
7163 @interface SectionsController : CyteViewController <
7164 UITableViewDataSource,
7167 _transient Database *database_;
7168 _H<NSMutableArray> sections_;
7169 _H<NSMutableArray> filtered_;
7170 _H<UITableView, 2> list_;
7173 - (id) initWithDatabase:(Database *)database;
7174 - (void) editButtonClicked;
7178 @implementation SectionsController
7180 - (NSURL *) navigationURL {
7181 return [NSURL URLWithString:@"cydia://sections"];
7184 - (void) updateNavigationItem {
7185 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7186 if ([sections_ count] == 0) {
7187 [[self navigationItem] setRightBarButtonItem:nil];
7189 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7190 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7192 action:@selector(editButtonClicked)
7193 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7197 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7198 [super setEditing:editing animated:animated];
7203 [delegate_ updateData];
7205 [self updateNavigationItem];
7208 - (void) viewDidAppear:(BOOL)animated {
7209 [super viewDidAppear:animated];
7210 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7213 - (void) viewWillDisappear:(BOOL)animated {
7214 [super viewWillDisappear:animated];
7215 if ([self isEditing]) [self setEditing:NO];
7218 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7219 Section *section = nil;
7220 int index = [indexPath row];
7221 if (![self isEditing]) {
7224 section = [filtered_ objectAtIndex:index];
7226 section = [sections_ objectAtIndex:index];
7231 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7232 if ([self isEditing])
7233 return [sections_ count];
7235 return [filtered_ count] + 1;
7238 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7242 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7243 static NSString *reuseIdentifier = @"SectionCell";
7245 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7247 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7249 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7254 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7255 if ([self isEditing])
7258 Section *section = [self sectionAtIndexPath:indexPath];
7260 SectionController *controller = [[[SectionController alloc]
7261 initWithDatabase:database_
7262 section:[section name]
7264 [controller setDelegate:delegate_];
7266 [[self navigationController] pushViewController:controller animated:YES];
7270 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7272 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7273 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7274 [list_ setRowHeight:45.0f];
7275 [(UITableView *) list_ setDataSource:self];
7276 [list_ setDelegate:self];
7277 [[self view] addSubview:list_];
7280 - (void) viewDidLoad {
7281 [super viewDidLoad];
7283 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7286 - (void) releaseSubviews {
7292 [super releaseSubviews];
7295 - (id) initWithDatabase:(Database *)database {
7296 if ((self = [super init]) != nil) {
7297 database_ = database;
7301 - (void) reloadData {
7304 NSArray *packages = [database_ packages];
7306 sections_ = [NSMutableArray arrayWithCapacity:16];
7307 filtered_ = [NSMutableArray arrayWithCapacity:16];
7309 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7312 for (Package *package in packages) {
7313 NSString *name([package section]);
7314 NSString *key(name == nil ? @"" : name);
7318 _profile(SectionsView$reloadData$Section)
7319 section = [sections objectForKey:key];
7320 if (section == nil) {
7321 _profile(SectionsView$reloadData$Section$Allocate)
7322 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7323 [sections setObject:section forKey:key];
7328 [section addToCount];
7330 _profile(SectionsView$reloadData$Filter)
7331 if (![package valid] || ![package visible])
7339 [sections_ addObjectsFromArray:[sections allValues]];
7341 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7343 for (Section *section in (id) sections_) {
7344 size_t count([section row]);
7348 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7349 [section setCount:count];
7350 [filtered_ addObject:section];
7353 [self updateNavigationItem];
7358 - (void) editButtonClicked {
7359 [self setEditing:![self isEditing] animated:YES];
7365 /* Changes Controller {{{ */
7366 @interface ChangesController : CyteViewController <
7367 UITableViewDataSource,
7370 _transient Database *database_;
7372 _H<NSArray> packages_;
7373 _H<NSMutableArray> sections_;
7374 _H<UITableView, 2> list_;
7378 - (id) initWithDatabase:(Database *)database;
7382 @implementation ChangesController
7384 - (NSURL *) navigationURL {
7385 return [NSURL URLWithString:@"cydia://changes"];
7388 - (void) viewDidAppear:(BOOL)animated {
7389 [super viewDidAppear:animated];
7390 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7393 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7394 NSInteger count([sections_ count]);
7395 return count == 0 ? 1 : count;
7398 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7399 if ([sections_ count] == 0)
7401 return [[sections_ objectAtIndex:section] name];
7404 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7405 if ([sections_ count] == 0)
7407 return [[sections_ objectAtIndex:section] count];
7410 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7411 @synchronized (database_) {
7412 if ([database_ era] != era_)
7415 NSUInteger sectionIndex([path section]);
7416 if (sectionIndex >= [sections_ count])
7418 Section *section([sections_ objectAtIndex:sectionIndex]);
7419 NSInteger row([path row]);
7420 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7423 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7424 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7426 cell = [[[PackageCell alloc] init] autorelease];
7428 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7429 [cell setPackage:package asSummary:false];
7433 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7434 Package *package([self packageAtIndexPath:path]);
7435 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7436 [view setDelegate:delegate_];
7437 [[self navigationController] pushViewController:view animated:YES];
7441 - (void) refreshButtonClicked {
7442 [delegate_ beginUpdate];
7443 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7446 - (void) upgradeButtonClicked {
7447 [delegate_ distUpgrade];
7448 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7452 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7454 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7455 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7456 [list_ setRowHeight:73];
7457 [(UITableView *) list_ setDataSource:self];
7458 [list_ setDelegate:self];
7459 [[self view] addSubview:list_];
7462 - (void) viewDidLoad {
7463 [super viewDidLoad];
7465 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7468 - (void) releaseSubviews {
7474 [super releaseSubviews];
7477 - (id) initWithDatabase:(Database *)database {
7478 if ((self = [super init]) != nil) {
7479 database_ = database;
7483 - (NSMutableArray *) _reloadPackages {
7484 @synchronized (database_) {
7485 era_ = [database_ era];
7486 NSArray *packages([database_ packages]);
7488 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7491 _profile(ChangesController$_reloadPackages$Filter)
7492 for (Package *package in packages)
7493 if ([package upgradableAndEssential:YES] || [package visible])
7494 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7497 _profile(ChangesController$_reloadPackages$radixSort)
7498 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7505 - (void) _reloadData {
7510 UIProgressHUD *hud([delegate_ addProgressHUD]);
7511 [hud setText:UCLocalize("LOADING")];
7512 //NSLog(@"HUD:%@::%@", delegate_, hud);
7513 packages = [self yieldToSelector:@selector(_reloadPackages)];
7514 [delegate_ removeProgressHUD:hud];
7516 packages = [self _reloadPackages];
7519 @synchronized (database_) {
7520 if (era_ != [database_ era])
7523 packages_ = packages;
7524 sections_ = [NSMutableArray arrayWithCapacity:16];
7526 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7527 Section *ignored = nil;
7528 Section *section = nil;
7532 bool unseens = false;
7534 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7536 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7537 Package *package = [packages_ objectAtIndex:offset];
7539 BOOL uae = [package upgradableAndEssential:YES];
7543 time_t seen([package seen]);
7545 if (section == nil || last != seen) {
7549 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7552 _profile(ChangesController$reloadData$Allocate)
7553 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7554 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7555 [sections_ addObject:section];
7559 [section addToCount];
7560 } else if ([package ignored]) {
7561 if (ignored == nil) {
7562 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7564 [ignored addToCount];
7567 [upgradable addToCount];
7572 CFRelease(formatter);
7575 Section *last = [sections_ lastObject];
7576 size_t count = [last count];
7577 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7578 [sections_ removeLastObject];
7581 if ([ignored count] != 0)
7582 [sections_ insertObject:ignored atIndex:0];
7584 [sections_ insertObject:upgradable atIndex:0];
7588 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7589 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7590 style:UIBarButtonItemStylePlain
7592 action:@selector(upgradeButtonClicked)
7593 ] autorelease]) animated:YES];
7595 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7596 initWithTitle:UCLocalize("REFRESH")
7597 style:UIBarButtonItemStylePlain
7599 action:@selector(refreshButtonClicked)
7600 ] autorelease]) animated:YES];
7605 - (void) reloadData {
7607 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7612 /* Search Controller {{{ */
7613 @interface SearchController : FilteredPackageListController <
7616 _H<UISearchBar, 1> search_;
7620 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7621 - (void) reloadData;
7625 @implementation SearchController
7627 - (NSURL *) navigationURL {
7628 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7629 return [NSURL URLWithString:@"cydia://search"];
7631 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7634 - (void) useSearch {
7635 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7640 - (void) viewWillAppear:(BOOL)animated {
7641 [super viewWillAppear:animated];
7643 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7647 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7648 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7653 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7654 [search_ resignFirstResponder];
7658 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7659 [search_ setText:@""];
7660 [self searchBarButtonClicked:searchBar];
7663 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7664 [self searchBarButtonClicked:searchBar];
7667 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7668 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7672 - (bool) shouldYield {
7676 - (bool) shouldBlock {
7677 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7680 - (bool) isSummarized {
7681 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7684 - (bool) showsSections {
7688 - (NSMutableArray *) _reloadPackages {
7689 NSMutableArray *packages([super _reloadPackages]);
7690 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7691 [packages radixSortUsingSelector:@selector(rank)];
7695 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7696 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7697 search_ = [[[UISearchBar alloc] init] autorelease];
7698 [search_ setDelegate:self];
7701 [search_ setText:query];
7705 - (void) viewDidAppear:(BOOL)animated {
7706 [super viewDidAppear:animated];
7708 if (!searchloaded_) {
7709 searchloaded_ = YES;
7710 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7711 [search_ layoutSubviews];
7712 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7714 UITextField *textField;
7715 if ([search_ respondsToSelector:@selector(searchField)])
7716 textField = [search_ searchField];
7718 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7720 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7721 [textField setEnablesReturnKeyAutomatically:NO];
7722 [[self navigationItem] setTitleView:textField];
7726 - (void) reloadData {
7727 id object([search_ text]);
7728 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7729 object = [object componentsSeparatedByString:@" "];
7731 [self setObject:object];
7737 - (void) didSelectPackage:(Package *)package {
7738 [search_ resignFirstResponder];
7739 [super didSelectPackage:package];
7744 /* Package Settings Controller {{{ */
7745 @interface PackageSettingsController : CyteViewController <
7746 UITableViewDataSource,
7749 _transient Database *database_;
7751 _H<Package> package_;
7752 _H<UITableView, 2> table_;
7753 _H<UISwitch> subscribedSwitch_;
7754 _H<UISwitch> ignoredSwitch_;
7755 _H<UITableViewCell> subscribedCell_;
7756 _H<UITableViewCell> ignoredCell_;
7759 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7763 @implementation PackageSettingsController
7765 - (NSURL *) navigationURL {
7766 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7769 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7770 if (package_ == nil)
7773 if ([package_ installed] == nil)
7779 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7780 if (package_ == nil)
7783 // both sections contain just one item right now.
7787 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7791 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7793 return UCLocalize("SHOW_ALL_CHANGES_EX");
7795 return UCLocalize("IGNORE_UPGRADES_EX");
7798 - (void) onSubscribed:(id)control {
7799 bool value([control isOn]);
7800 if (package_ == nil)
7802 if ([package_ setSubscribed:value])
7803 [delegate_ updateData];
7806 - (void) _updateIgnored {
7807 const char *package([name_ UTF8String]);
7808 bool on([ignoredSwitch_ isOn]);
7810 pid_t pid(ExecFork());
7812 FILE *dpkg(popen("dpkg --set-selections", "w"));
7813 fwrite(package, strlen(package), 1, dpkg);
7816 fwrite(" hold\n", 6, 1, dpkg);
7818 fwrite(" install\n", 9, 1, dpkg);
7828 int result(waitpid(pid, &status, 0));
7831 _assert(result == pid);
7837 - (void) onIgnored:(id)control {
7838 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7839 [invocation setTarget:self];
7840 [invocation setSelector:@selector(_updateIgnored)];
7842 [delegate_ reloadDataWithInvocation:invocation];
7845 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7846 if (package_ == nil)
7849 switch ([indexPath section]) {
7850 case 0: return subscribedCell_;
7851 case 1: return ignoredCell_;
7860 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7862 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7863 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7864 [(UITableView *) table_ setDataSource:self];
7865 [table_ setDelegate:self];
7866 [[self view] addSubview:table_];
7868 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7869 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7870 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7872 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7873 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7874 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7876 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7877 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7878 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7879 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7881 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7882 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7883 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7884 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7887 - (void) viewDidLoad {
7888 [super viewDidLoad];
7890 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7893 - (void) releaseSubviews {
7895 subscribedCell_ = nil;
7897 ignoredSwitch_ = nil;
7898 subscribedSwitch_ = nil;
7900 [super releaseSubviews];
7903 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7904 if ((self = [super init]) != nil) {
7905 database_ = database;
7910 - (void) reloadData {
7913 package_ = [database_ packageWithName:name_];
7915 if (package_ != nil) {
7916 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7917 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7918 } // XXX: what now, G?
7920 [table_ reloadData];
7926 /* Installed Controller {{{ */
7927 @interface InstalledController : FilteredPackageListController {
7931 - (id) initWithDatabase:(Database *)database;
7933 - (void) updateRoleButton;
7934 - (void) queueStatusDidChange;
7938 @implementation InstalledController
7940 - (NSURL *) navigationURL {
7941 return [NSURL URLWithString:@"cydia://installed"];
7944 - (id) initWithDatabase:(Database *)database {
7945 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7946 [self updateRoleButton];
7947 [self queueStatusDidChange];
7952 - (void) queueButtonClicked {
7957 - (void) queueStatusDidChange {
7961 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7962 initWithTitle:UCLocalize("QUEUE")
7963 style:UIBarButtonItemStyleDone
7965 action:@selector(queueButtonClicked)
7968 [[self navigationItem] setLeftBarButtonItem:nil];
7974 - (void) updateRoleButton {
7975 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7976 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7977 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7978 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7980 action:@selector(roleButtonClicked)
7984 - (void) roleButtonClicked {
7985 [self setObject:[NSNumber numberWithBool:expert_]];
7989 [self updateRoleButton];
7995 /* Source Cell {{{ */
7996 @interface SourceCell : CyteTableViewCell <
7997 CyteTableViewCellDelegate
8000 _H<NSString> origin_;
8001 _H<NSString> label_;
8004 - (void) setSource:(Source *)source;
8008 @implementation SourceCell
8010 - (void) _setImage:(UIImage *)image {
8012 [content_ setNeedsDisplay];
8015 - (void) _setSource:(Source *)source {
8016 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8018 if (NSString *base = [source base])
8019 if ([base length] != 0) {
8020 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
8022 if (NSData *data = [NSURLConnection
8023 sendSynchronousRequest:[NSURLRequest
8025 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8029 returningResponse:NULL
8032 if (UIImage *image = [UIImage imageWithData:data])
8033 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
8039 - (void) setSource:(Source *)source {
8040 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8042 origin_ = [source name];
8043 label_ = [source uri];
8045 [content_ setNeedsDisplay];
8047 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
8050 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8051 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8052 UIView *content([self contentView]);
8053 CGRect bounds([content bounds]);
8055 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8056 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8057 [content_ setBackgroundColor:[UIColor whiteColor]];
8058 [content addSubview:content_];
8060 [content_ setDelegate:self];
8061 [content_ setOpaque:YES];
8065 - (NSString *) accessibilityLabel {
8069 - (void) drawContentRect:(CGRect)rect {
8070 bool highlighted(highlighted_);
8071 float width(rect.size.width);
8074 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8081 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8085 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8090 /* Source Controller {{{ */
8091 @interface SourceController : FilteredPackageListController {
8092 _transient Source *source_;
8096 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8100 @implementation SourceController
8102 - (NSURL *) navigationURL {
8103 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8106 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8107 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8109 key_ = [source key];
8113 - (void) reloadData {
8114 source_ = [database_ sourceWithKey:key_];
8115 key_ = [source_ key];
8116 [self setObject:source_];
8118 [[self navigationItem] setTitle:[source_ label]];
8125 /* Sources Controller {{{ */
8126 @interface SourcesController : CyteViewController <
8127 UITableViewDataSource,
8130 _transient Database *database_;
8131 _H<UITableView, 2> list_;
8132 _H<NSMutableArray> sources_;
8136 _H<UIProgressHUD> hud_;
8139 //NSURLConnection *installer_;
8140 NSURLConnection *trivial_;
8141 NSURLConnection *trivial_bz2_;
8142 NSURLConnection *trivial_gz_;
8143 //NSURLConnection *automatic_;
8148 - (id) initWithDatabase:(Database *)database;
8149 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8153 @implementation SourcesController
8155 - (void) _releaseConnection:(NSURLConnection *)connection {
8156 if (connection != nil) {
8157 [connection cancel];
8158 //[connection setDelegate:nil];
8159 [connection release];
8164 //[self _releaseConnection:installer_];
8165 [self _releaseConnection:trivial_];
8166 [self _releaseConnection:trivial_gz_];
8167 [self _releaseConnection:trivial_bz2_];
8168 //[self _releaseConnection:automatic_];
8173 - (NSURL *) navigationURL {
8174 return [NSURL URLWithString:@"cydia://sources"];
8177 - (void) viewDidAppear:(BOOL)animated {
8178 [super viewDidAppear:animated];
8179 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8182 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8183 return offset_ == 0 ? 1 : 2;
8186 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8187 switch (section + (offset_ == 0 ? 1 : 0)) {
8188 case 0: return UCLocalize("ENTERED_BY_USER");
8189 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8195 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8196 int count = [sources_ count];
8198 case 0: return (offset_ == 0 ? count : offset_);
8199 case 1: return count - offset_;
8205 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8207 switch (indexPath.section) {
8208 case 0: idx = indexPath.row; break;
8209 case 1: idx = indexPath.row + offset_; break;
8213 return [sources_ objectAtIndex:idx];
8216 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8217 static NSString *cellIdentifier = @"SourceCell";
8219 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8220 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8221 [cell setSource:[self sourceAtIndexPath:indexPath]];
8222 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8227 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8228 Source *source = [self sourceAtIndexPath:indexPath];
8230 SourceController *controller = [[[SourceController alloc]
8231 initWithDatabase:database_
8235 [controller setDelegate:delegate_];
8237 [[self navigationController] pushViewController:controller animated:YES];
8240 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8241 Source *source = [self sourceAtIndexPath:indexPath];
8242 return [source record] != nil;
8245 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8246 if (editingStyle == UITableViewCellEditingStyleDelete) {
8247 Source *source = [self sourceAtIndexPath:indexPath];
8248 [Sources_ removeObjectForKey:[source key]];
8249 [delegate_ syncData];
8254 [delegate_ addTrivialSource:href_];
8255 [delegate_ syncData];
8258 - (NSString *) getWarning {
8259 NSString *href(href_);
8260 NSRange colon([href rangeOfString:@"://"]);
8261 if (colon.location != NSNotFound)
8262 href = [href substringFromIndex:(colon.location + 3)];
8263 href = [href stringByAddingPercentEscapes];
8264 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8265 href = [href stringByCachingURLWithCurrentCDN];
8267 NSURL *url([NSURL URLWithString:href]);
8269 NSStringEncoding encoding;
8270 NSError *error(nil);
8272 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8273 return [warning length] == 0 ? nil : warning;
8277 - (void) _endConnection:(NSURLConnection *)connection {
8278 // XXX: the memory management in this method is horribly awkward
8280 NSURLConnection **field = NULL;
8281 if (connection == trivial_)
8283 else if (connection == trivial_bz2_)
8284 field = &trivial_bz2_;
8285 else if (connection == trivial_gz_)
8286 field = &trivial_gz_;
8287 _assert(field != NULL);
8288 [connection release];
8293 trivial_bz2_ == nil &&
8296 [delegate_ releaseNetworkActivityIndicator];
8298 [delegate_ removeProgressHUD:hud_];
8304 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8307 UIAlertView *alert = [[[UIAlertView alloc]
8308 initWithTitle:UCLocalize("SOURCE_WARNING")
8311 cancelButtonTitle:UCLocalize("CANCEL")
8313 UCLocalize("ADD_ANYWAY"),
8317 [alert setContext:@"warning"];
8318 [alert setNumberOfRows:1];
8322 } else if (error_ != nil) {
8323 UIAlertView *alert = [[[UIAlertView alloc]
8324 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8325 message:[error_ localizedDescription]
8327 cancelButtonTitle:UCLocalize("OK")
8328 otherButtonTitles:nil
8331 [alert setContext:@"urlerror"];
8334 UIAlertView *alert = [[[UIAlertView alloc]
8335 initWithTitle:UCLocalize("NOT_REPOSITORY")
8336 message:UCLocalize("NOT_REPOSITORY_EX")
8338 cancelButtonTitle:UCLocalize("OK")
8339 otherButtonTitles:nil
8342 [alert setContext:@"trivial"];
8351 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8352 switch ([response statusCode]) {
8358 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8359 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8361 [self _endConnection:connection];
8364 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8365 [self _endConnection:connection];
8368 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8369 NSURL *url([NSURL URLWithString:href]);
8371 NSMutableURLRequest *request = [NSMutableURLRequest
8373 cachePolicy:NSURLRequestUseProtocolCachePolicy
8374 timeoutInterval:120.0
8377 [request setHTTPMethod:method];
8379 if (Machine_ != NULL)
8380 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8382 if ([url isCydiaSecure]) {
8383 if (UniqueID_ != nil)
8384 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8387 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8390 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8391 NSString *context([alert context]);
8393 if ([context isEqualToString:@"source"]) {
8396 NSString *href = [[alert textField] text];
8398 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8400 if (![href hasSuffix:@"/"])
8401 href_ = [href stringByAppendingString:@"/"];
8405 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8406 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8407 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8408 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8412 // XXX: this is stupid
8413 hud_ = [delegate_ addProgressHUD];
8414 [hud_ setText:UCLocalize("VERIFYING_URL")];
8415 [delegate_ retainNetworkActivityIndicator];
8424 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8425 } else if ([context isEqualToString:@"trivial"])
8426 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8427 else if ([context isEqualToString:@"urlerror"])
8428 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8429 else if ([context isEqualToString:@"warning"]) {
8443 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8448 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8450 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8451 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8452 [list_ setRowHeight:56];
8453 [(UITableView *) list_ setDataSource:self];
8454 [list_ setDelegate:self];
8455 [[self view] addSubview:list_];
8458 - (void) viewDidLoad {
8459 [super viewDidLoad];
8461 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8462 [self updateButtonsForEditingStatus:NO animated:NO];
8465 - (void) releaseSubviews {
8470 [super releaseSubviews];
8473 - (id) initWithDatabase:(Database *)database {
8474 if ((self = [super init]) != nil) {
8475 database_ = database;
8479 - (void) reloadData {
8483 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8486 sources_ = [NSMutableArray arrayWithCapacity:16];
8487 [sources_ addObjectsFromArray:[database_ sources]];
8489 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8492 int count([sources_ count]);
8494 for (int i = 0; i != count; i++) {
8495 if ([[sources_ objectAtIndex:i] record] == nil)
8500 [list_ setEditing:NO];
8501 [self updateButtonsForEditingStatus:NO animated:NO];
8505 - (void) showAddSourcePrompt {
8506 UIAlertView *alert = [[[UIAlertView alloc]
8507 initWithTitle:UCLocalize("ENTER_APT_URL")
8510 cancelButtonTitle:UCLocalize("CANCEL")
8512 UCLocalize("ADD_SOURCE"),
8516 [alert setContext:@"source"];
8518 [alert setNumberOfRows:1];
8519 [alert addTextFieldWithValue:@"http://" label:@""];
8521 UITextInputTraits *traits = [[alert textField] textInputTraits];
8522 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8523 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8524 [traits setKeyboardType:UIKeyboardTypeURL];
8525 // XXX: UIReturnKeyDone
8526 [traits setReturnKeyType:UIReturnKeyNext];
8531 - (void) addButtonClicked {
8532 [self showAddSourcePrompt];
8535 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8536 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8537 initWithTitle:UCLocalize("ADD")
8538 style:UIBarButtonItemStylePlain
8540 action:@selector(addButtonClicked)
8541 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8543 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8544 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8545 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8547 action:@selector(editButtonClicked)
8548 ] autorelease] animated:animated];
8550 if (IsWildcat_ && !editing)
8551 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8552 initWithTitle:UCLocalize("SETTINGS")
8553 style:UIBarButtonItemStylePlain
8555 action:@selector(settingsButtonClicked)
8559 - (void) settingsButtonClicked {
8560 [delegate_ showSettings];
8563 - (void) editButtonClicked {
8564 [list_ setEditing:![list_ isEditing] animated:YES];
8566 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8572 /* Settings Controller {{{ */
8573 @interface SettingsController : CyteViewController <
8574 UITableViewDataSource,
8577 _transient Database *database_;
8578 // XXX: ok, "roledelegate_"?...
8579 _transient id roledelegate_;
8580 _H<UITableView, 2> table_;
8581 _H<UISegmentedControl> segment_;
8582 _H<UIView> container_;
8585 - (void) showDoneButton;
8586 - (void) resizeSegmentedControl;
8590 @implementation SettingsController
8593 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8595 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8596 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8597 [table_ setDelegate:self];
8598 [(UITableView *) table_ setDataSource:self];
8599 [[self view] addSubview:table_];
8601 NSArray *items = [NSArray arrayWithObjects:
8603 UCLocalize("HACKER"),
8604 UCLocalize("DEVELOPER"),
8606 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8607 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8608 [container_ addSubview:segment_];
8611 - (void) viewDidLoad {
8612 [super viewDidLoad];
8614 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8617 if ([Role_ isEqualToString:@"User"]) index = 0;
8618 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8619 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8621 [segment_ setSelectedSegmentIndex:index];
8622 [self showDoneButton];
8625 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8626 [self resizeSegmentedControl];
8629 - (void) releaseSubviews {
8634 [super releaseSubviews];
8637 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8638 if ((self = [super init]) != nil) {
8639 database_ = database;
8640 roledelegate_ = delegate;
8644 - (void) resizeSegmentedControl {
8645 CGFloat width = [[self view] frame].size.width;
8646 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8649 - (void) viewWillAppear:(BOOL)animated {
8650 [super viewWillAppear:animated];
8652 [self resizeSegmentedControl];
8655 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8656 [self resizeSegmentedControl];
8659 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8660 [self resizeSegmentedControl];
8664 NSString *role(nil);
8666 switch ([segment_ selectedSegmentIndex]) {
8667 case 0: role = @"User"; break;
8668 case 1: role = @"Hacker"; break;
8669 case 2: role = @"Developer"; break;
8674 if (![role isEqualToString:Role_]) {
8675 bool rolling(Role_ == nil);
8678 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8682 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8686 [roledelegate_ loadData];
8688 [roledelegate_ updateData];
8692 - (void) segmentChanged:(UISegmentedControl *)control {
8693 [self showDoneButton];
8696 - (void) saveAndClose {
8699 [[self navigationItem] setRightBarButtonItem:nil];
8700 [[self navigationController] dismissModalViewControllerAnimated:YES];
8703 - (void) doneButtonClicked {
8704 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8705 [spinner startAnimating];
8706 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8707 [[self navigationItem] setRightBarButtonItem:spinItem];
8709 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8712 - (void) showDoneButton {
8713 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8714 initWithTitle:UCLocalize("DONE")
8715 style:UIBarButtonItemStyleDone
8717 action:@selector(doneButtonClicked)
8718 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8721 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8722 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8726 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8730 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8731 return nil; // This method is required by the protocol.
8734 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8736 return UCLocalize("ROLE_EX");
8738 return [NSString stringWithFormat:
8739 @"%@: %@\n%@: %@\n%@: %@",
8740 UCLocalize("USER"), UCLocalize("USER_EX"),
8741 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8742 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8747 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8748 return section == 3 ? 44.0f : 0;
8751 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8752 return section == 3 ? container_ : nil;
8755 - (void) reloadData {
8758 [table_ reloadData];
8763 /* Stash Controller {{{ */
8764 @interface StashController : CyteViewController {
8765 _H<UIActivityIndicatorView> spinner_;
8766 _H<UILabel> status_;
8767 _H<UILabel> caption_;
8772 @implementation StashController
8775 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8776 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8778 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8779 CGRect spinrect = [spinner_ frame];
8780 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8781 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8782 [spinner_ setFrame:spinrect];
8783 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8784 [[self view] addSubview:spinner_];
8785 [spinner_ startAnimating];
8788 captrect.size.width = [[self view] frame].size.width;
8789 captrect.size.height = 40.0f;
8790 captrect.origin.x = 0;
8791 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8792 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8793 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8794 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8795 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8796 [caption_ setTextColor:[UIColor whiteColor]];
8797 [caption_ setBackgroundColor:[UIColor clearColor]];
8798 [caption_ setShadowColor:[UIColor blackColor]];
8799 [caption_ setTextAlignment:UITextAlignmentCenter];
8800 [[self view] addSubview:caption_];
8803 statusrect.size.width = [[self view] frame].size.width;
8804 statusrect.size.height = 30.0f;
8805 statusrect.origin.x = 0;
8806 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8807 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8808 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8809 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8810 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8811 [status_ setTextColor:[UIColor whiteColor]];
8812 [status_ setBackgroundColor:[UIColor clearColor]];
8813 [status_ setShadowColor:[UIColor blackColor]];
8814 [status_ setTextAlignment:UITextAlignmentCenter];
8815 [[self view] addSubview:status_];
8818 - (void) releaseSubviews {
8823 [super releaseSubviews];
8829 @interface CYURLCache : SDURLCache {
8834 @implementation CYURLCache
8836 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8839 else if ([event isEqualToString:@"no-cache"])
8841 else if ([event isEqualToString:@"store"])
8843 else if ([event isEqualToString:@"invalid"])
8845 else if ([event isEqualToString:@"memory"])
8847 else if ([event isEqualToString:@"disk"])
8849 else if ([event isEqualToString:@"miss"])
8852 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8856 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8857 if (NSURLResponse *response = [cached response])
8858 if (NSString *mime = [response MIMEType])
8859 if ([mime isEqualToString:@"text/cache-manifest"]) {
8860 NSURL *url([response URL]);
8863 NSLog(@"###: %@", [url absoluteString]);
8866 @synchronized (HostConfig_) {
8867 [CachedURLs_ addObject:url];
8871 [super storeCachedResponse:cached forRequest:request];
8876 @interface Cydia : UIApplication <
8877 ConfirmationControllerDelegate,
8880 UINavigationControllerDelegate,
8881 UITabBarControllerDelegate
8883 _H<UIWindow> window_;
8884 _H<CYTabBarController> tabbar_;
8885 _H<CydiaLoadingViewController> emulated_;
8887 _H<NSMutableArray> essential_;
8888 _H<NSMutableArray> broken_;
8890 Database *database_;
8892 _H<NSURL> starturl_;
8897 _H<StashController> stash_;
8906 @implementation Cydia
8908 - (void) beginUpdate {
8909 [tabbar_ beginUpdate];
8913 return [tabbar_ updating];
8917 if ([broken_ count] != 0) {
8918 int count = [broken_ count];
8920 UIAlertView *alert = [[[UIAlertView alloc]
8921 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8922 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8924 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8926 UCLocalize("TEMPORARY_IGNORE"),
8930 [alert setContext:@"fixhalf"];
8931 [alert setNumberOfRows:2];
8933 } else if (!Ignored_ && [essential_ count] != 0) {
8934 int count = [essential_ count];
8936 UIAlertView *alert = [[[UIAlertView alloc]
8937 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8938 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8940 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8942 UCLocalize("UPGRADE_ESSENTIAL"),
8943 UCLocalize("COMPLETE_UPGRADE"),
8947 [alert setContext:@"upgrade"];
8952 - (void) returnToCydia {
8956 - (void) _saveConfig {
8962 NSString *error(nil);
8964 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8966 NSError *error(nil);
8967 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8968 NSLog(@"failure to save metadata data: %@", error);
8973 NSLog(@"failure to serialize metadata: %@", error);
8980 // Navigation controller for the queuing badge.
8981 - (UINavigationController *) queueNavigationController {
8982 NSArray *controllers = [tabbar_ viewControllers];
8983 return [controllers objectAtIndex:3];
8986 - (void) unloadData {
8987 [tabbar_ unloadData];
8990 - (void) _updateData {
8994 UINavigationController *navigation = [self queueNavigationController];
8996 id queuedelegate = nil;
8997 if ([[navigation viewControllers] count] > 0)
8998 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9000 [queuedelegate queueStatusDidChange];
9001 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9004 - (void) _refreshIfPossible:(NSDate *)update {
9005 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9007 bool recently = false;
9008 if (update != nil) {
9009 NSTimeInterval interval([update timeIntervalSinceNow]);
9010 if (interval <= 0 && interval > -(15*60))
9014 // Don't automatic refresh if:
9015 // - We already refreshed recently.
9016 // - We already auto-refreshed this launch.
9017 // - Auto-refresh is disabled.
9018 if (recently || loaded_ || ManualRefresh) {
9019 // If we are cancelling, we need to make sure it knows it's already loaded.
9022 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9024 // We are going to load, so remember that.
9027 SCNetworkReachabilityFlags flags; {
9028 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9029 SCNetworkReachabilityGetFlags(reachability, &flags);
9030 CFRelease(reachability);
9033 // XXX: this elaborate mess is what Apple is using to determine this? :(
9034 // XXX: do we care if the user has to intervene? maybe that's ok?
9036 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9037 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9038 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9039 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9040 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9041 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9045 // If we can reach the server, auto-refresh!
9047 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9053 - (void) refreshIfPossible {
9054 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9057 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9058 @synchronized (self) {
9059 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9060 [hud setText:UCLocalize("RELOADING_DATA")];
9062 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9065 [self removeProgressHUD:hud];
9069 [essential_ removeAllObjects];
9070 [broken_ removeAllObjects];
9072 NSArray *packages([database_ packages]);
9073 for (Package *package in packages) {
9075 [broken_ addObject:package];
9076 if ([package upgradableAndEssential:NO]) {
9077 if ([package essential])
9078 [essential_ addObject:package];
9083 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9086 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9087 [changesItem setBadgeValue:badge];
9088 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9089 [self setApplicationIconBadgeNumber:changes];
9092 [changesItem setBadgeValue:nil];
9093 [changesItem setAnimatedBadge:NO];
9094 [self setApplicationIconBadgeNumber:0];
9100 - (void) updateData {
9106 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9109 - (void) disemulate {
9110 if (emulated_ == nil)
9113 [window_ addSubview:[tabbar_ view]];
9114 [[emulated_ view] removeFromSuperview];
9116 [window_ setUserInteractionEnabled:YES];
9119 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9120 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9122 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9124 UIViewController *parent;
9125 if (emulated_ == nil)
9134 [parent presentModalViewController:navigation animated:YES];
9137 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9138 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9140 if (navigation != nil)
9141 [navigation pushViewController:progress animated:YES];
9143 [self presentModalViewController:progress force:YES];
9145 [progress invoke:invocation withTitle:title];
9149 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9150 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9153 - (void) repairWithInvocation:(NSInvocation *)invocation {
9155 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9159 - (void) repairWithSelector:(SEL)selector {
9160 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9163 - (void) reloadData {
9164 [self reloadDataWithInvocation:nil];
9165 if ([database_ progressDelegate] == nil)
9171 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9174 - (void) addSource:(NSDictionary *) source {
9178 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9179 AddSource(href, distribution, sections);
9182 - (void) addTrivialSource:(NSString *)href {
9183 AddSource(href, @"./");
9186 - (void) updateValues {
9191 pkgProblemResolver *resolver = [database_ resolver];
9193 resolver->InstallProtect();
9194 if (!resolver->Resolve(true))
9199 // XXX: this is a really crappy way of doing this.
9200 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9201 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9202 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9203 if ([tabbar_ updating])
9204 [tabbar_ cancelUpdate];
9206 if (![database_ prepare])
9209 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9210 [page setDelegate:self];
9211 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9214 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9215 [tabbar_ presentModalViewController:confirm_ animated:YES];
9221 @synchronized (self) {
9226 - (void) clearPackage:(Package *)package {
9227 @synchronized (self) {
9234 - (void) installPackages:(NSArray *)packages {
9235 @synchronized (self) {
9236 for (Package *package in packages)
9243 - (void) installPackage:(Package *)package {
9244 @synchronized (self) {
9251 - (void) removePackage:(Package *)package {
9252 @synchronized (self) {
9259 - (void) distUpgrade {
9260 @synchronized (self) {
9261 if (![database_ upgrade])
9268 [database_ perform];
9269 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9272 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9275 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9277 [self refreshIfPossible];
9280 - (void) showSettings {
9281 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9284 - (void) retainNetworkActivityIndicator {
9285 if (activity_++ == 0)
9286 [self setNetworkActivityIndicatorVisible:YES];
9289 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9293 - (void) releaseNetworkActivityIndicator {
9294 if (--activity_ == 0)
9295 [self setNetworkActivityIndicatorVisible:NO];
9298 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9303 - (void) cancelAndClear:(bool)clear {
9304 @synchronized (self) {
9316 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9317 NSString *context([alert context]);
9319 if ([context isEqualToString:@"conffile"]) {
9320 FILE *input = [database_ input];
9321 if (button == [alert cancelButtonIndex])
9322 fprintf(input, "N\n");
9323 else if (button == [alert firstOtherButtonIndex])
9324 fprintf(input, "Y\n");
9327 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9328 } else if ([context isEqualToString:@"fixhalf"]) {
9329 if (button == [alert cancelButtonIndex]) {
9330 @synchronized (self) {
9331 for (Package *broken in (id) broken_) {
9334 NSString *id = [broken id];
9335 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9336 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9337 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9338 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9344 } else if (button == [alert firstOtherButtonIndex]) {
9345 [broken_ removeAllObjects];
9349 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9350 } else if ([context isEqualToString:@"upgrade"]) {
9351 if (button == [alert firstOtherButtonIndex]) {
9352 @synchronized (self) {
9353 for (Package *essential in (id) essential_)
9354 [essential install];
9359 } else if (button == [alert firstOtherButtonIndex] + 1) {
9361 } else if (button == [alert cancelButtonIndex]) {
9365 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9369 - (void) system:(NSString *)command {
9370 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9373 system([command UTF8String]);
9379 - (void) applicationWillSuspend {
9381 [super applicationWillSuspend];
9384 - (BOOL) isSafeToSuspend {
9387 NSLog(@"isSafeToSuspend: locked_ != 0");
9392 // Use external process status API internally.
9393 // This is probably a really bad idea.
9394 // XXX: what is the point of this? does this solve anything at all?
9395 uint64_t status = 0;
9397 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9398 notify_get_state(notify_token, &status);
9399 notify_cancel(notify_token);
9404 NSLog(@"isSafeToSuspend: status != 0");
9410 NSLog(@"isSafeToSuspend: -> true");
9415 - (void) applicationSuspend:(__GSEvent *)event {
9416 if ([self isSafeToSuspend])
9417 [super applicationSuspend:event];
9420 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9421 if ([self isSafeToSuspend])
9422 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9425 - (void) _setSuspended:(BOOL)value {
9426 if ([self isSafeToSuspend])
9427 [super _setSuspended:value];
9430 - (UIProgressHUD *) addProgressHUD {
9431 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9432 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9434 [window_ setUserInteractionEnabled:NO];
9436 UIViewController *target(tabbar_);
9437 if (UIViewController *modal = [target modalViewController])
9440 UIView *view([target view]);
9441 [view addSubview:hud];
9443 [hud showInView:[tabbar_ view]];
9449 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9452 [hud removeFromSuperview];
9453 [window_ setUserInteractionEnabled:YES];
9456 - (CyteViewController *) pageForPackage:(NSString *)name {
9457 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9460 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9461 NSString *scheme([[url scheme] lowercaseString]);
9462 if ([[url absoluteString] length] <= [scheme length] + 3)
9464 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9465 NSArray *components([path pathComponents]);
9467 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9468 return [self pageForPackage:[components objectAtIndex:1]];
9470 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9473 NSString *base([components objectAtIndex:0]);
9475 CyteViewController *controller = nil;
9477 if ([base isEqualToString:@"url"]) {
9478 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9479 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9480 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9481 } else if (!external && [components count] == 1) {
9482 if ([base isEqualToString:@"manage"]) {
9483 controller = [[[ManageController alloc] init] autorelease];
9486 if ([base isEqualToString:@"sources"]) {
9487 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9490 if ([base isEqualToString:@"home"]) {
9491 controller = [[[HomeController alloc] init] autorelease];
9494 if ([base isEqualToString:@"sections"]) {
9495 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9498 if ([base isEqualToString:@"search"]) {
9499 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9502 if ([base isEqualToString:@"changes"]) {
9503 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9506 if ([base isEqualToString:@"installed"]) {
9507 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9509 } else if ([components count] == 2) {
9510 NSString *argument = [components objectAtIndex:1];
9512 if ([base isEqualToString:@"package"]) {
9513 controller = [self pageForPackage:argument];
9516 if (!external && [base isEqualToString:@"search"]) {
9517 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9520 if (!external && [base isEqualToString:@"sections"]) {
9521 if ([argument isEqualToString:@"all"])
9523 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9526 if (!external && [base isEqualToString:@"sources"]) {
9527 if ([argument isEqualToString:@"add"]) {
9528 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9529 [(SourcesController *)controller showAddSourcePrompt];
9531 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9532 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9536 if (!external && [base isEqualToString:@"launch"]) {
9537 [self launchApplicationWithIdentifier:argument suspended:NO];
9540 } else if (!external && [components count] == 3) {
9541 NSString *arg1 = [components objectAtIndex:1];
9542 NSString *arg2 = [components objectAtIndex:2];
9544 if ([base isEqualToString:@"package"]) {
9545 if ([arg2 isEqualToString:@"settings"]) {
9546 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9547 } else if ([arg2 isEqualToString:@"files"]) {
9548 if (Package *package = [database_ packageWithName:arg1]) {
9549 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9550 [(FileTable *)controller setPackage:package];
9556 [controller setDelegate:self];
9560 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9561 CyteViewController *page([self pageForURL:url forExternal:external]);
9564 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9565 [nav setViewControllers:[NSArray arrayWithObject:page]];
9566 [tabbar_ setUnselectedViewController:nav];
9572 - (void) applicationOpenURL:(NSURL *)url {
9573 [super applicationOpenURL:url];
9578 [self openCydiaURL:url forExternal:YES];
9581 - (void) applicationWillResignActive:(UIApplication *)application {
9582 // Stop refreshing if you get a phone call or lock the device.
9583 if ([tabbar_ updating])
9584 [tabbar_ cancelUpdate];
9586 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9587 [super applicationWillResignActive:application];
9590 - (void) saveState {
9591 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9592 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9593 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9599 - (void) applicationWillTerminate:(UIApplication *)application {
9603 - (void) setConfigurationData:(NSString *)data {
9604 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9606 if (!conffile_r(data)) {
9607 lprintf("E:invalid conffile\n");
9611 NSString *ofile = conffile_r[1];
9612 //NSString *nfile = conffile_r[2];
9614 UIAlertView *alert = [[[UIAlertView alloc]
9615 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9616 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9618 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9620 UCLocalize("ACCEPT_NEW_COPY"),
9621 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9625 [alert setContext:@"conffile"];
9626 [alert setNumberOfRows:2];
9630 - (void) addStashController {
9632 stash_ = [[[StashController alloc] init] autorelease];
9633 [window_ addSubview:[stash_ view]];
9636 - (void) removeStashController {
9637 [[stash_ view] removeFromSuperview];
9643 [self setIdleTimerDisabled:YES];
9645 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9646 UpdateExternalStatus(1);
9647 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9648 UpdateExternalStatus(0);
9650 [self removeStashController];
9652 if (ExecFork() == 0) {
9653 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9654 perror("launchctl stop");
9658 - (void) setupViewControllers {
9659 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9661 NSMutableArray *items([NSMutableArray arrayWithObjects:
9662 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9663 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9664 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9665 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9669 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9670 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9672 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9675 NSMutableArray *controllers([NSMutableArray array]);
9676 for (UITabBarItem *item in items) {
9677 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9678 [controller setTabBarItem:item];
9679 [controllers addObject:controller];
9681 [tabbar_ setViewControllers:controllers];
9683 [tabbar_ setUpdateDelegate:self];
9686 - (void) _sendMemoryWarningNotification {
9687 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9690 - (void) _sendMemoryWarningNotifications {
9692 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9697 - (void) applicationDidFinishLaunching:(id)unused {
9698 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9701 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9702 [self setApplicationSupportsShakeToEdit:NO];
9704 @synchronized (HostConfig_) {
9705 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9708 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9709 initWithMemoryCapacity:524288
9710 diskCapacity:10485760
9711 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9714 [CydiaWebViewController _initialize];
9716 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9718 // this would disallow http{,s} URLs from accessing this data
9719 //[WebView registerURLSchemeAsLocal:@"cydia"];
9721 Font12_ = [UIFont systemFontOfSize:12];
9722 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9723 Font14_ = [UIFont systemFontOfSize:14];
9724 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9725 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9727 essential_ = [NSMutableArray arrayWithCapacity:4];
9728 broken_ = [NSMutableArray arrayWithCapacity:4];
9730 // XXX: I really need this thing... like, seriously... I'm sorry
9731 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9733 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9734 [window_ orderFront:self];
9735 [window_ makeKey:self];
9736 [window_ setHidden:NO];
9739 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9740 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9741 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9742 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9743 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9744 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9745 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9746 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9747 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9750 [self addStashController];
9751 // XXX: this would be much cleaner as a yieldToSelector:
9752 // that way the removeStashController could happen right here inline
9753 // we also could no longer require the useless stash_ field anymore
9754 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9758 database_ = [Database sharedInstance];
9759 [database_ setDelegate:self];
9761 [window_ setUserInteractionEnabled:NO];
9762 [self setupViewControllers];
9764 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9765 [window_ addSubview:[emulated_ view]];
9767 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9771 - (NSArray *) defaultStartPages {
9772 NSMutableArray *standard = [NSMutableArray array];
9773 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9774 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9775 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9777 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9779 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9780 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9782 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9789 [window_ setUserInteractionEnabled:YES];
9790 [self showSettings];
9793 if ([emulated_ modalViewController] != nil)
9794 [emulated_ dismissModalViewControllerAnimated:YES];
9795 [window_ setUserInteractionEnabled:NO];
9798 [self reloadDataWithInvocation:nil];
9799 [self refreshIfPossible];
9804 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9805 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9806 int standardIndex = 0;
9807 NSArray *standard = [self defaultStartPages];
9814 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9815 if (valid && closed != nil) {
9816 NSTimeInterval interval([closed timeIntervalSinceNow]);
9817 // XXX: Is 15 minutes the optimal time here?
9818 if (interval > 0 && interval <= -(15*60))
9822 if (valid && [saved count] != [standard count])
9826 for (unsigned int i = 0; i < [standard count]; i++) {
9827 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9828 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9829 // but it's good enough for now.
9830 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9837 NSArray *items = nil;
9839 [tabbar_ setSelectedIndex:savedIndex];
9842 [tabbar_ setSelectedIndex:standardIndex];
9846 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9847 NSArray *stack = [items objectAtIndex:tab];
9848 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9849 NSMutableArray *current = [NSMutableArray array];
9851 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9852 NSString *addr = [stack objectAtIndex:nav];
9853 NSURL *url = [NSURL URLWithString:addr];
9854 CyteViewController *page = [self pageForURL:url forExternal:NO];
9856 [current addObject:page];
9859 [navigation setViewControllers:current];
9862 // (Try to) show the startup URL.
9863 if (starturl_ != nil) {
9864 [self openCydiaURL:starturl_ forExternal:NO];
9869 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9870 if (item != nil && IsWildcat_) {
9871 [sheet showFromBarButtonItem:item animated:YES];
9873 [sheet showInView:window_];
9877 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9878 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9879 [progress setTitle:task];
9880 [progress addProgressEvent:event];
9883 - (void) addProgressEventForTask:(NSArray *)data {
9884 CydiaProgressEvent *event([data objectAtIndex:0]);
9885 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9886 [self addProgressEvent:event forTask:task];
9889 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9890 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9896 id Alloc_(id self, SEL selector) {
9897 id object = alloc_(self, selector);
9898 lprintf("[%s]A-%p\n", self->isa->name, object);
9903 id Dealloc_(id self, SEL selector) {
9904 id object = dealloc_(self, selector);
9905 lprintf("[%s]D-%p\n", self->isa->name, object);
9909 Class $WebDefaultUIKitDelegate;
9911 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9912 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9913 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9914 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9917 static NSSet *MobilizedFiles_;
9919 static NSURL *MobilizeURL(NSURL *url) {
9920 NSString *path([url path]);
9921 if ([path hasPrefix:@"/var/root/"]) {
9922 NSString *file([path substringFromIndex:10]);
9923 if ([MobilizedFiles_ containsObject:file])
9924 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9930 Class $CFXPreferencesPropertyListSource;
9931 @class CFXPreferencesPropertyListSource;
9933 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9934 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9935 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9936 url = MobilizeURL(url);
9937 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9938 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9944 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9945 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9946 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9947 url = MobilizeURL(url);
9948 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9949 //NSLog(@"%@ %@", [url absoluteString], value);
9955 Class $NSURLConnection;
9957 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9958 NSMutableURLRequest *copy([request mutableCopy]);
9960 NSURL *url([copy URL]);
9962 NSString *href([url absoluteString]);
9963 NSString *host([url host]);
9964 NSString *scheme([[url scheme] lowercaseString]);
9966 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9968 @synchronized (HostConfig_) {
9969 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9970 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9971 [copy setHTTPShouldUsePipelining:YES];
9973 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9974 if ([control isEqualToString:@"max-age=0"])
9975 if ([CachedURLs_ containsObject:href]) {
9977 NSLog(@"~~~: %@", href);
9980 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9982 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9983 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9984 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9988 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9992 int main(int argc, char *argv[]) {
9993 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9997 UpdateExternalStatus(0);
9999 if (Class $UIDevice = objc_getClass("UIDevice")) {
10000 UIDevice *device([$UIDevice currentDevice]);
10001 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10003 IsWildcat_ = false;
10005 UIScreen *screen([UIScreen mainScreen]);
10006 if ([screen respondsToSelector:@selector(scale)])
10007 ScreenScale_ = [screen scale];
10011 UIDevice *device([UIDevice currentDevice]);
10012 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10013 Idiom_ = @"iphone";
10015 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10016 if (idiom == UIUserInterfaceIdiomPhone)
10017 Idiom_ = @"iphone";
10018 else if (idiom == UIUserInterfaceIdiomPad)
10021 NSLog(@"unknown UIUserInterfaceIdiom!");
10024 Pcre pattern("^([0-9]+\\.[0-9]+)");
10025 if (pattern([device systemVersion]))
10026 Firmware_ = pattern[1];
10028 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10030 HostConfig_ = [[[NSObject alloc] init] autorelease];
10031 @synchronized (HostConfig_) {
10032 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10033 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10034 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10035 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10036 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10039 NSString *ui(@"ui/ios");
10041 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10042 UI_ = CydiaURL(ui);
10044 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10046 MobilizedFiles_ = [NSMutableSet setWithObjects:
10047 @"Library/Preferences/com.apple.Accessibility.plist",
10048 @"Library/Preferences/com.apple.preferences.sounds.plist",
10051 /* Library Hacks {{{ */
10052 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10054 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10056 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10057 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10058 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10059 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10062 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10063 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10064 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10065 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10068 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10069 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10070 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10071 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10072 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10075 $NSURLConnection = objc_getClass("NSURLConnection");
10076 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10077 if (NSURLConnection$init$ != NULL) {
10078 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10079 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10082 /* Set Locale {{{ */
10083 Locale_ = CFLocaleCopyCurrent();
10084 Languages_ = [NSLocale preferredLanguages];
10086 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10087 //NSLog(@"%@", [Languages_ description]);
10090 if (Locale_ != NULL)
10091 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10092 else if (Languages_ != nil && [Languages_ count] != 0)
10093 lang = [[Languages_ objectAtIndex:0] UTF8String];
10095 // XXX: consider just setting to C and then falling through?
10098 if (lang != NULL) {
10099 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10100 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10103 NSLog(@"Setting Language: %s", lang);
10105 if (lang != NULL) {
10106 setenv("LANG", lang, true);
10107 std::setlocale(LC_ALL, lang);
10111 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10113 /* Parse Arguments {{{ */
10114 bool substrate(false);
10120 for (int argi(1); argi != argc; ++argi)
10121 if (strcmp(argv[argi], "--") == 0) {
10123 argv[argi] = argv[0];
10129 for (int argi(1); argi != arge; ++argi)
10130 if (strcmp(args[argi], "--substrate") == 0)
10133 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10137 App_ = [[NSBundle mainBundle] bundlePath];
10143 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10144 alloc_ = alloc->method_imp;
10145 alloc->method_imp = (IMP) &Alloc_;*/
10147 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10148 dealloc_ = dealloc->method_imp;
10149 dealloc->method_imp = (IMP) &Dealloc_;*/
10151 /* System Information {{{ */
10155 size = sizeof(maxproc);
10156 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10157 perror("sysctlbyname(\"kern.maxproc\", ?)");
10158 else if (maxproc < 64) {
10160 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10161 perror("sysctlbyname(\"kern.maxproc\", #)");
10164 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10165 char *osversion = new char[size];
10166 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10167 perror("sysctlbyname(\"kern.osversion\", ?)");
10169 System_ = [NSString stringWithUTF8String:osversion];
10171 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10172 char *machine = new char[size];
10173 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10174 perror("sysctlbyname(\"hw.machine\", ?)");
10176 Machine_ = machine;
10178 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10179 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10180 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10182 UniqueID_ = [device uniqueIdentifier];
10184 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10185 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10186 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10188 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10189 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10190 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10192 if (mcc != NULL && mnc != NULL)
10193 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10200 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10201 Build_ = [system objectForKey:@"ProductBuildVersion"];
10202 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10203 Product_ = [info objectForKey:@"SafariProductVersion"];
10204 Safari_ = [info objectForKey:@"CFBundleVersion"];
10207 /* Load Database {{{ */
10209 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10211 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10213 if (Metadata_ == NULL)
10214 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10216 Settings_ = [Metadata_ objectForKey:@"Settings"];
10218 Packages_ = [Metadata_ objectForKey:@"Packages"];
10220 Values_ = [Metadata_ objectForKey:@"Values"];
10221 Sections_ = [Metadata_ objectForKey:@"Sections"];
10222 Sources_ = [Metadata_ objectForKey:@"Sources"];
10224 Token_ = [Metadata_ objectForKey:@"Token"];
10226 Version_ = [Metadata_ objectForKey:@"Version"];
10228 @synchronized (HostConfig_) {
10229 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10233 if (Settings_ != nil)
10234 Role_ = [Settings_ objectForKey:@"Role"];
10236 if (Values_ == nil) {
10237 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10238 [Metadata_ setObject:Values_ forKey:@"Values"];
10241 if (Sections_ == nil) {
10242 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10243 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10246 if (Sources_ == nil) {
10247 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10248 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10251 if (Version_ == nil) {
10252 Version_ = [NSNumber numberWithUnsignedInt:0];
10253 [Metadata_ setObject:Version_ forKey:@"Version"];
10256 @synchronized (HostConfig_) {
10257 if (CydiaSource_ == nil) {
10258 CydiaSource_ = @"apt.saurik.com";
10259 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10263 if ([Version_ unsignedIntValue] == 0) {
10264 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10265 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10266 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10267 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10269 Version_ = [NSNumber numberWithUnsignedInt:1];
10270 [Metadata_ setObject:Version_ forKey:@"Version"];
10272 [Metadata_ removeObjectForKey:@"LastUpdate"];
10281 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10284 if (Packages_ != nil) {
10286 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10290 [Metadata_ removeObjectForKey:@"Packages"];
10296 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10298 #define MobileSubstrate_(name) \
10299 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10300 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10301 if (handle == NULL) \
10302 NSLog(@"%s", dlerror()); \
10305 MobileSubstrate_(Activator)
10306 MobileSubstrate_(libstatusbar)
10307 MobileSubstrate_(SimulatedKeyEvents)
10308 MobileSubstrate_(WinterBoard)
10310 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10311 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10313 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10315 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10316 unlink("/tmp/.cydia.fw");
10318 } else if (access("/User", F_OK) != 0 || version < 4) {
10321 system("/usr/libexec/cydia/firmware.sh");
10325 _assert([[NSFileManager defaultManager]
10326 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10327 withIntermediateDirectories:YES
10332 if (access("/tmp/cydia.chk", F_OK) == 0) {
10333 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10334 _assert(errno == ENOENT);
10335 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10336 _assert(errno == ENOENT);
10339 /* APT Initialization {{{ */
10340 _assert(pkgInitConfig(*_config));
10341 _assert(pkgInitSystem(*_config, _system));
10344 _config->Set("APT::Acquire::Translation", lang);
10346 // XXX: this timeout might be important :(
10347 //_config->Set("Acquire::http::Timeout", 15);
10349 _config->Set("Acquire::http::MaxParallel", 3);
10351 /* Color Choices {{{ */
10352 space_ = CGColorSpaceCreateDeviceRGB();
10354 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10355 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10356 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10357 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10358 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10359 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10360 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10361 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10362 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10364 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10365 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10367 /* UIKit Configuration {{{ */
10368 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10369 if ($GSFontSetUseLegacyFontMetrics != NULL)
10370 $GSFontSetUseLegacyFontMetrics(YES);
10372 // XXX: I have a feeling this was important
10373 //UIKeyboardDisableAutomaticAppearance();
10376 Colon_ = UCLocalize("COLON_DELIMITED");
10377 Elision_ = UCLocalize("ELISION");
10378 Error_ = UCLocalize("ERROR");
10379 Warning_ = UCLocalize("WARNING");
10382 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10384 CGColorSpaceRelease(space_);
10385 CFRelease(Locale_);