1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
125 #include <CydiaSubstrate/CydiaSubstrate.h>
126 #include "Menes/Menes.h"
128 #include "CyteKit/PerlCompatibleRegEx.hpp"
129 #include "CyteKit/TableViewCell.h"
130 #include "CyteKit/WebScriptObject-Cyte.h"
131 #include "CyteKit/WebViewController.h"
132 #include "CyteKit/stringWithUTF8Bytes.h"
134 #include "Cydia/MIMEAddress.h"
135 #include "Cydia/LoadingViewController.h"
136 #include "Cydia/ProgressEvent.h"
138 #include "SDURLCache/SDURLCache.h"
145 #define _timestamp ({ \
147 gettimeofday(&tv, NULL); \
148 tv.tv_sec * 1000000 + tv.tv_usec; \
151 typedef std::vector<class ProfileTime *> TimeList;
161 ProfileTime(const char *name) :
165 times_.push_back(this);
168 void AddTime(uint64_t time) {
175 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
187 ProfileTimer(ProfileTime &time) :
194 time_.AddTime(_timestamp - start_);
199 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
201 std::cerr << "========" << std::endl;
204 #define _profile(name) { \
205 static ProfileTime name(#name); \
206 ProfileTimer _ ## name(name);
211 extern NSString *Cydia_;
213 #define lprintf(args...) fprintf(stderr, args)
216 #define TraceLogging (1 && !ForRelease)
217 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
218 #define ProfileTimes (0 && !ForRelease)
219 #define ForSaurik (0 && !ForRelease)
220 #define LogBrowser (0 && !ForRelease)
221 #define TrackResize (0 && !ForRelease)
222 #define ManualRefresh (1 && !ForRelease)
223 #define ShowInternals (0 && !ForRelease)
224 #define AlwaysReload (0 && !ForRelease)
225 #define TryIndexedCollation (0 && !ForRelease)
229 #define _trace(args...)
234 #define _profile(name) {
237 #define PrintTimes() do {} while (false)
240 // Hash Functions/Structures {{{
241 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
249 static NSString *Colon_;
251 static NSString *Error_;
252 static NSString *Warning_;
254 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
256 static _finline NSString *CydiaURL(NSString *path) {
258 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
259 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
260 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
261 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
262 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
264 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
267 static _finline void UpdateExternalStatus(uint64_t newStatus) {
269 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
270 notify_set_state(notify_token, newStatus);
271 notify_cancel(notify_token);
273 notify_post("com.saurik.Cydia.status");
276 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
277 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
278 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
281 /* NSForcedOrderingSearch doesn't work on the iPhone */
282 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
283 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
284 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
286 /* Insertion Sort {{{ */
288 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
289 const char *ptr = (const char *)list;
291 CFIndex half = count / 2;
292 const char *probe = ptr + elementSize * half;
293 CFComparisonResult cr = comparator(element, probe, context);
294 if (0 == cr) return (probe - (const char *)list) / elementSize;
295 ptr = (cr < 0) ? ptr : probe + elementSize;
296 count = (cr < 0) ? half : (half + (count & 1) - 1);
298 return (ptr - (const char *)list) / elementSize;
301 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
302 const char *ptr = (const char *)list;
304 CFIndex half = count / 2;
305 const char *probe = ptr + elementSize * half;
306 CFComparisonResult cr = comparator(element, probe, context);
307 if (0 == cr) return (probe - (const char *)list) / elementSize;
308 ptr = (cr < 0) ? ptr : probe + elementSize;
309 count = (cr < 0) ? half : (half + (count & 1) - 1);
311 return (ptr - (const char *)list) / elementSize;
314 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
315 if (range.length == 0)
317 const void **values(new const void *[range.length]);
318 CFArrayGetValues(array, range, values);
320 #if HistogramInsertionSort > 0
321 uint32_t total(0), *offsets(new uint32_t[range.length]);
324 for (CFIndex index(1); index != range.length; ++index) {
325 const void *value(values[index]);
326 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
327 CFIndex correct(index);
328 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
329 #if HistogramInsertionSort > 1
330 NSLog(@"%@ < %@", value, values[correct - 1]);
335 if (correct != index) {
336 size_t offset(index - correct);
337 #if HistogramInsertionSort
341 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
343 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
344 values[correct] = value;
348 CFArrayReplaceValues(array, range, values, range.length);
351 #if HistogramInsertionSort > 0
352 for (CFIndex index(0); index != range.length; ++index)
353 if (offsets[index] != 0)
354 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
355 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
362 /* Apple Bug Fixes {{{ */
363 @implementation UIWebDocumentView (Cydia)
365 - (void) _setScrollerOffset:(CGPoint)offset {
366 UIScroller *scroller([self _scroller]);
368 CGSize size([scroller contentSize]);
369 CGSize bounds([scroller bounds].size);
372 max.x = size.width - bounds.width;
373 max.y = size.height - bounds.height;
381 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
382 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
384 [scroller setOffset:offset];
390 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
391 size_t length([self length] - state->state);
394 else if (length > count)
396 for (size_t i(0); i != length; ++i)
397 objects[i] = [self item:state->state++];
398 state->itemsPtr = objects;
399 state->mutationsPtr = (unsigned long *) self;
403 /* Cydia NSString Additions {{{ */
404 @interface NSString (Cydia)
405 - (NSComparisonResult) compareByPath:(NSString *)other;
406 - (NSString *) stringByCachingURLWithCurrentCDN;
407 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
410 @implementation NSString (Cydia)
412 - (NSComparisonResult) compareByPath:(NSString *)other {
413 NSString *prefix = [self commonPrefixWithString:other options:0];
414 size_t length = [prefix length];
416 NSRange lrange = NSMakeRange(length, [self length] - length);
417 NSRange rrange = NSMakeRange(length, [other length] - length);
419 lrange = [self rangeOfString:@"/" options:0 range:lrange];
420 rrange = [other rangeOfString:@"/" options:0 range:rrange];
422 NSComparisonResult value;
424 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
425 value = NSOrderedSame;
426 else if (lrange.location == NSNotFound)
427 value = NSOrderedAscending;
428 else if (rrange.location == NSNotFound)
429 value = NSOrderedDescending;
431 value = NSOrderedSame;
433 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
434 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
435 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
436 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
438 NSComparisonResult result = [lpath compare:rpath];
439 return result == NSOrderedSame ? value : result;
442 - (NSString *) stringByCachingURLWithCurrentCDN {
444 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
445 withString:@"://cache.cydia.saurik.com/"
449 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
450 return [(id)CFURLCreateStringByAddingPercentEscapes(
455 kCFStringEncodingUTF8
462 /* C++ NSString Wrapper Cache {{{ */
463 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
464 return size == 0 ? NULL :
465 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
466 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
469 static _finline CFStringRef CYStringCreate(const char *data) {
470 return CYStringCreate(data, strlen(data));
479 _finline void clear_() {
480 if (cache_ != NULL) {
487 _finline bool empty() const {
491 _finline size_t size() const {
495 _finline char *data() const {
499 _finline void clear() {
504 _finline CYString() :
511 _finline ~CYString() {
515 void operator =(const CYString &rhs) {
519 if (rhs.cache_ == nil)
522 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
525 void copy(apr_pool_t *pool) {
526 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
527 memcpy(temp, data_, size_);
532 void set(apr_pool_t *pool, const char *data, size_t size) {
538 data_ = const_cast<char *>(data);
546 _finline void set(apr_pool_t *pool, const char *data) {
547 set(pool, data, data == NULL ? 0 : strlen(data));
550 _finline void set(apr_pool_t *pool, const std::string &rhs) {
551 set(pool, rhs.data(), rhs.size());
554 bool operator ==(const CYString &rhs) const {
555 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
558 _finline operator CFStringRef() {
560 cache_ = CYStringCreate(data_, size_);
564 _finline operator id() {
565 return (NSString *) static_cast<CFStringRef>(*this);
568 _finline operator const char *() {
569 return reinterpret_cast<const char *>(data_);
573 /* C++ NSString Algorithm Adapters {{{ */
575 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
578 struct NSStringMapHash :
579 std::unary_function<NSString *, size_t>
581 _finline size_t operator ()(NSString *value) const {
582 return CFStringHashNSString((CFStringRef) value);
586 struct NSStringMapLess :
587 std::binary_function<NSString *, NSString *, bool>
589 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
590 return [lhs compare:rhs] == NSOrderedAscending;
594 struct NSStringMapEqual :
595 std::binary_function<NSString *, NSString *, bool>
597 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
598 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
599 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
600 //[lhs isEqualToString:rhs];
605 /* CoreGraphics Primitives {{{ */
610 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
611 CGFloat color[] = {red, green, blue, alpha};
612 return CGColorCreate(space, color);
621 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
622 color_(Create_(space, red, green, blue, alpha))
624 Set(space, red, green, blue, alpha);
629 CGColorRelease(color_);
636 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
638 color_ = Create_(space, red, green, blue, alpha);
641 operator CGColorRef() {
647 /* Random Global Variables {{{ */
648 static const int PulseInterval_ = 50000;
650 static const NSString *UI_;
653 static bool RestartSubstrate_;
654 static NSArray *Finishes_;
656 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
657 #define NotifyConfig_ "/etc/notify.conf"
659 static bool Queuing_;
661 static CYColor Blue_;
662 static CYColor Blueish_;
663 static CYColor Black_;
665 static CYColor White_;
666 static CYColor Gray_;
667 static CYColor Green_;
668 static CYColor Purple_;
669 static CYColor Purplish_;
671 static UIColor *InstallingColor_;
672 static UIColor *RemovingColor_;
674 static NSString *App_;
676 static BOOL Advanced_;
677 static BOOL Ignored_;
679 static _H<UIFont> Font12_;
680 static _H<UIFont> Font12Bold_;
681 static _H<UIFont> Font14_;
682 static _H<UIFont> Font18Bold_;
683 static _H<UIFont> Font22Bold_;
685 static const char *Machine_ = NULL;
686 static NSString *System_ = nil;
687 static NSString *SerialNumber_ = nil;
688 static NSString *ChipID_ = nil;
689 static NSString *BBSNum_ = nil;
690 static _H<NSString> Token_;
691 static NSString *UniqueID_ = nil;
692 static NSString *PLMN_ = nil;
693 static NSString *Build_ = nil;
694 static NSString *Product_ = nil;
695 static NSString *Safari_ = nil;
697 static CFLocaleRef Locale_;
698 static NSArray *Languages_;
699 static CGColorSpaceRef space_;
701 static NSDictionary *SectionMap_;
702 static NSMutableDictionary *Metadata_;
703 static _transient NSMutableDictionary *Settings_;
704 static _transient NSString *Role_;
705 static _transient NSMutableDictionary *Packages_;
706 static _transient NSMutableDictionary *Values_;
707 static _transient NSMutableDictionary *Sections_;
708 static _transient NSMutableDictionary *Sources_;
709 static _transient NSNumber *Version_;
710 static _transient _H<NSString> CydiaSource_;
711 static bool Changed_;
715 static CGFloat ScreenScale_;
716 static NSString *Idiom_;
717 static NSString *Firmware_;
719 static _H<NSMutableDictionary> SessionData_;
720 static _H<NSObject> HostConfig_;
721 static _H<NSMutableSet> BridgedHosts_;
722 static _H<NSMutableSet> TokenHosts_;
723 static _H<NSMutableSet> InsecureHosts_;
724 static _H<NSMutableSet> PipelinedHosts_;
725 static _H<NSMutableSet> CachedURLs_;
727 static NSString *kCydiaProgressEventTypeError = @"Error";
728 static NSString *kCydiaProgressEventTypeInformation = @"Information";
729 static NSString *kCydiaProgressEventTypeStatus = @"Status";
730 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
733 static void AddSource(NSDictionary *source) {
734 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
738 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
739 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
742 distribution, @"Distribution",
743 sections ?: [NSMutableArray array], @"Sections",
747 static void WriteSources() {
748 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
749 _assert(file != NULL);
751 NSString *distribution(@"ios");
752 if (Firmware_ != nil)
753 distribution = [distribution stringByAppendingString:[NSString stringWithFormat:@"-%@", Firmware_]];
755 fprintf(file, "deb http://%s/ %s main\n",
756 [CydiaSource_ UTF8String],
757 [distribution UTF8String]
760 for (NSString *key in [Sources_ allKeys]) {
761 NSDictionary *source([Sources_ objectForKey:key]);
763 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
765 fprintf(file, "%s %s %s%s%s\n",
766 [[source objectForKey:@"Type"] UTF8String],
767 [[source objectForKey:@"URI"] UTF8String],
768 [[source objectForKey:@"Distribution"] UTF8String],
769 [sections count] == 0 ? "" : " ",
770 [[sections componentsJoinedByString:@" "] UTF8String]
777 /* Display Helpers {{{ */
778 inline float Interpolate(float begin, float end, float fraction) {
779 return (end - begin) * fraction + begin;
782 static _finline const char *StripVersion_(const char *version) {
783 const char *colon(strchr(version, ':'));
784 return colon == NULL ? version : colon + 1;
787 NSString *LocalizeSection(NSString *section) {
788 static Pcre title_r("^(.*?) \\((.*)\\)$");
789 if (title_r(section)) {
790 NSString *parent(title_r[1]);
791 NSString *child(title_r[2]);
793 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
794 LocalizeSection(parent),
795 LocalizeSection(child)
799 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
802 NSString *Simplify(NSString *title) {
803 const char *data = [title UTF8String];
804 size_t size = [title length];
806 static Pcre square_r("^\\[(.*)\\]$");
807 if (square_r(data, size))
808 return Simplify(square_r[1]);
810 static Pcre paren_r("^\\((.*)\\)$");
811 if (paren_r(data, size))
812 return Simplify(paren_r[1]);
814 static Pcre title_r("^(.*?) \\((.*)\\)$");
815 if (title_r(data, size))
816 return Simplify(title_r[1]);
822 NSString *GetLastUpdate() {
823 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
826 return UCLocalize("NEVER_OR_UNKNOWN");
828 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
829 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
831 CFRelease(formatter);
833 return [(NSString *) formatted autorelease];
836 bool isSectionVisible(NSString *section) {
837 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
838 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
839 return hidden == nil || ![hidden boolValue];
842 static NSObject *CYIOGetValue(const char *path, NSString *property) {
843 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
844 if (entry == MACH_PORT_NULL)
847 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
848 IOObjectRelease(entry);
852 return [(id) value autorelease];
855 static NSString *CYHex(NSData *data, bool reverse = false) {
859 size_t length([data length]);
860 uint8_t bytes[length];
861 [data getBytes:bytes];
863 char string[length * 2 + 1];
864 for (size_t i(0); i != length; ++i)
865 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
867 return [NSString stringWithUTF8String:string];
872 /* Delegate Prototypes {{{ */
875 @class CydiaProgressEvent;
877 @protocol DatabaseDelegate
878 - (void) repairWithSelector:(SEL)selector;
879 - (void) setConfigurationData:(NSString *)data;
880 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
883 @class CYPackageController;
885 @protocol CydiaDelegate
886 - (void) returnToCydia;
888 - (void) retainNetworkActivityIndicator;
889 - (void) releaseNetworkActivityIndicator;
890 - (void) clearPackage:(Package *)package;
891 - (void) installPackage:(Package *)package;
892 - (void) installPackages:(NSArray *)packages;
893 - (void) removePackage:(Package *)package;
894 - (void) beginUpdate;
896 - (void) distUpgrade;
900 - (void) addSource:(NSDictionary *)source;
901 - (void) addTrivialSource:(NSString *)href;
902 - (void) showSettings;
903 - (UIProgressHUD *) addProgressHUD;
904 - (void) removeProgressHUD:(UIProgressHUD *)hud;
905 - (CyteViewController *) pageForPackage:(NSString *)name;
906 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
907 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
911 /* Status Delegation {{{ */
913 public pkgAcquireStatus
916 _transient NSObject<ProgressDelegate> *delegate_;
926 void setDelegate(NSObject<ProgressDelegate> *delegate) {
927 delegate_ = delegate;
930 NSObject<ProgressDelegate> *getDelegate() const {
934 virtual bool MediaChange(std::string media, std::string drive) {
938 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
942 virtual void Fetch(pkgAcquire::ItemDesc &item) {
943 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
944 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
945 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
948 virtual void Done(pkgAcquire::ItemDesc &item) {
949 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
950 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
951 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
954 virtual void Fail(pkgAcquire::ItemDesc &item) {
956 item.Owner->Status == pkgAcquire::Item::StatIdle ||
957 item.Owner->Status == pkgAcquire::Item::StatDone
961 std::string &error(item.Owner->ErrorText);
965 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
966 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
969 virtual bool Pulse(pkgAcquire *Owner) {
970 bool value = pkgAcquireStatus::Pulse(Owner);
973 double(CurrentBytes + CurrentItems) /
974 double(TotalBytes + TotalItems)
977 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
978 [NSNumber numberWithDouble:percent], @"Percent",
980 [NSNumber numberWithDouble:CurrentBytes], @"Current",
981 [NSNumber numberWithDouble:TotalBytes], @"Total",
982 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
983 nil] waitUntilDone:YES];
985 if (value && ![delegate_ isProgressCancelled])
993 _finline bool WasCancelled() const {
997 virtual void Start() {
998 pkgAcquireStatus::Start();
999 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1002 virtual void Stop() {
1003 pkgAcquireStatus::Stop();
1004 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1005 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1009 /* Database Interface {{{ */
1010 typedef std::map< unsigned long, _H<Source> > SourceMap;
1012 @interface Database : NSObject {
1018 pkgCacheFile cache_;
1019 pkgDepCache::Policy *policy_;
1020 pkgRecords *records_;
1021 pkgProblemResolver *resolver_;
1022 pkgAcquire *fetcher_;
1024 SPtr<pkgPackageManager> manager_;
1025 pkgSourceList *list_;
1027 SourceMap sourceMap_;
1028 _H<NSMutableArray> sourceList_;
1030 CFMutableArrayRef packages_;
1032 _transient NSObject<DatabaseDelegate> *delegate_;
1033 _transient NSObject<ProgressDelegate> *progress_;
1041 std::map<const char *, _H<NSString> > sections_;
1044 + (Database *) sharedInstance;
1047 - (void) _readCydia:(NSNumber *)fd;
1048 - (void) _readStatus:(NSNumber *)fd;
1049 - (void) _readOutput:(NSNumber *)fd;
1053 - (Package *) packageWithName:(NSString *)name;
1055 - (pkgCacheFile &) cache;
1056 - (pkgDepCache::Policy *) policy;
1057 - (pkgRecords *) records;
1058 - (pkgProblemResolver *) resolver;
1059 - (pkgAcquire &) fetcher;
1060 - (pkgSourceList &) list;
1061 - (NSArray *) packages;
1062 - (NSArray *) sources;
1063 - (Source *) sourceWithKey:(NSString *)key;
1064 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1072 - (void) updateWithStatus:(Status &)status;
1074 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1076 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1077 - (NSObject<ProgressDelegate> *) progressDelegate;
1079 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1081 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1085 /* ProgressEvent Implementation {{{ */
1086 @implementation CydiaProgressEvent
1088 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1089 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1092 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1093 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1094 [event setPackage:package];
1098 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1099 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1101 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1102 NSArray *fields([description componentsSeparatedByString:@" "]);
1103 [event setItem:fields];
1105 if ([fields count] > 3) {
1106 [event setPackage:[fields objectAtIndex:2]];
1107 [event setVersion:[fields objectAtIndex:3]];
1110 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1115 + (NSArray *) _attributeKeys {
1116 return [NSArray arrayWithObjects:
1126 - (NSArray *) attributeKeys {
1127 return [[self class] _attributeKeys];
1130 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1131 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1134 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1135 if ((self = [super init]) != nil) {
1141 - (NSString *) message {
1145 - (NSString *) type {
1149 - (NSArray *) item {
1150 return (id) item_ ?: [NSNull null];
1153 - (void) setItem:(NSArray *)item {
1157 - (NSString *) package {
1158 return (id) package_ ?: [NSNull null];
1161 - (void) setPackage:(NSString *)package {
1165 - (NSString *) url {
1166 return (id) url_ ?: [NSNull null];
1169 - (void) setURL:(NSString *)url {
1173 - (void) setVersion:(NSString *)version {
1177 - (NSString *) version {
1178 return (id) version_ ?: [NSNull null];
1181 - (NSString *) compound:(NSString *)value {
1183 NSString *mode(nil); {
1184 NSString *type([self type]);
1185 if ([type isEqualToString:kCydiaProgressEventTypeError])
1186 mode = UCLocalize("ERROR");
1187 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1188 mode = UCLocalize("WARNING");
1192 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1198 - (NSString *) compoundMessage {
1199 return [self compound:[self message]];
1202 - (NSString *) compoundTitle {
1205 if (package_ == nil)
1207 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1208 title = [package name];
1212 return [self compound:title];
1218 // Cytore Definitions {{{
1219 struct PackageValue :
1222 Cytore::Offset<PackageValue> next_;
1224 uint32_t index_ : 23;
1225 uint32_t subscribed_ : 1;
1242 Cytore::Offset<PackageValue> packages_[1 << 16];
1245 static Cytore::File<MetaValue> MetaFile_;
1247 // Cytore Helper Functions {{{
1248 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1249 SplitHash nhash = { hashlittle(name, length) };
1251 PackageValue *metadata;
1253 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1254 offset: if (offset->IsNull()) {
1255 *offset = MetaFile_.New<PackageValue>(length + 1);
1256 metadata = &MetaFile_.Get(*offset);
1258 if (metadata == NULL) {
1262 metadata = new PackageValue();
1263 memset(metadata, 0, sizeof(*metadata));
1266 memcpy(metadata->name_, name, length + 1);
1267 metadata->nhash_ = nhash.u16[1];
1269 metadata = &MetaFile_.Get(*offset);
1271 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1272 offset = &metadata->next_;
1280 static void PackageImport(const void *key, const void *value, void *context) {
1281 bool &fail(*reinterpret_cast<bool *>(context));
1284 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1285 NSLog(@"failed to import package %@", key);
1289 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1290 NSDictionary *package((NSDictionary *) value);
1292 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1293 if ([subscribed boolValue] && !metadata->subscribed_)
1294 metadata->subscribed_ = true;
1296 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1297 time_t time([date timeIntervalSince1970]);
1298 if (metadata->first_ > time || metadata->first_ == 0)
1299 metadata->first_ = time;
1302 NSDate *date([package objectForKey:@"LastSeen"]);
1303 NSString *version([package objectForKey:@"LastVersion"]);
1305 if (date != nil && version != nil) {
1306 time_t time([date timeIntervalSince1970]);
1307 if (metadata->last_ < time || metadata->last_ == 0)
1308 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1309 size_t length(strlen(buffer));
1310 uint16_t vhash(hashlittle(buffer, length));
1312 size_t capped(std::min<size_t>(8, length));
1313 char *latest(buffer + length - capped);
1315 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1316 metadata->vhash_ = vhash;
1318 metadata->last_ = time;
1324 /* Source Class {{{ */
1325 @interface Source : NSObject {
1327 Database *database_;
1330 CYString depiction_;
1331 CYString description_;
1337 CYString distribution_;
1343 _H<NSString> authority_;
1345 CYString defaultIcon_;
1347 _H<NSDictionary> record_;
1351 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1353 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1355 - (NSString *) depictionForPackage:(NSString *)package;
1356 - (NSString *) supportForPackage:(NSString *)package;
1358 - (NSDictionary *) record;
1362 - (NSString *) distribution;
1363 - (NSString *) type;
1365 - (NSString *) base;
1368 - (NSString *) host;
1370 - (NSString *) name;
1371 - (NSString *) shortDescription;
1372 - (NSString *) label;
1373 - (NSString *) origin;
1374 - (NSString *) version;
1376 - (NSString *) defaultIcon;
1380 @implementation Source
1384 distribution_.clear();
1389 description_.clear();
1395 defaultIcon_.clear();
1402 + (NSString *) webScriptNameForSelector:(SEL)selector {
1404 else if (selector == @selector(addSection:))
1405 return @"addSection";
1406 else if (selector == @selector(getField:))
1408 else if (selector == @selector(removeSection:))
1409 return @"removeSection";
1410 else if (selector == @selector(remove))
1416 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1417 return [self webScriptNameForSelector:selector] == nil;
1420 + (NSArray *) _attributeKeys {
1421 return [NSArray arrayWithObjects:
1429 @"shortDescription",
1437 - (NSArray *) attributeKeys {
1438 return [[self class] _attributeKeys];
1441 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1442 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1445 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1448 trusted_ = index->IsTrusted();
1450 uri_.set(pool, index->GetURI());
1451 distribution_.set(pool, index->GetDist());
1452 type_.set(pool, index->GetType());
1454 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1455 if (dindex != NULL) {
1456 base_.set(pool, dindex->MetaIndexURI(""));
1459 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1462 pkgTagFile tags(&fd);
1464 pkgTagSection section;
1471 {"default-icon", &defaultIcon_},
1472 {"depiction", &depiction_},
1473 {"description", &description_},
1475 {"origin", &origin_},
1476 {"support", &support_},
1477 {"version", &version_},
1480 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1481 const char *start, *end;
1483 if (section.Find(names[i].name_, start, end)) {
1484 CYString &value(*names[i].value_);
1485 value.set(pool, start, end - start);
1491 record_ = [Sources_ objectForKey:[self key]];
1493 NSURL *url([NSURL URLWithString:uri_]);
1497 host_ = [host_ lowercaseString];
1502 authority_ = [url path];
1505 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1506 if ((self = [super init]) != nil) {
1507 era_ = [database era];
1508 database_ = database;
1511 [self setMetaIndex:index inPool:pool];
1515 - (NSString *) getField:(NSString *)name {
1516 @synchronized (database_) {
1517 if ([database_ era] != era_ || index_ == NULL)
1520 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1525 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1530 pkgTagFile tags(&fd);
1532 pkgTagSection section;
1535 const char *start, *end;
1536 if (!section.Find([name UTF8String], start, end))
1537 return (NSString *) [NSNull null];
1539 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1542 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1543 NSDictionary *lhr = [self record];
1544 NSDictionary *rhr = [source record];
1546 if ((lhr == nil) != (rhr == nil))
1547 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1549 NSString *lhs = [self name];
1550 NSString *rhs = [source name];
1552 if ([lhs length] != 0 && [rhs length] != 0) {
1553 unichar lhc = [lhs characterAtIndex:0];
1554 unichar rhc = [rhs characterAtIndex:0];
1556 if (isalpha(lhc) && !isalpha(rhc))
1557 return NSOrderedAscending;
1558 else if (!isalpha(lhc) && isalpha(rhc))
1559 return NSOrderedDescending;
1562 return [lhs compare:rhs options:LaxCompareOptions_];
1565 - (NSString *) depictionForPackage:(NSString *)package {
1566 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1569 - (NSString *) supportForPackage:(NSString *)package {
1570 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1573 - (NSArray *) sections {
1574 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1577 - (void) _addSection:(NSString *)section {
1580 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1581 if (![sections containsObject:section]) {
1582 [sections addObject:section];
1586 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1591 - (bool) addSection:(NSString *)section {
1595 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1599 - (void) _removeSection:(NSString *)section {
1603 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1604 if ([sections containsObject:section]) {
1605 [sections removeObject:section];
1610 - (bool) removeSection:(NSString *)section {
1614 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1619 [Sources_ removeObjectForKey:[self key]];
1624 bool value(record_ != nil);
1625 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1629 - (NSDictionary *) record {
1637 - (NSString *) uri {
1641 - (NSString *) distribution {
1642 return distribution_;
1645 - (NSString *) type {
1649 - (NSString *) base {
1653 - (NSString *) key {
1654 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1657 - (NSString *) host {
1661 - (NSString *) name {
1662 return origin_.empty() ? (id) authority_ : origin_;
1665 - (NSString *) shortDescription {
1666 return description_;
1669 - (NSString *) label {
1670 return label_.empty() ? (id) authority_ : label_;
1673 - (NSString *) origin {
1677 - (NSString *) version {
1681 - (NSString *) defaultIcon {
1682 return defaultIcon_;
1687 /* CydiaOperation Class {{{ */
1688 @interface CydiaOperation : NSObject {
1689 _H<NSString> operator_;
1690 _H<NSString> value_;
1693 - (NSString *) operator;
1694 - (NSString *) value;
1698 @implementation CydiaOperation
1700 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1701 if ((self = [super init]) != nil) {
1702 operator_ = [NSString stringWithUTF8String:_operator];
1703 value_ = [NSString stringWithUTF8String:value];
1707 + (NSArray *) _attributeKeys {
1708 return [NSArray arrayWithObjects:
1714 - (NSArray *) attributeKeys {
1715 return [[self class] _attributeKeys];
1718 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1719 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1722 - (NSString *) operator {
1726 - (NSString *) value {
1732 /* CydiaClause Class {{{ */
1733 @interface CydiaClause : NSObject {
1734 _H<NSString> package_;
1735 _H<CydiaOperation> version_;
1738 - (NSString *) package;
1739 - (CydiaOperation *) version;
1743 @implementation CydiaClause
1745 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1746 if ((self = [super init]) != nil) {
1747 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1749 if (const char *version = dep.TargetVer())
1750 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1752 version_ = (id) [NSNull null];
1756 + (NSArray *) _attributeKeys {
1757 return [NSArray arrayWithObjects:
1763 - (NSArray *) attributeKeys {
1764 return [[self class] _attributeKeys];
1767 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1768 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1771 - (NSString *) package {
1775 - (CydiaOperation *) version {
1781 /* CydiaRelation Class {{{ */
1782 @interface CydiaRelation : NSObject {
1783 _H<NSString> relationship_;
1784 _H<NSMutableArray> clauses_;
1787 - (NSString *) relationship;
1788 - (NSArray *) clauses;
1792 @implementation CydiaRelation
1794 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1795 if ((self = [super init]) != nil) {
1796 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1797 clauses_ = [NSMutableArray arrayWithCapacity:8];
1799 pkgCache::DepIterator start;
1800 pkgCache::DepIterator end;
1801 dep.GlobOr(start, end); // ++dep
1804 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1806 // yes, seriously. (wtf?)
1814 + (NSArray *) _attributeKeys {
1815 return [NSArray arrayWithObjects:
1821 - (NSArray *) attributeKeys {
1822 return [[self class] _attributeKeys];
1825 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1826 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1829 - (NSString *) relationship {
1830 return relationship_;
1833 - (NSArray *) clauses {
1837 - (void) addClause:(CydiaClause *)clause {
1838 [clauses_ addObject:clause];
1843 /* Package Class {{{ */
1844 struct ParsedPackage {
1847 CYString architecture_;
1850 CYString depiction_;
1860 @interface Package : NSObject {
1863 uint32_t essential_ : 1;
1864 uint32_t obsolete_ : 1;
1865 uint32_t ignored_ : 1;
1871 _transient Database *database_;
1873 pkgCache::VerIterator version_;
1874 pkgCache::PkgIterator iterator_;
1875 pkgCache::VerFileIterator file_;
1881 CYString installed_;
1883 const char *section_;
1884 _transient NSString *section$_;
1888 PackageValue *metadata_;
1889 ParsedPackage *parsed_;
1891 _H<NSMutableArray> tags_;
1894 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1895 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1897 - (pkgCache::PkgIterator) iterator;
1900 - (NSString *) section;
1901 - (NSString *) simpleSection;
1903 - (NSString *) longSection;
1904 - (NSString *) shortSection;
1908 - (MIMEAddress *) maintainer;
1910 - (NSString *) longDescription;
1911 - (NSString *) shortDescription;
1914 - (PackageValue *) metadata;
1917 - (bool) subscribed;
1918 - (bool) setSubscribed:(bool)subscribed;
1922 - (NSString *) latest;
1923 - (NSString *) installed;
1924 - (BOOL) uninstalled;
1927 - (BOOL) upgradableAndEssential:(BOOL)essential;
1930 - (BOOL) unfiltered;
1934 - (BOOL) halfConfigured;
1935 - (BOOL) halfInstalled;
1937 - (NSString *) mode;
1940 - (NSString *) name;
1942 - (NSString *) homepage;
1943 - (NSString *) depiction;
1944 - (MIMEAddress *) author;
1946 - (NSString *) support;
1948 - (NSArray *) files;
1949 - (NSArray *) warnings;
1950 - (NSArray *) applications;
1952 - (Source *) source;
1955 - (BOOL) matches:(NSArray *)query;
1957 - (bool) hasSupportingRole;
1958 - (BOOL) hasTag:(NSString *)tag;
1959 - (NSString *) primaryPurpose;
1960 - (NSArray *) purposes;
1961 - (bool) isCommercial;
1963 - (void) setIndex:(size_t)index;
1965 - (CYString &) cyname;
1967 - (uint32_t) compareBySection:(NSArray *)sections;
1972 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1973 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1974 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1975 - (bool) isVisibleInSection:(NSString *)section;
1976 - (bool) isVisibleInSource:(Source *)source;
1980 uint32_t PackageChangesRadix(Package *self, void *) {
1985 uint32_t timestamp : 30;
1986 uint32_t ignored : 1;
1987 uint32_t upgradable : 1;
1991 bool upgradable([self upgradableAndEssential:YES]);
1992 value.bits.upgradable = upgradable ? 1 : 0;
1995 value.bits.timestamp = 0;
1996 value.bits.ignored = [self ignored] ? 0 : 1;
1997 value.bits.upgradable = 1;
1999 value.bits.timestamp = [self seen] >> 2;
2000 value.bits.ignored = 0;
2001 value.bits.upgradable = 0;
2004 return _not(uint32_t) - value.key;
2007 uint32_t PackagePrefixRadix(Package *self, void *context) {
2008 size_t offset(reinterpret_cast<size_t>(context));
2009 CYString &name([self cyname]);
2011 size_t size(name.size());
2014 char *text(name.data());
2017 if (!isdigit(text[0]))
2021 while (size != digits && isdigit(text[digits]))
2029 if (offset == 0 && zeros != 0) {
2030 memset(data, '0', zeros);
2031 memcpy(data + zeros, text, 4 - zeros);
2033 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2034 if (size <= offset - zeros)
2037 text += offset - zeros;
2038 size -= offset - zeros;
2041 memcpy(data, text, 4);
2043 memcpy(data, text, size);
2044 memset(data + size, 0, 4 - size);
2047 for (size_t i(0); i != 4; ++i)
2048 if (isalpha(data[i]))
2056 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2058 /* XXX: ntohl may be more honest */
2059 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2062 CYString &(*PackageName)(Package *self, SEL sel);
2064 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2065 _profile(PackageNameCompare)
2066 CYString &lhi(PackageName(lhs, @selector(cyname)));
2067 CYString &rhi(PackageName(rhs, @selector(cyname)));
2068 CFStringRef lhn(lhi), rhn(rhi);
2071 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2072 else if (rhn == NULL)
2073 return NSOrderedDescending;
2075 _profile(PackageNameCompare$NumbersLast)
2076 if (!lhi.empty() && !rhi.empty()) {
2077 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2078 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2079 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2080 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2081 return lha ? NSOrderedAscending : NSOrderedDescending;
2085 CFIndex length = CFStringGetLength(lhn);
2087 _profile(PackageNameCompare$Compare)
2088 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2093 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2094 return PackageNameCompare(*lhs, *rhs, context);
2097 struct PackageNameOrdering :
2098 std::binary_function<Package *, Package *, bool>
2100 _finline bool operator ()(Package *lhs, Package *rhs) const {
2101 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2105 @implementation Package
2107 - (NSString *) description {
2108 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2112 if (parsed_ != NULL)
2117 + (NSString *) webScriptNameForSelector:(SEL)selector {
2119 else if (selector == @selector(clear))
2121 else if (selector == @selector(getField:))
2123 else if (selector == @selector(hasTag:))
2125 else if (selector == @selector(install))
2127 else if (selector == @selector(remove))
2133 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2134 return [self webScriptNameForSelector:selector] == nil;
2137 + (NSArray *) _attributeKeys {
2138 return [NSArray arrayWithObjects:
2158 @"shortDescription",
2171 - (NSArray *) attributeKeys {
2172 return [[self class] _attributeKeys];
2175 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2176 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2179 - (NSArray *) relations {
2180 @synchronized (database_) {
2181 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2182 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2183 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2187 - (NSString *) architecture {
2189 @synchronized (database_) {
2190 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2193 - (NSString *) getField:(NSString *)name {
2194 @synchronized (database_) {
2195 if ([database_ era] != era_ || file_.end())
2198 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2200 const char *start, *end;
2201 if (!parser.Find([name UTF8String], start, end))
2202 return (NSString *) [NSNull null];
2204 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2208 if (parsed_ != NULL)
2210 @synchronized (database_) {
2211 if ([database_ era] != era_ || file_.end())
2214 ParsedPackage *parsed(new ParsedPackage);
2217 _profile(Package$parse)
2218 pkgRecords::Parser *parser;
2220 _profile(Package$parse$Lookup)
2221 parser = &[database_ records]->Lookup(file_);
2226 _profile(Package$parse$Find)
2231 {"architecture", &parsed->architecture_},
2232 {"icon", &parsed->icon_},
2233 {"depiction", &parsed->depiction_},
2234 {"homepage", &parsed->homepage_},
2235 {"website", &website},
2236 {"bugs", &parsed->bugs_},
2237 {"support", &parsed->support_},
2238 {"sponsor", &parsed->sponsor_},
2239 {"author", &parsed->author_},
2242 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2243 const char *start, *end;
2245 if (parser->Find(names[i].name_, start, end)) {
2246 CYString &value(*names[i].value_);
2247 _profile(Package$parse$Value)
2248 value.set(pool_, start, end - start);
2254 _profile(Package$parse$Tagline)
2255 const char *start, *end;
2256 if (parser->ShortDesc(start, end)) {
2257 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2260 while (stop != start && stop[-1] == '\r')
2262 parsed->tagline_.set(pool_, start, stop - start);
2266 _profile(Package$parse$Retain)
2267 if (parsed->homepage_.empty())
2268 parsed->homepage_ = website;
2269 if (parsed->homepage_ == parsed->depiction_)
2270 parsed->homepage_.clear();
2275 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2276 if ((self = [super init]) != nil) {
2277 _profile(Package$initWithVersion)
2280 database_ = database;
2281 era_ = [database era];
2285 pkgCache::PkgIterator iterator(version.ParentPkg());
2286 iterator_ = iterator;
2288 _profile(Package$initWithVersion$Version)
2289 if (!version_.end())
2290 file_ = version_.FileList();
2292 pkgCache &cache([database_ cache]);
2293 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2297 _profile(Package$initWithVersion$Cache)
2298 name_.set(NULL, iterator.Display());
2300 latest_.set(NULL, StripVersion_(version_.VerStr()));
2302 pkgCache::VerIterator current(iterator.CurrentVer());
2304 installed_.set(NULL, StripVersion_(current.VerStr()));
2307 _profile(Package$initWithVersion$Tags)
2308 pkgCache::TagIterator tag(iterator.TagList());
2310 tags_ = [NSMutableArray arrayWithCapacity:8];
2312 const char *name(tag.Name());
2313 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2315 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2316 if (strcmp(name + 6, "enduser") == 0)
2318 else if (strcmp(name + 6, "hacker") == 0)
2320 else if (strcmp(name + 6, "developer") == 0)
2322 else if (strcmp(name + 6, "cydia") == 0)
2328 if (strncmp(name, "cydia::", 7) == 0) {
2329 if (strcmp(name + 7, "essential") == 0)
2331 else if (strcmp(name + 7, "obsolete") == 0)
2336 } while (!tag.end());
2340 _profile(Package$initWithVersion$Metadata)
2341 const char *mixed(iterator.Name());
2342 size_t size(strlen(mixed));
2343 char lower[size + 1];
2345 for (size_t i(0); i != size; ++i)
2346 lower[i] = mixed[i] | 0x20;
2349 PackageValue *metadata(PackageFind(lower, size));
2350 metadata_ = metadata;
2352 id_.set(NULL, metadata->name_, size);
2354 const char *latest(version_.VerStr());
2355 size_t length(strlen(latest));
2357 uint16_t vhash(hashlittle(latest, length));
2359 size_t capped(std::min<size_t>(8, length));
2360 latest = latest + length - capped;
2362 if (metadata->first_ == 0)
2363 metadata->first_ = now_;
2365 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2366 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2367 metadata->vhash_ = vhash;
2368 metadata->last_ = now_;
2369 } else if (metadata->last_ == 0)
2370 metadata->last_ = metadata->first_;
2373 _profile(Package$initWithVersion$Section)
2374 section_ = iterator.Section();
2377 _profile(Package$initWithVersion$Flags)
2378 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2379 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2384 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2385 pkgCache::VerIterator version;
2387 _profile(Package$packageWithIterator$GetCandidateVer)
2388 version = [database policy]->GetCandidateVer(iterator);
2396 _profile(Package$packageWithIterator$Allocate)
2397 package = [Package allocWithZone:zone];
2400 _profile(Package$packageWithIterator$Initialize)
2402 initWithVersion:version
2409 _profile(Package$packageWithIterator$Autorelease)
2410 package = [package autorelease];
2416 - (pkgCache::PkgIterator) iterator {
2420 - (NSString *) section {
2421 if (section$_ == nil) {
2422 if (section_ == NULL)
2425 _profile(Package$section$mappedSectionForPointer)
2426 section$_ = [database_ mappedSectionForPointer:section_];
2431 - (NSString *) simpleSection {
2432 if (NSString *section = [self section])
2433 return Simplify(section);
2438 - (NSString *) longSection {
2439 return LocalizeSection([self section]);
2442 - (NSString *) shortSection {
2443 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2446 - (NSString *) uri {
2449 pkgIndexFile *index;
2450 pkgCache::PkgFileIterator file(file_.File());
2451 if (![database_ list].FindIndex(file, index))
2453 return [NSString stringWithUTF8String:iterator_->Path];
2454 //return [NSString stringWithUTF8String:file.Site()];
2455 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2459 - (MIMEAddress *) maintainer {
2460 @synchronized (database_) {
2461 if ([database_ era] != era_ || file_.end())
2464 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2465 const std::string &maintainer(parser->Maintainer());
2466 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2470 @synchronized (database_) {
2471 if ([database_ era] != era_ || version_.end())
2474 return version_->InstalledSize;
2477 - (NSString *) longDescription {
2478 @synchronized (database_) {
2479 if ([database_ era] != era_ || file_.end())
2482 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2483 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2485 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2486 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2487 if ([lines count] < 2)
2490 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2491 for (size_t i(1), e([lines count]); i != e; ++i) {
2492 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2493 [trimmed addObject:trim];
2496 return [trimmed componentsJoinedByString:@"\n"];
2499 - (NSString *) shortDescription {
2500 if (parsed_ != NULL)
2501 return static_cast<NSString *>(parsed_->tagline_);
2503 @synchronized (database_) {
2504 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2506 const char *start, *end;
2507 if (!parser.ShortDesc(start, end))
2510 if (end - start > 200)
2514 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2517 while (end != start && end[-1] == '\r')
2521 return [(id) CYStringCreate(start, end - start) autorelease];
2525 _profile(Package$index)
2526 CFStringRef name((CFStringRef) [self name]);
2527 if (CFStringGetLength(name) == 0)
2529 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2530 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2532 return toupper(character);
2536 - (PackageValue *) metadata {
2541 PackageValue *metadata([self metadata]);
2542 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2545 - (bool) subscribed {
2546 return [self metadata]->subscribed_;
2549 - (bool) setSubscribed:(bool)subscribed {
2550 PackageValue *metadata([self metadata]);
2551 if (metadata->subscribed_ == subscribed)
2553 metadata->subscribed_ = subscribed;
2561 - (NSString *) latest {
2565 - (NSString *) installed {
2569 - (BOOL) uninstalled {
2570 return installed_.empty();
2574 return !version_.end();
2577 - (BOOL) upgradableAndEssential:(BOOL)essential {
2578 _profile(Package$upgradableAndEssential)
2579 pkgCache::VerIterator current(iterator_.CurrentVer());
2581 return essential && essential_;
2583 return !version_.end() && version_ != current;
2587 - (BOOL) essential {
2592 return [database_ cache][iterator_].InstBroken();
2595 - (BOOL) unfiltered {
2596 _profile(Package$unfiltered$obsolete)
2597 if (_unlikely(obsolete_))
2601 _profile(Package$unfiltered$hasSupportingRole)
2602 if (_unlikely(![self hasSupportingRole]))
2610 if (![self unfiltered])
2615 _profile(Package$visible$section)
2616 section = [self section];
2619 _profile(Package$visible$isSectionVisible)
2620 if (!isSectionVisible(section))
2628 unsigned char current(iterator_->CurrentState);
2629 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2632 - (BOOL) halfConfigured {
2633 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2636 - (BOOL) halfInstalled {
2637 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2641 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2642 return state.Mode != pkgDepCache::ModeKeep;
2645 - (NSString *) mode {
2646 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2648 switch (state.Mode) {
2649 case pkgDepCache::ModeDelete:
2650 if ((state.iFlags & pkgDepCache::Purge) != 0)
2654 case pkgDepCache::ModeKeep:
2655 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2656 return @"REINSTALL";
2657 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2661 case pkgDepCache::ModeInstall:
2662 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2663 return @"REINSTALL";
2664 else*/ switch (state.Status) {
2666 return @"DOWNGRADE";
2672 return @"NEW_INSTALL";
2683 - (NSString *) name {
2684 return name_.empty() ? id_ : name_;
2687 - (UIImage *) icon {
2688 NSString *section = [self simpleSection];
2691 if (parsed_ != NULL)
2692 if (NSString *href = parsed_->icon_)
2693 if ([href hasPrefix:@"file:///"])
2694 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2695 if (icon == nil) if (section != nil)
2696 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2697 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2698 if ([dicon hasPrefix:@"file:///"])
2699 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2701 icon = [UIImage applicationImageNamed:@"unknown.png"];
2705 - (NSString *) homepage {
2706 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2709 - (NSString *) depiction {
2710 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2713 - (MIMEAddress *) sponsor {
2714 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2717 - (MIMEAddress *) author {
2718 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2721 - (NSString *) support {
2722 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2725 - (NSArray *) files {
2726 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2727 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2730 fin.open([path UTF8String]);
2735 while (std::getline(fin, line))
2736 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2741 - (NSString *) state {
2742 @synchronized (database_) {
2743 if ([database_ era] != era_ || file_.end())
2746 switch (iterator_->CurrentState) {
2747 case pkgCache::State::NotInstalled:
2748 return @"NotInstalled";
2749 case pkgCache::State::UnPacked:
2751 case pkgCache::State::HalfConfigured:
2752 return @"HalfConfigured";
2753 case pkgCache::State::HalfInstalled:
2754 return @"HalfInstalled";
2755 case pkgCache::State::ConfigFiles:
2756 return @"ConfigFiles";
2757 case pkgCache::State::Installed:
2758 return @"Installed";
2759 case pkgCache::State::TriggersAwaited:
2760 return @"TriggersAwaited";
2761 case pkgCache::State::TriggersPending:
2762 return @"TriggersPending";
2765 return (NSString *) [NSNull null];
2768 - (NSString *) selection {
2769 @synchronized (database_) {
2770 if ([database_ era] != era_ || file_.end())
2773 switch (iterator_->SelectedState) {
2774 case pkgCache::State::Unknown:
2776 case pkgCache::State::Install:
2778 case pkgCache::State::Hold:
2780 case pkgCache::State::DeInstall:
2781 return @"DeInstall";
2782 case pkgCache::State::Purge:
2786 return (NSString *) [NSNull null];
2789 - (NSArray *) warnings {
2790 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2791 const char *name(iterator_.Name());
2793 size_t length(strlen(name));
2794 if (length < 2) invalid:
2795 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2796 else for (size_t i(0); i != length; ++i)
2798 /* XXX: technically this is not allowed */
2799 (name[i] < 'A' || name[i] > 'Z') &&
2800 (name[i] < 'a' || name[i] > 'z') &&
2801 (name[i] < '0' || name[i] > '9') &&
2802 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2805 if (strcmp(name, "cydia") != 0) {
2808 bool _private = false;
2811 bool repository = [[self section] isEqualToString:@"Repositories"];
2813 if (NSArray *files = [self files])
2814 for (NSString *file in files)
2815 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2817 else if (!user && [file isEqualToString:@"/User"])
2819 else if (!_private && [file isEqualToString:@"/private"])
2821 else if (!stash && [file isEqualToString:@"/var/stash"])
2824 /* XXX: this is not sensitive enough. only some folders are valid. */
2825 if (cydia && !repository)
2826 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2828 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2830 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2832 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2835 return [warnings count] == 0 ? nil : warnings;
2838 - (NSArray *) applications {
2839 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2841 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2843 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2844 if (NSArray *files = [self files])
2845 for (NSString *file in files)
2846 if (application_r(file)) {
2847 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2848 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2849 if ([id isEqualToString:me])
2852 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2854 display = application_r[1];
2856 NSString *bundle([file stringByDeletingLastPathComponent]);
2857 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2858 if (icon == nil || [icon length] == 0)
2860 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2862 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2863 [applications addObject:application];
2865 [application addObject:id];
2866 [application addObject:display];
2867 [application addObject:url];
2870 return [applications count] == 0 ? nil : applications;
2873 - (Source *) source {
2874 if (source_ == nil) {
2875 @synchronized (database_) {
2876 if ([database_ era] != era_ || file_.end())
2877 source_ = (Source *) [NSNull null];
2879 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2883 return source_ == (Source *) [NSNull null] ? nil : source_;
2890 - (BOOL) matches:(NSArray *)query {
2891 if (query == nil || [query count] == 0)
2900 string = [self name];
2901 length = [string length];
2903 for (NSString *term in query) {
2904 range = [string rangeOfString:term options:MatchCompareOptions_];
2905 if (range.location != NSNotFound)
2906 rank_ -= 6 * 1000000 / length;
2911 length = [string length];
2913 for (NSString *term in query) {
2914 range = [string rangeOfString:term options:MatchCompareOptions_];
2915 if (range.location != NSNotFound)
2916 rank_ -= 6 * 1000000 / length;
2920 string = [self shortDescription];
2921 length = [string length];
2922 NSUInteger stop(std::min<NSUInteger>(length, 200));
2924 for (NSString *term in query) {
2925 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2926 if (range.location != NSNotFound)
2927 rank_ -= 2 * 100000;
2933 - (bool) hasSupportingRole {
2938 if ([Role_ isEqualToString:@"User"])
2942 if ([Role_ isEqualToString:@"Hacker"])
2946 if ([Role_ isEqualToString:@"Developer"])
2951 - (NSArray *) tags {
2955 - (BOOL) hasTag:(NSString *)tag {
2956 return tags_ == nil ? NO : [tags_ containsObject:tag];
2959 - (NSString *) primaryPurpose {
2960 for (NSString *tag in (NSArray *) tags_)
2961 if ([tag hasPrefix:@"purpose::"])
2962 return [tag substringFromIndex:9];
2966 - (NSArray *) purposes {
2967 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2968 for (NSString *tag in (NSArray *) tags_)
2969 if ([tag hasPrefix:@"purpose::"])
2970 [purposes addObject:[tag substringFromIndex:9]];
2971 return [purposes count] == 0 ? nil : purposes;
2974 - (bool) isCommercial {
2975 return [self hasTag:@"cydia::commercial"];
2978 - (void) setIndex:(size_t)index {
2979 if (metadata_->index_ != index)
2980 metadata_->index_ = index;
2983 - (CYString &) cyname {
2984 return name_.empty() ? id_ : name_;
2987 - (uint32_t) compareBySection:(NSArray *)sections {
2988 NSString *section([self section]);
2989 for (size_t i(0), e([sections count]); i != e; ++i) {
2990 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2994 return _not(uint32_t);
2998 @synchronized (database_) {
2999 pkgProblemResolver *resolver = [database_ resolver];
3000 resolver->Clear(iterator_);
3002 pkgCacheFile &cache([database_ cache]);
3003 cache->SetReInstall(iterator_, false);
3004 cache->MarkKeep(iterator_, false);
3008 @synchronized (database_) {
3009 pkgProblemResolver *resolver = [database_ resolver];
3010 resolver->Clear(iterator_);
3011 resolver->Protect(iterator_);
3013 pkgCacheFile &cache([database_ cache]);
3014 cache->SetReInstall(iterator_, false);
3015 cache->MarkInstall(iterator_, false);
3017 pkgDepCache::StateCache &state((*cache)[iterator_]);
3018 if (!state.Install())
3019 cache->SetReInstall(iterator_, true);
3023 @synchronized (database_) {
3024 pkgProblemResolver *resolver = [database_ resolver];
3025 resolver->Clear(iterator_);
3026 resolver->Remove(iterator_);
3027 resolver->Protect(iterator_);
3029 pkgCacheFile &cache([database_ cache]);
3030 cache->SetReInstall(iterator_, false);
3031 cache->MarkDelete(iterator_, true);
3034 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3035 _profile(Package$isUnfilteredAndSearchedForBy)
3038 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3039 value &= [self unfiltered];
3042 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3043 value &= [self matches:query];
3050 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3051 if ([search length] == 0)
3054 _profile(Package$isUnfilteredAndSelectedForBy)
3057 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3058 value &= [self unfiltered];
3061 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3062 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3069 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3070 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3073 - (bool) isVisibleInSection:(NSString *)name {
3074 NSString *section([self section]);
3078 section == nil && [name length] == 0 ||
3079 [name isEqualToString:section]
3080 ) && [self visible];
3083 - (bool) isVisibleInSource:(Source *)source {
3084 return [self source] == source && [self visible];
3089 /* Section Class {{{ */
3090 @interface Section : NSObject {
3095 _H<NSString> localized_;
3098 - (NSComparisonResult) compareByLocalized:(Section *)section;
3099 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3100 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3101 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3102 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3103 - (NSString *) name;
3110 - (void) addToCount;
3112 - (void) setCount:(size_t)count;
3113 - (NSString *) localized;
3117 @implementation Section
3119 - (NSComparisonResult) compareByLocalized:(Section *)section {
3120 NSString *lhs(localized_);
3121 NSString *rhs([section localized]);
3123 /*if ([lhs length] != 0 && [rhs length] != 0) {
3124 unichar lhc = [lhs characterAtIndex:0];
3125 unichar rhc = [rhs characterAtIndex:0];
3127 if (isalpha(lhc) && !isalpha(rhc))
3128 return NSOrderedAscending;
3129 else if (!isalpha(lhc) && isalpha(rhc))
3130 return NSOrderedDescending;
3133 return [lhs compare:rhs options:LaxCompareOptions_];
3136 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3137 if ((self = [self initWithName:name localize:NO]) != nil) {
3138 if (localized != nil)
3139 localized_ = localized;
3143 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3144 return [self initWithName:name row:0 localize:localize];
3147 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3148 if ((self = [super init]) != nil) {
3153 localized_ = LocalizeSection(name_);
3157 /* XXX: localize the index thingees */
3158 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3159 if ((self = [super init]) != nil) {
3160 name_ = [NSString stringWithCharacters:&index length:1];
3166 - (NSString *) name {
3186 - (void) addToCount {
3190 - (void) setCount:(size_t)count {
3194 - (NSString *) localized {
3201 class CydiaLogCleaner :
3202 public pkgArchiveCleaner
3205 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3210 /* Database Implementation {{{ */
3211 @implementation Database
3213 + (Database *) sharedInstance {
3214 static _H<Database> instance;
3215 if (instance == nil)
3216 instance = [[[Database alloc] init] autorelease];
3224 - (void) releasePackages {
3225 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3226 CFArrayRemoveAllValues(packages_);
3230 // XXX: actually implement this thing
3232 [self releasePackages];
3233 apr_pool_destroy(pool_);
3234 NSRecycleZone(zone_);
3238 - (void) _readCydia:(NSNumber *)fd {
3239 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3240 std::istream is(&ib);
3243 static Pcre finish_r("^finish:([^:]*)$");
3245 while (std::getline(is, line)) {
3246 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3248 const char *data(line.c_str());
3249 size_t size = line.size();
3250 lprintf("C:%s\n", data);
3252 if (finish_r(data, size)) {
3253 NSString *finish = finish_r[1];
3254 int index = [Finishes_ indexOfObject:finish];
3255 if (index != INT_MAX && index > Finish_)
3265 - (void) _readStatus:(NSNumber *)fd {
3266 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3267 std::istream is(&ib);
3270 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3271 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3273 while (std::getline(is, line)) {
3274 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3276 const char *data(line.c_str());
3277 size_t size(line.size());
3278 lprintf("S:%s\n", data);
3280 if (conffile_r(data, size)) {
3281 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3282 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3283 } else if (strncmp(data, "status: ", 8) == 0) {
3284 // status: <package>: {unpacked,half-configured,installed}
3285 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3286 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3287 } else if (strncmp(data, "processing: ", 12) == 0) {
3288 // processing: configure: config-test
3289 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3290 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3291 } else if (pmstatus_r(data, size)) {
3292 std::string type([pmstatus_r[1] UTF8String]);
3294 NSString *package = pmstatus_r[2];
3295 if ([package isEqualToString:@"dpkg-exec"])
3298 float percent([pmstatus_r[3] floatValue]);
3299 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3301 NSString *string = pmstatus_r[4];
3303 if (type == "pmerror") {
3304 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3305 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3306 } else if (type == "pmstatus") {
3307 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3308 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3309 } else if (type == "pmconffile")
3310 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3312 lprintf("E:unknown pmstatus\n");
3314 lprintf("E:unknown status\n");
3322 - (void) _readOutput:(NSNumber *)fd {
3323 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3324 std::istream is(&ib);
3327 while (std::getline(is, line)) {
3328 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3330 lprintf("O:%s\n", line.c_str());
3332 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3333 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3345 - (Package *) packageWithName:(NSString *)name {
3348 @synchronized (self) {
3349 if (static_cast<pkgDepCache *>(cache_) == NULL)
3351 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3352 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3356 if ((self = [super init]) != nil) {
3363 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3364 apr_pool_create(&pool_, NULL);
3366 size_t capacity(MetaFile_->active_);
3372 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3373 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3377 _assert(pipe(fds) != -1);
3380 _config->Set("APT::Keep-Fds::", cydiafd_);
3381 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3384 detachNewThreadSelector:@selector(_readCydia:)
3386 withObject:[NSNumber numberWithInt:fds[0]]
3389 _assert(pipe(fds) != -1);
3393 detachNewThreadSelector:@selector(_readStatus:)
3395 withObject:[NSNumber numberWithInt:fds[0]]
3398 _assert(pipe(fds) != -1);
3399 _assert(dup2(fds[0], 0) != -1);
3400 _assert(close(fds[0]) != -1);
3402 input_ = fdopen(fds[1], "a");
3404 _assert(pipe(fds) != -1);
3405 _assert(dup2(fds[1], 1) != -1);
3406 _assert(close(fds[1]) != -1);
3409 detachNewThreadSelector:@selector(_readOutput:)
3411 withObject:[NSNumber numberWithInt:fds[0]]
3416 - (pkgCacheFile &) cache {
3420 - (pkgDepCache::Policy *) policy {
3424 - (pkgRecords *) records {
3428 - (pkgProblemResolver *) resolver {
3432 - (pkgAcquire &) fetcher {
3436 - (pkgSourceList &) list {
3440 - (NSArray *) packages {
3441 return (NSArray *) packages_;
3444 - (NSArray *) sources {
3448 - (Source *) sourceWithKey:(NSString *)key {
3449 for (Source *source in [self sources]) {
3450 if ([[source key] isEqualToString:key])
3455 - (bool) popErrorWithTitle:(NSString *)title {
3458 while (!_error->empty()) {
3460 bool warning(!_error->PopMessage(error));
3465 size_t size(error.size());
3466 if (size == 0 || error[size - 1] != '\n')
3468 error.resize(size - 1);
3471 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3473 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3479 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3480 return [self popErrorWithTitle:title] || !success;
3483 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3484 @synchronized (self) {
3487 [self releasePackages];
3490 [sourceList_ removeAllObjects];
3510 apr_pool_clear(pool_);
3512 NSRecycleZone(zone_);
3513 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3515 int chk(creat("/tmp/cydia.chk", 0644));
3519 if (invocation != nil)
3520 [invocation invoke];
3522 NSString *title(UCLocalize("DATABASE"));
3525 OpProgress progress;
3526 while (!cache_.Open(progress, true)) { pop:
3528 bool warning(!_error->PopMessage(error));
3529 lprintf("cache_.Open():[%s]\n", error.c_str());
3531 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3532 [delegate_ repairWithSelector:@selector(configure)];
3533 else if (error == "The package lists or status file could not be parsed or opened.")
3534 [delegate_ repairWithSelector:@selector(update)];
3535 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3536 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3537 // else if (error == "Malformed Status line")
3538 // else if (error == "The list of sources could not be read.")
3540 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3550 unlink("/tmp/cydia.chk");
3552 now_ = [[NSDate date] timeIntervalSince1970];
3554 policy_ = new pkgDepCache::Policy();
3555 records_ = new pkgRecords(cache_);
3556 resolver_ = new pkgProblemResolver(cache_);
3557 fetcher_ = new pkgAcquire(&status_);
3560 list_ = new pkgSourceList();
3561 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3564 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3565 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3569 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3572 if (cache_->BrokenCount() != 0) {
3573 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3576 if (cache_->BrokenCount() != 0) {
3577 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3581 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3585 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3586 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3587 [sourceList_ addObject:object];
3589 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3590 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3591 // XXX: this could be more intelligent
3592 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3593 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3595 sourceMap_[cached->ID] = object;
3600 /*std::vector<Package *> packages;
3601 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3606 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3607 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3608 //packages.push_back(package);
3609 CFArrayAppendValue(packages_, CFRetain(package));
3613 /*if (packages.empty())
3614 packages_ = [[NSArray alloc] init];
3616 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3619 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3620 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3621 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3629 /*if (!packages.empty())
3630 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3631 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3633 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3635 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3637 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3641 size_t count(CFArrayGetCount(packages_));
3642 MetaFile_->active_ = count;
3644 for (size_t index(0); index != count; ++index)
3645 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3652 @synchronized (self) {
3654 resolver_ = new pkgProblemResolver(cache_);
3656 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3657 if (!cache_[iterator].Keep())
3658 cache_->MarkKeep(iterator, false);
3659 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3660 cache_->SetReInstall(iterator, false);
3663 - (void) configure {
3664 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3666 system([dpkg UTF8String]);
3671 // XXX: I don't remember this condition
3676 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3678 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3680 if ([self popErrorWithTitle:title])
3684 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3686 CydiaLogCleaner cleaner;
3687 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3694 fetcher_->Shutdown();
3696 pkgRecords records(cache_);
3698 lock_ = new FileFd();
3699 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3701 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3703 if ([self popErrorWithTitle:title])
3707 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3710 manager_ = (_system->CreatePM(cache_));
3711 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3718 bool substrate(RestartSubstrate_);
3719 RestartSubstrate_ = false;
3721 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3723 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3725 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3727 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3728 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3731 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3733 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3735 [self popErrorWithTitle:title];
3739 bool failed = false;
3740 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3741 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3743 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3749 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3757 RestartSubstrate_ = true;
3760 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3762 if (_error->PendingError()) {
3767 if (result == pkgPackageManager::Failed) {
3772 if (result != pkgPackageManager::Completed) {
3777 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3779 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3781 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3782 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3785 if (![before isEqualToArray:after])
3790 NSString *title(UCLocalize("UPGRADE"));
3791 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3797 [self updateWithStatus:status_];
3800 - (void) updateWithStatus:(Status &)status {
3801 NSString *title(UCLocalize("REFRESHING_DATA"));
3804 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3808 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3809 if ([self popErrorWithTitle:title])
3812 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3814 bool success(ListUpdate(status, list, PulseInterval_));
3815 if (status.WasCancelled())
3818 [self popErrorWithTitle:title forOperation:success];
3819 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3823 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3826 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3827 delegate_ = delegate;
3830 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3831 progress_ = delegate;
3832 status_.setDelegate(delegate);
3835 - (NSObject<ProgressDelegate> *) progressDelegate {
3839 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3840 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3841 return i == sourceMap_.end() ? nil : i->second;
3844 - (NSString *) mappedSectionForPointer:(const char *)section {
3845 _H<NSString> *mapped;
3847 _profile(Database$mappedSectionForPointer$Cache)
3848 mapped = §ions_[section];
3851 if (*mapped == NULL) {
3852 size_t length(strlen(section));
3853 char spaced[length + 1];
3855 _profile(Database$mappedSectionForPointer$Replace)
3856 for (size_t index(0); index != length; ++index)
3857 spaced[index] = section[index] == '_' ? ' ' : section[index];
3858 spaced[length] = '\0';
3863 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3864 string = [NSString stringWithUTF8String:spaced];
3867 _profile(Database$mappedSectionForPointer$Map)
3868 string = [SectionMap_ objectForKey:string] ?: string;
3878 static _H<NSMutableSet> Diversions_;
3880 @interface Diversion : NSObject {
3883 _H<NSString> format_;
3888 @implementation Diversion
3890 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3891 if ((self = [super init]) != nil) {
3892 pattern_ = [from UTF8String];
3898 - (NSString *) divert:(NSString *)url {
3899 return !pattern_(url) ? nil : pattern_->*format_;
3902 + (NSURL *) divertURL:(NSURL *)url {
3904 NSString *href([url absoluteString]);
3906 for (Diversion *diversion in (id) Diversions_)
3907 if (NSString *diverted = [diversion divert:href]) {
3909 NSLog(@"div: %@", diverted);
3911 url = [NSURL URLWithString:diverted];
3918 - (NSString *) key {
3922 - (NSUInteger) hash {
3926 - (BOOL) isEqual:(Diversion *)object {
3927 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3932 @interface CydiaObject : NSObject {
3933 _H<IndirectDelegate> indirect_;
3934 _transient id delegate_;
3937 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3941 @interface CydiaWebViewController : CyteWebViewController {
3942 _H<CydiaObject> cydia_;
3945 + (void) addDiversion:(Diversion *)diversion;
3949 /* Web Scripting {{{ */
3950 @implementation CydiaObject
3952 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3953 if ((self = [super init]) != nil) {
3954 indirect_ = indirect;
3958 - (void) setDelegate:(id)delegate {
3959 delegate_ = delegate;
3962 + (NSArray *) _attributeKeys {
3963 return [NSArray arrayWithObjects:
3980 - (NSArray *) attributeKeys {
3981 return [[self class] _attributeKeys];
3984 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3985 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3988 - (NSString *) version {
3992 - (NSString *) device {
3993 return [[UIDevice currentDevice] uniqueIdentifier];
3996 - (NSString *) firmware {
3997 return [[UIDevice currentDevice] systemVersion];
4000 - (NSString *) hostname {
4001 return [[UIDevice currentDevice] name];
4004 - (NSString *) idiom {
4005 return (id) Idiom_ ?: [NSNull null];
4008 - (NSString *) plmn {
4009 return (id) PLMN_ ?: [NSNull null];
4012 - (NSString *) bbsnum {
4013 return (id) BBSNum_ ?: [NSNull null];
4016 - (NSString *) ecid {
4017 return (id) ChipID_ ?: [NSNull null];
4020 - (NSString *) serial {
4021 return SerialNumber_;
4024 - (NSString *) role {
4025 return (id) Role_ ?: [NSNull null];
4028 - (NSString *) model {
4029 return [NSString stringWithUTF8String:Machine_];
4032 - (NSString *) token {
4033 return (id) Token_ ?: [NSNull null];
4036 + (NSString *) webScriptNameForSelector:(SEL)selector {
4038 else if (selector == @selector(addBridgedHost:))
4039 return @"addBridgedHost";
4040 else if (selector == @selector(addInsecureHost:))
4041 return @"addInsecureHost";
4042 else if (selector == @selector(addInternalRedirect::))
4043 return @"addInternalRedirect";
4044 else if (selector == @selector(addPipelinedHost:scheme:))
4045 return @"addPipelinedHost";
4046 else if (selector == @selector(addSource:::))
4047 return @"addSource";
4048 else if (selector == @selector(addTokenHost:))
4049 return @"addTokenHost";
4050 else if (selector == @selector(addTrivialSource:))
4051 return @"addTrivialSource";
4052 else if (selector == @selector(close))
4054 else if (selector == @selector(du:))
4056 else if (selector == @selector(stringWithFormat:arguments:))
4058 else if (selector == @selector(getAllSources))
4059 return @"getAllSourcs";
4060 else if (selector == @selector(getKernelNumber:))
4061 return @"getKernelNumber";
4062 else if (selector == @selector(getKernelString:))
4063 return @"getKernelString";
4064 else if (selector == @selector(getInstalledPackages))
4065 return @"getInstalledPackages";
4066 else if (selector == @selector(getIORegistryEntry::))
4067 return @"getIORegistryEntry";
4068 else if (selector == @selector(getLocaleIdentifier))
4069 return @"getLocaleIdentifier";
4070 else if (selector == @selector(getPreferredLanguages))
4071 return @"getPreferredLanguages";
4072 else if (selector == @selector(getPackageById:))
4073 return @"getPackageById";
4074 else if (selector == @selector(getMetadataKeys))
4075 return @"getMetadataKeys";
4076 else if (selector == @selector(getMetadataValue:))
4077 return @"getMetadataValue";
4078 else if (selector == @selector(getSessionValue:))
4079 return @"getSessionValue";
4080 else if (selector == @selector(installPackages:))
4081 return @"installPackages";
4082 else if (selector == @selector(localizedStringForKey:value:table:))
4084 else if (selector == @selector(popViewController:))
4085 return @"popViewController";
4086 else if (selector == @selector(refreshSources))
4087 return @"refreshSources";
4088 else if (selector == @selector(removeButton))
4089 return @"removeButton";
4090 else if (selector == @selector(saveConfig))
4091 return @"saveConfig";
4092 else if (selector == @selector(setCydiaSource:))
4093 return @"setCydiaSource";
4094 else if (selector == @selector(setMetadataValue::))
4095 return @"setMetadataValue";
4096 else if (selector == @selector(setSessionValue::))
4097 return @"setSessionValue";
4098 else if (selector == @selector(substitutePackageNames:))
4099 return @"substitutePackageNames";
4100 else if (selector == @selector(scrollToBottom:))
4101 return @"scrollToBottom";
4102 else if (selector == @selector(setAllowsNavigationAction:))
4103 return @"setAllowsNavigationAction";
4104 else if (selector == @selector(setBadgeValue:))
4105 return @"setBadgeValue";
4106 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4107 return @"setButtonImage";
4108 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4109 return @"setButtonTitle";
4110 else if (selector == @selector(setHidesBackButton:))
4111 return @"setHidesBackButton";
4112 else if (selector == @selector(setHidesNavigationBar:))
4113 return @"setHidesNavigationBar";
4114 else if (selector == @selector(setNavigationBarStyle:))
4115 return @"setNavigationBarStyle";
4116 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4117 return @"setNavigationBarTintColor";
4118 else if (selector == @selector(setPasteboardString:))
4119 return @"setPasteboardString";
4120 else if (selector == @selector(setPasteboardURL:))
4121 return @"setPasteboardURL";
4122 else if (selector == @selector(setToken:))
4124 else if (selector == @selector(setViewportWidth:))
4125 return @"setViewportWidth";
4126 else if (selector == @selector(statfs:))
4128 else if (selector == @selector(supports:))
4130 else if (selector == @selector(unload))
4136 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4137 return [self webScriptNameForSelector:selector] == nil;
4140 - (BOOL) supports:(NSString *)feature {
4141 return [feature isEqualToString:@"window.open"];
4145 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4148 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4149 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4152 - (NSNumber *) getKernelNumber:(NSString *)name {
4153 const char *string([name UTF8String]);
4156 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4157 return (id) [NSNull null];
4159 if (size != sizeof(int))
4160 return (id) [NSNull null];
4163 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4164 return (id) [NSNull null];
4166 return [NSNumber numberWithInt:value];
4169 - (NSString *) getKernelString:(NSString *)name {
4170 const char *string([name UTF8String]);
4173 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4174 return (id) [NSNull null];
4176 char value[size + 1];
4177 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4178 return (id) [NSNull null];
4180 // XXX: just in case you request something ludicrous
4183 return [NSString stringWithCString:value];
4186 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4187 NSObject *value(CYIOGetValue([path UTF8String], entry));
4190 if ([value isKindOfClass:[NSData class]])
4191 value = CYHex((NSData *) value);
4196 - (void) _setCydiaSource:(NSString *)source {
4197 @synchronized (HostConfig_) {
4198 CydiaSource_ = source;
4199 [Metadata_ setObject:source forKey:@"CydiaSource"];
4205 - (void) setCydiaSource:(NSString *)source {
4206 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4209 - (NSString *) cydiaSource {
4210 @synchronized (HostConfig_) {
4211 return (id) CydiaSource_ ?: [NSNull null];
4215 - (NSArray *) getMetadataKeys {
4216 @synchronized (Values_) {
4217 return [Values_ allKeys];
4220 - (id) getMetadataValue:(NSString *)key {
4221 @synchronized (Values_) {
4222 return [Values_ objectForKey:key];
4225 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4226 @synchronized (Values_) {
4227 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4228 [Values_ removeObjectForKey:key];
4230 [Values_ setObject:value forKey:key];
4232 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4235 - (id) getSessionValue:(NSString *)key {
4236 @synchronized (SessionData_) {
4237 return [SessionData_ objectForKey:key];
4240 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4241 @synchronized (SessionData_) {
4242 if (value == (id) [WebUndefined undefined])
4243 [SessionData_ removeObjectForKey:key];
4245 [SessionData_ setObject:value forKey:key];
4248 - (void) addBridgedHost:(NSString *)host {
4249 @synchronized (HostConfig_) {
4250 [BridgedHosts_ addObject:host];
4253 - (void) addInsecureHost:(NSString *)host {
4254 @synchronized (HostConfig_) {
4255 [InsecureHosts_ addObject:host];
4258 - (void) addTokenHost:(NSString *)host {
4259 @synchronized (HostConfig_) {
4260 [TokenHosts_ addObject:host];
4263 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4264 @synchronized (HostConfig_) {
4265 if (scheme != (id) [WebUndefined undefined])
4266 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4268 [PipelinedHosts_ addObject:host];
4271 - (void) popViewController:(NSNumber *)value {
4272 if (value == (id) [WebUndefined undefined])
4273 value = [NSNumber numberWithBool:YES];
4274 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4277 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4278 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4280 for (NSString *section in sections)
4281 [array addObject:section];
4283 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4286 distribution, @"Distribution",
4288 nil] waitUntilDone:NO];
4291 - (void) addTrivialSource:(NSString *)href {
4292 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4295 - (void) refreshSources {
4296 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4299 - (void) saveConfig {
4300 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4303 - (NSArray *) getAllSources {
4304 return [[Database sharedInstance] sources];
4307 - (NSArray *) getInstalledPackages {
4308 Database *database([Database sharedInstance]);
4309 @synchronized (database) {
4310 NSArray *packages([database packages]);
4311 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4312 for (Package *package in packages)
4313 if (![package uninstalled])
4314 [installed addObject:package];
4318 - (Package *) getPackageById:(NSString *)id {
4319 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4323 return (Package *) [NSNull null];
4326 - (NSString *) getLocaleIdentifier {
4327 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4330 - (NSArray *) getPreferredLanguages {
4334 - (NSArray *) statfs:(NSString *)path {
4337 if (path == nil || statfs([path UTF8String], &stat) == -1)
4340 return [NSArray arrayWithObjects:
4341 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4342 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4343 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4347 - (NSNumber *) du:(NSString *)path {
4348 NSNumber *value(nil);
4351 _assert(pipe(fds) != -1);
4353 pid_t pid(ExecFork());
4355 _assert(dup2(fds[1], 1) != -1);
4356 _assert(close(fds[0]) != -1);
4357 _assert(close(fds[1]) != -1);
4358 /* XXX: this should probably not use du */
4359 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4364 _assert(close(fds[1]) != -1);
4366 if (FILE *du = fdopen(fds[0], "r")) {
4368 while (fgets(line, sizeof(line), du) != NULL) {
4369 size_t length(strlen(line));
4370 while (length != 0 && line[length - 1] == '\n')
4371 line[--length] = '\0';
4372 if (char *tab = strchr(line, '\t')) {
4374 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4379 } else _assert(close(fds[0]));
4383 if (waitpid(pid, &status, 0) == -1)
4386 else _assert(false);
4392 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4395 - (void) installPackages:(NSArray *)packages {
4396 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4399 - (NSString *) substitutePackageNames:(NSString *)message {
4400 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4401 for (size_t i(0), e([words count]); i != e; ++i) {
4402 NSString *word([words objectAtIndex:i]);
4403 if (Package *package = [[Database sharedInstance] packageWithName:word])
4404 [words replaceObjectAtIndex:i withObject:[package name]];
4407 return [words componentsJoinedByString:@" "];
4410 - (void) removeButton {
4411 [indirect_ removeButton];
4414 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4415 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4418 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4419 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4422 - (void) setBadgeValue:(id)value {
4423 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4426 - (void) setAllowsNavigationAction:(NSString *)value {
4427 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4430 - (void) setHidesBackButton:(NSString *)value {
4431 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4434 - (void) setHidesNavigationBar:(NSString *)value {
4435 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4438 - (void) setNavigationBarStyle:(NSString *)value {
4439 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4442 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4443 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4444 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4445 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4448 - (void) setPasteboardString:(NSString *)value {
4449 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4452 - (void) setPasteboardURL:(NSString *)value {
4453 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4456 - (void) _setToken:(NSString *)token {
4460 [Metadata_ removeObjectForKey:@"Token"];
4462 [Metadata_ setObject:Token_ forKey:@"Token"];
4467 - (void) setToken:(NSString *)token {
4468 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4471 - (void) scrollToBottom:(NSNumber *)animated {
4472 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4475 - (void) setViewportWidth:(float)width {
4476 [indirect_ setViewportWidthOnMainThread:width];
4479 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4480 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4481 unsigned count([arguments count]);
4483 for (unsigned i(0); i != count; ++i)
4484 values[i] = [arguments objectAtIndex:i];
4485 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4488 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4489 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4491 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4493 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4499 @interface NSURL (CydiaSecure)
4502 @implementation NSURL (CydiaSecure)
4504 - (bool) isCydiaSecure {
4505 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4508 @synchronized (HostConfig_) {
4509 if ([InsecureHosts_ containsObject:[self host]])
4518 /* Cydia Browser Controller {{{ */
4519 @implementation CydiaWebViewController
4521 - (NSURL *) navigationURL {
4522 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4525 + (void) initialize {
4526 Diversions_ = [NSMutableSet setWithCapacity:0];
4529 + (void) addDiversion:(Diversion *)diversion {
4530 [Diversions_ addObject:diversion];
4533 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4534 [super webView:view didClearWindowObject:window forFrame:frame];
4536 WebDataSource *source([frame dataSource]);
4537 NSURLResponse *response([source response]);
4538 NSURL *url([response URL]);
4539 NSString *scheme([[url scheme] lowercaseString]);
4541 bool bridged(false);
4543 @synchronized (HostConfig_) {
4544 if ([scheme isEqualToString:@"file"])
4546 else if ([scheme isEqualToString:@"https"])
4547 if ([BridgedHosts_ containsObject:[url host]])
4552 [window setValue:cydia_ forKey:@"cydia"];
4555 - (void) _setupMail:(MFMailComposeViewController *)controller {
4556 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4558 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4559 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4562 - (NSURL *) URLWithURL:(NSURL *)url {
4563 return [Diversion divertURL:url];
4566 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4567 NSURL *url([request URL]);
4568 NSString *host([url host]);
4570 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4572 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4573 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4574 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4575 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4578 @synchronized (HostConfig_) {
4579 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4582 if ([url isCydiaSecure] && token) {
4583 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4584 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4590 - (void) setDelegate:(id)delegate {
4591 [super setDelegate:delegate];
4592 [cydia_ setDelegate:delegate];
4595 - (NSString *) applicationNameForUserAgent {
4596 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4599 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4601 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4602 if (Product_ != nil)
4603 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4609 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4610 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4616 @interface AppCacheController : CydiaWebViewController {
4621 @implementation AppCacheController
4623 - (void) didReceiveMemoryWarning {
4630 @interface NSObject (CydiaScript)
4631 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4634 @implementation NSObject (CydiaScript)
4636 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4642 @implementation NSArray (CydiaScript)
4644 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4645 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4646 for (size_t i(0), e([self count]); i != e; ++i)
4647 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4653 @implementation NSDictionary (CydiaScript)
4655 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4656 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4658 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4665 /* Confirmation Controller {{{ */
4666 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4667 if (!iterator.end())
4668 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4669 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4671 pkgCache::PkgIterator package(dep.TargetPkg());
4674 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4681 @protocol ConfirmationControllerDelegate
4682 - (void) cancelAndClear:(bool)clear;
4683 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4687 @interface ConfirmationController : CydiaWebViewController {
4688 _transient Database *database_;
4690 _H<UIAlertView> essential_;
4692 _H<NSDictionary> changes_;
4693 _H<NSMutableArray> issues_;
4694 _H<NSDictionary> sizes_;
4699 - (id) initWithDatabase:(Database *)database;
4703 @implementation ConfirmationController
4707 RestartSubstrate_ = true;
4708 [delegate_ confirmWithNavigationController:[self navigationController]];
4711 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4712 NSString *context([alert context]);
4714 if ([context isEqualToString:@"remove"]) {
4715 if (button == [alert cancelButtonIndex])
4716 [self dismissModalViewControllerAnimated:YES];
4717 else if (button == [alert firstOtherButtonIndex]) {
4721 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4722 } else if ([context isEqualToString:@"unable"]) {
4723 [self dismissModalViewControllerAnimated:YES];
4724 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4726 [super alertView:alert clickedButtonAtIndex:button];
4730 - (void) _doContinue {
4731 [delegate_ cancelAndClear:NO];
4732 [self dismissModalViewControllerAnimated:YES];
4735 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4736 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4740 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4741 [super webView:view didClearWindowObject:window forFrame:frame];
4743 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4744 (id) changes_, @"changes",
4745 (id) issues_, @"issues",
4746 (id) sizes_, @"sizes",
4748 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4751 - (id) initWithDatabase:(Database *)database {
4752 if ((self = [super init]) != nil) {
4753 database_ = database;
4755 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4756 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4757 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4758 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4759 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4763 pkgCacheFile &cache([database_ cache]);
4764 NSArray *packages([database_ packages]);
4765 pkgDepCache::Policy *policy([database_ policy]);
4767 issues_ = [NSMutableArray arrayWithCapacity:4];
4769 for (Package *package in packages) {
4770 pkgCache::PkgIterator iterator([package iterator]);
4771 NSString *name([package id]);
4773 if ([package broken]) {
4774 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4776 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4778 reasons, @"reasons",
4781 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4785 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4786 pkgCache::DepIterator start;
4787 pkgCache::DepIterator end;
4788 dep.GlobOr(start, end); // ++dep
4790 if (!cache->IsImportantDep(end))
4792 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4795 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4797 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4798 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4799 clauses, @"clauses",
4803 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4805 pkgCache::PkgIterator target(start.TargetPkg());
4806 if (target->ProvidesList != 0)
4807 reason = @"missing";
4809 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4811 reason = @"installed";
4812 installed = [NSString stringWithUTF8String:ver.VerStr()];
4813 } else if (!cache[target].CandidateVerIter(cache).end())
4814 reason = @"uninstalled";
4815 else if (target->ProvidesList == 0)
4816 reason = @"uninstallable";
4818 reason = @"virtual";
4821 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4822 [NSString stringWithUTF8String:start.CompType()], @"operator",
4823 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4826 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4827 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4828 version, @"version",
4830 installed, @"installed",
4833 // yes, seriously. (wtf?)
4841 pkgDepCache::StateCache &state(cache[iterator]);
4843 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4845 if (state.NewInstall())
4846 [installs addObject:name];
4847 // XXX: else if (state.Install())
4848 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4849 [reinstalls addObject:name];
4850 // XXX: move before previous if
4851 else if (state.Upgrade())
4852 [upgrades addObject:name];
4853 else if (state.Downgrade())
4854 [downgrades addObject:name];
4855 else if (!state.Delete())
4856 // XXX: _assert(state.Keep());
4858 else if (special_r(name))
4859 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4860 [NSNull null], @"package",
4861 [NSArray arrayWithObjects:
4862 [NSDictionary dictionaryWithObjectsAndKeys:
4863 @"Conflicts", @"relationship",
4864 [NSArray arrayWithObjects:
4865 [NSDictionary dictionaryWithObjectsAndKeys:
4867 [NSNull null], @"version",
4868 @"installed", @"reason",
4875 if ([package essential])
4877 [removes addObject:name];
4880 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4881 substrate_ |= DepSubstrate(iterator.CurrentVer());
4886 else if (Advanced_) {
4887 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4889 essential_ = [[[UIAlertView alloc]
4890 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4891 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4893 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4895 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4899 [essential_ setContext:@"remove"];
4901 essential_ = [[[UIAlertView alloc]
4902 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4903 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4905 cancelButtonTitle:UCLocalize("OKAY")
4906 otherButtonTitles:nil
4909 [essential_ setContext:@"unable"];
4912 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4913 installs, @"installs",
4914 reinstalls, @"reinstalls",
4915 upgrades, @"upgrades",
4916 downgrades, @"downgrades",
4917 removes, @"removes",
4920 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4921 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4922 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4925 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4929 - (UIBarButtonItem *) leftButton {
4930 return [[[UIBarButtonItem alloc]
4931 initWithTitle:UCLocalize("CANCEL")
4932 style:UIBarButtonItemStylePlain
4934 action:@selector(cancelButtonClicked)
4939 - (void) applyRightButton {
4940 if ([issues_ count] == 0 && ![self isLoading])
4941 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4942 initWithTitle:UCLocalize("CONFIRM")
4943 style:UIBarButtonItemStyleDone
4945 action:@selector(confirmButtonClicked)
4948 [[self navigationItem] setRightBarButtonItem:nil];
4952 - (void) cancelButtonClicked {
4953 [self dismissModalViewControllerAnimated:YES];
4954 [delegate_ cancelAndClear:YES];
4958 - (void) confirmButtonClicked {
4959 if (essential_ != nil)
4969 /* Progress Data {{{ */
4970 @interface CydiaProgressData : NSObject {
4971 _transient id delegate_;
4980 _H<NSMutableArray> events_;
4981 _H<NSString> title_;
4983 _H<NSString> status_;
4984 _H<NSString> finish_;
4989 @implementation CydiaProgressData
4991 + (NSArray *) _attributeKeys {
4992 return [NSArray arrayWithObjects:
5004 - (NSArray *) attributeKeys {
5005 return [[self class] _attributeKeys];
5008 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5009 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5013 if ((self = [super init]) != nil) {
5014 events_ = [NSMutableArray arrayWithCapacity:32];
5018 - (void) setDelegate:(id)delegate {
5019 delegate_ = delegate;
5022 - (void) setPercent:(float)value {
5026 - (NSNumber *) percent {
5027 return [NSNumber numberWithFloat:percent_];
5030 - (void) setCurrent:(float)value {
5034 - (NSNumber *) current {
5035 return [NSNumber numberWithFloat:current_];
5038 - (void) setTotal:(float)value {
5042 - (NSNumber *) total {
5043 return [NSNumber numberWithFloat:total_];
5046 - (void) setSpeed:(float)value {
5050 - (NSNumber *) speed {
5051 return [NSNumber numberWithFloat:speed_];
5054 - (NSArray *) events {
5058 - (void) removeAllEvents {
5059 [events_ removeAllObjects];
5062 - (void) addEvent:(CydiaProgressEvent *)event {
5063 [events_ addObject:event];
5066 - (void) setTitle:(NSString *)text {
5070 - (NSString *) title {
5074 - (void) setFinish:(NSString *)text {
5078 - (NSString *) finish {
5079 return (id) finish_ ?: [NSNull null];
5082 - (void) setRunning:(bool)running {
5086 - (NSNumber *) running {
5087 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5092 /* Progress Controller {{{ */
5093 @interface ProgressController : CydiaWebViewController <
5096 _transient Database *database_;
5097 _H<CydiaProgressData, 1> progress_;
5101 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5103 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5105 - (void) setTitle:(NSString *)title;
5106 - (void) setCancellable:(bool)cancellable;
5110 @implementation ProgressController
5113 [database_ setProgressDelegate:nil];
5117 - (UIBarButtonItem *) leftButton {
5118 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5119 initWithTitle:UCLocalize("CANCEL")
5120 style:UIBarButtonItemStylePlain
5122 action:@selector(cancel)
5123 ] autorelease] : nil;
5126 - (void) updateCancel {
5127 [super applyLeftButton];
5130 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5131 if ((self = [super init]) != nil) {
5132 database_ = database;
5133 delegate_ = delegate;
5135 [database_ setProgressDelegate:self];
5137 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5138 [progress_ setDelegate:self];
5140 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5142 [scroller_ setBackgroundColor:[UIColor blackColor]];
5144 [[self navigationItem] setHidesBackButton:YES];
5146 [self updateCancel];
5150 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5151 [super webView:view didClearWindowObject:window forFrame:frame];
5152 [window setValue:progress_ forKey:@"cydiaProgress"];
5155 - (void) updateProgress {
5156 [self dispatchEvent:@"CydiaProgressUpdate"];
5159 - (void) viewWillAppear:(BOOL)animated {
5160 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5161 [super viewWillAppear:animated];
5165 UpdateExternalStatus(0);
5168 [delegate_ saveState];
5172 [delegate_ returnToCydia];
5176 [delegate_ terminateWithSuccess];
5177 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5178 [delegate_ suspendWithAnimation:YES];
5180 [delegate_ suspend];*/
5192 system("/usr/bin/sbreload");
5198 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5199 SBReboot(SBSSpringBoardServerPort());
5201 reboot2(RB_AUTOBOOT);
5208 - (void) setTitle:(NSString *)title {
5209 [progress_ setTitle:title];
5210 [self updateProgress];
5213 - (UIBarButtonItem *) rightButton {
5214 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5215 initWithTitle:UCLocalize("CLOSE")
5216 style:UIBarButtonItemStylePlain
5218 action:@selector(close)
5222 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5223 UpdateExternalStatus(1);
5225 [progress_ setRunning:true];
5226 [self setTitle:title];
5227 // implicit updateProgress
5229 SHA1SumValue notifyconf; {
5231 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5234 MMap mmap(file, MMap::ReadOnly);
5236 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5237 notifyconf = sha1.Result();
5241 SHA1SumValue springlist; {
5243 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5246 MMap mmap(file, MMap::ReadOnly);
5248 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5249 springlist = sha1.Result();
5253 if (invocation != nil) {
5254 [invocation yieldToSelector:@selector(invoke)];
5255 [self setTitle:@"COMPLETE"];
5260 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5263 MMap mmap(file, MMap::ReadOnly);
5265 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5266 if (!(notifyconf == sha1.Result()))
5273 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5276 MMap mmap(file, MMap::ReadOnly);
5278 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5279 if (!(springlist == sha1.Result()))
5285 if (RestartSubstrate_)
5289 RestartSubstrate_ = false;
5292 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5293 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5294 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5295 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5296 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5300 system("su -c /usr/bin/uicache mobile");
5303 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5305 [progress_ setRunning:false];
5306 [self updateProgress];
5308 [self applyRightButton];
5311 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5312 [progress_ addEvent:event];
5313 [self updateProgress];
5316 - (bool) isProgressCancelled {
5317 return cancel_ == 2;
5322 [self updateCancel];
5325 - (void) setCancellable:(bool)cancellable {
5326 unsigned cancel(cancel_);
5330 else if (cancel_ == 0)
5333 if (cancel != cancel_)
5334 [self updateCancel];
5337 - (void) setProgressCancellable:(NSNumber *)cancellable {
5338 [self setCancellable:[cancellable boolValue]];
5341 - (void) setProgressPercent:(NSNumber *)percent {
5342 [progress_ setPercent:[percent floatValue]];
5343 [self updateProgress];
5346 - (void) setProgressStatus:(NSDictionary *)status {
5347 if (status == nil) {
5348 [progress_ setCurrent:0];
5349 [progress_ setTotal:0];
5350 [progress_ setSpeed:0];
5352 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5354 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5355 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5356 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5359 [self updateProgress];
5365 /* Package Cell {{{ */
5366 @interface PackageCell : CyteTableViewCell <
5367 CyteTableViewCellDelegate
5371 _H<NSString> description_;
5373 _H<NSString> source_;
5375 _H<UIImage> placard_;
5379 - (PackageCell *) init;
5380 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5382 - (void) drawContentRect:(CGRect)rect;
5386 @implementation PackageCell
5388 - (PackageCell *) init {
5389 CGRect frame(CGRectMake(0, 0, 320, 74));
5390 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5391 UIView *content([self contentView]);
5392 CGRect bounds([content bounds]);
5394 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5395 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5396 [content addSubview:content_];
5398 [content_ setDelegate:self];
5399 [content_ setOpaque:YES];
5403 - (NSString *) accessibilityLabel {
5404 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5407 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5408 summarized_ = summary;
5418 [content_ setBackgroundColor:[UIColor whiteColor]];
5422 Source *source = [package source];
5424 icon_ = [package icon];
5426 if (NSString *name = [package name])
5427 name_ = [NSString stringWithString:name];
5429 NSString *description(nil);
5431 if (description == nil && IsWildcat_)
5432 description = [package longDescription];
5433 if (description == nil)
5434 description = [package shortDescription];
5436 if (description != nil)
5437 description_ = [NSString stringWithString:description];
5439 commercial_ = [package isCommercial];
5441 NSString *label = nil;
5442 bool trusted = false;
5444 if (source != nil) {
5445 label = [source label];
5446 trusted = [source trusted];
5447 } else if ([[package id] isEqualToString:@"firmware"])
5448 label = UCLocalize("APPLE");
5450 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5452 NSString *from(label);
5454 NSString *section = [package simpleSection];
5455 if (section != nil && ![section isEqualToString:label]) {
5456 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5457 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5460 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5462 if (NSString *purpose = [package primaryPurpose])
5463 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5468 if (NSString *mode = [package mode]) {
5469 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5470 color = RemovingColor_;
5471 //placard = @"removing";
5473 color = InstallingColor_;
5474 //placard = @"installing";
5477 // XXX: the removing/installing placards are not @2x
5480 color = [UIColor whiteColor];
5482 if ([package installed] != nil)
5483 placard = @"installed";
5488 [content_ setBackgroundColor:color];
5491 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5494 [self setNeedsDisplay];
5495 [content_ setNeedsDisplay];
5498 - (void) drawSummaryContentRect:(CGRect)rect {
5499 bool highlighted(highlighted_);
5500 float width([self bounds].size.width);
5504 rect.size = [(UIImage *) icon_ size];
5506 rect.size.width /= 4;
5507 rect.size.height /= 4;
5509 rect.origin.x = 14 - rect.size.width / 4;
5510 rect.origin.y = 14 - rect.size.height / 4;
5512 [icon_ drawInRect:rect];
5515 if (badge_ != nil) {
5517 rect.size = [(UIImage *) badge_ size];
5519 rect.size.width /= 4;
5520 rect.size.height /= 4;
5522 rect.origin.x = 20 - rect.size.width / 4;
5523 rect.origin.y = 20 - rect.size.height / 4;
5525 [badge_ drawInRect:rect];
5532 UISetColor(commercial_ ? Purple_ : Black_);
5533 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5535 if (placard_ != nil)
5536 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5539 - (void) drawNormalContentRect:(CGRect)rect {
5540 bool highlighted(highlighted_);
5541 float width([self bounds].size.width);
5545 rect.size = [(UIImage *) icon_ size];
5547 rect.size.width /= 2;
5548 rect.size.height /= 2;
5550 rect.origin.x = 25 - rect.size.width / 2;
5551 rect.origin.y = 25 - rect.size.height / 2;
5553 [icon_ drawInRect:rect];
5556 if (badge_ != nil) {
5558 rect.size = [(UIImage *) badge_ size];
5560 rect.size.width /= 2;
5561 rect.size.height /= 2;
5563 rect.origin.x = 36 - rect.size.width / 2;
5564 rect.origin.y = 36 - rect.size.height / 2;
5566 [badge_ drawInRect:rect];
5573 UISetColor(commercial_ ? Purple_ : Black_);
5574 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5575 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5578 UISetColor(commercial_ ? Purplish_ : Gray_);
5579 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5581 if (placard_ != nil)
5582 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5585 - (void) drawContentRect:(CGRect)rect {
5587 [self drawSummaryContentRect:rect];
5589 [self drawNormalContentRect:rect];
5594 /* Section Cell {{{ */
5595 @interface SectionCell : CyteTableViewCell <
5596 CyteTableViewCellDelegate
5598 _H<NSString> basic_;
5599 _H<NSString> section_;
5601 _H<NSString> count_;
5603 _H<UISwitch> switch_;
5607 - (void) setSection:(Section *)section editing:(BOOL)editing;
5611 @implementation SectionCell
5613 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5614 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5615 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5616 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5617 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5619 UIView *content([self contentView]);
5620 CGRect bounds([content bounds]);
5622 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5623 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5624 [content addSubview:content_];
5625 [content_ setBackgroundColor:[UIColor whiteColor]];
5627 [content_ setDelegate:self];
5631 - (void) onSwitch:(id)sender {
5632 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5633 if (metadata == nil) {
5634 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5635 [Sections_ setObject:metadata forKey:basic_];
5638 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5642 - (void) setSection:(Section *)section editing:(BOOL)editing {
5643 if (editing != editing_) {
5645 [switch_ removeFromSuperview];
5647 [self addSubview:switch_];
5656 if (section == nil) {
5657 name_ = UCLocalize("ALL_PACKAGES");
5660 basic_ = [section name];
5661 section_ = [section localized];
5663 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5664 count_ = [NSString stringWithFormat:@"%d", [section count]];
5667 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5670 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5671 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5673 [content_ setNeedsDisplay];
5676 - (void) setFrame:(CGRect)frame {
5677 [super setFrame:frame];
5679 CGRect rect([switch_ frame]);
5680 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5683 - (NSString *) accessibilityLabel {
5687 - (void) drawContentRect:(CGRect)rect {
5688 bool highlighted(highlighted_ && !editing_);
5690 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5695 float width(rect.size.width);
5701 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5703 CGSize size = [count_ sizeWithFont:Font14_];
5707 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5713 /* File Table {{{ */
5714 @interface FileTable : CyteViewController <
5715 UITableViewDataSource,
5718 _transient Database *database_;
5719 _H<Package> package_;
5721 _H<NSMutableArray> files_;
5722 _H<UITableView, 2> list_;
5725 - (id) initWithDatabase:(Database *)database;
5726 - (void) setPackage:(Package *)package;
5730 @implementation FileTable
5732 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5733 return files_ == nil ? 0 : [files_ count];
5736 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5740 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5741 static NSString *reuseIdentifier = @"Cell";
5743 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5745 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5746 [cell setFont:[UIFont systemFontOfSize:16]];
5748 [cell setText:[files_ objectAtIndex:indexPath.row]];
5749 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5754 - (NSURL *) navigationURL {
5755 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5759 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5761 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5762 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5763 [list_ setRowHeight:24.0f];
5764 [(UITableView *) list_ setDataSource:self];
5765 [list_ setDelegate:self];
5766 [[self view] addSubview:list_];
5769 - (void) viewDidLoad {
5770 [super viewDidLoad];
5772 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5775 - (void) releaseSubviews {
5781 [super releaseSubviews];
5784 - (id) initWithDatabase:(Database *)database {
5785 if ((self = [super init]) != nil) {
5786 database_ = database;
5790 - (void) setPackage:(Package *)package {
5794 files_ = [NSMutableArray arrayWithCapacity:32];
5796 if (package != nil) {
5798 name_ = [package id];
5800 if (NSArray *files = [package files])
5801 [files_ addObjectsFromArray:files];
5803 if ([files_ count] != 0) {
5804 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5805 [files_ removeObjectAtIndex:0];
5806 [files_ sortUsingSelector:@selector(compareByPath:)];
5808 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5809 [stack addObject:@"/"];
5811 for (int i(0), e([files_ count]); i != e; ++i) {
5812 NSString *file = [files_ objectAtIndex:i];
5813 while (![file hasPrefix:[stack lastObject]])
5814 [stack removeLastObject];
5815 NSString *directory = [stack lastObject];
5816 [stack addObject:[file stringByAppendingString:@"/"]];
5817 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5818 ([stack count] - 2) * 3, "",
5819 [file substringFromIndex:[directory length]]
5828 - (void) reloadData {
5831 [self setPackage:[database_ packageWithName:name_]];
5836 /* Package Controller {{{ */
5837 @interface CYPackageController : CydiaWebViewController <
5838 UIActionSheetDelegate
5840 _transient Database *database_;
5841 _H<Package> package_;
5844 _H<NSMutableArray> buttons_;
5845 _H<UIBarButtonItem> button_;
5848 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5852 @implementation CYPackageController
5854 - (NSURL *) navigationURL {
5855 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5858 /* XXX: this is not safe at all... localization of /fail/ */
5859 - (void) _clickButtonWithName:(NSString *)name {
5860 if ([name isEqualToString:UCLocalize("CLEAR")])
5861 [delegate_ clearPackage:package_];
5862 else if ([name isEqualToString:UCLocalize("INSTALL")])
5863 [delegate_ installPackage:package_];
5864 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5865 [delegate_ installPackage:package_];
5866 else if ([name isEqualToString:UCLocalize("REMOVE")])
5867 [delegate_ removePackage:package_];
5868 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5869 [delegate_ installPackage:package_];
5870 else _assert(false);
5873 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5874 NSString *context([sheet context]);
5876 if ([context isEqualToString:@"modify"]) {
5877 if (button != [sheet cancelButtonIndex]) {
5878 NSString *buttonName = [buttons_ objectAtIndex:button];
5879 [self _clickButtonWithName:buttonName];
5882 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5886 - (bool) _allowJavaScriptPanel {
5891 - (void) _customButtonClicked {
5892 int count([buttons_ count]);
5897 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5899 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5900 [buttons addObjectsFromArray:buttons_];
5902 UIActionSheet *sheet = [[[UIActionSheet alloc]
5905 cancelButtonTitle:nil
5906 destructiveButtonTitle:nil
5907 otherButtonTitles:nil
5910 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5912 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5913 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5915 [sheet setContext:@"modify"];
5917 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5921 // We don't want to allow non-commercial packages to do custom things to the install button,
5922 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5923 - (void) customButtonClicked {
5925 [super customButtonClicked];
5927 [self _customButtonClicked];
5930 - (void) reloadButtonClicked {
5931 // Don't reload a commerical package by tapping the loading button,
5932 // but if it's not an Install button, we should forward it on.
5933 if (![package_ uninstalled])
5934 [self _customButtonClicked];
5937 - (void) applyLoadingTitle {
5938 // Don't show "Loading" as the title. Ever.
5941 - (UIBarButtonItem *) rightButton {
5946 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5947 if ((self = [super init]) != nil) {
5948 database_ = database;
5949 buttons_ = [NSMutableArray arrayWithCapacity:4];
5950 name_ = name == nil ? @"" : [NSString stringWithString:name];
5951 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5955 - (void) reloadData {
5958 package_ = [database_ packageWithName:name_];
5960 [buttons_ removeAllObjects];
5962 if (package_ != nil) {
5963 [(Package *) package_ parse];
5965 commercial_ = [package_ isCommercial];
5967 if ([package_ mode] != nil)
5968 [buttons_ addObject:UCLocalize("CLEAR")];
5969 if ([package_ source] == nil);
5970 else if ([package_ upgradableAndEssential:NO])
5971 [buttons_ addObject:UCLocalize("UPGRADE")];
5972 else if ([package_ uninstalled])
5973 [buttons_ addObject:UCLocalize("INSTALL")];
5975 [buttons_ addObject:UCLocalize("REINSTALL")];
5976 if (![package_ uninstalled])
5977 [buttons_ addObject:UCLocalize("REMOVE")];
5981 switch ([buttons_ count]) {
5982 case 0: title = nil; break;
5983 case 1: title = [buttons_ objectAtIndex:0]; break;
5984 default: title = UCLocalize("MODIFY"); break;
5987 button_ = [[[UIBarButtonItem alloc]
5989 style:UIBarButtonItemStylePlain
5991 action:@selector(customButtonClicked)
5995 - (bool) isLoading {
5996 return commercial_ ? [super isLoading] : false;
6002 /* Package List Controller {{{ */
6003 @interface PackageListController : CyteViewController <
6004 UITableViewDataSource,
6007 _transient Database *database_;
6009 _H<NSArray> packages_;
6010 _H<NSMutableArray> sections_;
6011 _H<UITableView, 2> list_;
6012 _H<NSMutableArray> index_;
6013 _H<NSMutableDictionary> indices_;
6014 _H<NSString> title_;
6015 unsigned reloading_;
6018 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6019 - (void) setDelegate:(id)delegate;
6020 - (void) resetCursor;
6025 @implementation PackageListController
6027 - (bool) isSummarized {
6031 - (bool) showsSections {
6035 - (void) deselectWithAnimation:(BOOL)animated {
6036 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6039 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6040 CGRect base = [[self view] bounds];
6041 base.size.height -= bounds.size.height;
6042 base.origin = [list_ frame].origin;
6044 [UIView beginAnimations:nil context:NULL];
6045 [UIView setAnimationBeginsFromCurrentState:YES];
6046 [UIView setAnimationCurve:curve];
6047 [UIView setAnimationDuration:duration];
6048 [list_ setFrame:base];
6049 [UIView commitAnimations];
6052 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6053 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6056 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6057 [self resizeForKeyboardBounds:bounds duration:0];
6060 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6061 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6062 *curve = UIViewAnimationCurveEaseInOut;
6064 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6066 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6069 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6072 - (void) keyboardWillShow:(NSNotification *)notification {
6075 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6076 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6078 NSTimeInterval duration;
6079 UIViewAnimationCurve curve;
6080 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6082 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);
6083 UIViewController *base = self;
6084 while ([base parentViewController] != nil)
6085 base = [base parentViewController];
6086 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6087 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6089 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6090 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6092 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6095 - (void) keyboardWillHide:(NSNotification *)notification {
6096 NSTimeInterval duration;
6097 UIViewAnimationCurve curve;
6098 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6100 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6103 - (void) viewWillAppear:(BOOL)animated {
6104 [super viewWillAppear:animated];
6106 [self resizeForKeyboardBounds:CGRectZero];
6107 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6108 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6111 - (void) viewWillDisappear:(BOOL)animated {
6112 [super viewWillDisappear:animated];
6114 [self resizeForKeyboardBounds:CGRectZero];
6115 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6116 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6119 - (void) viewDidAppear:(BOOL)animated {
6120 [super viewDidAppear:animated];
6121 [self deselectWithAnimation:animated];
6124 - (void) didSelectPackage:(Package *)package {
6125 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6126 [view setDelegate:delegate_];
6127 [[self navigationController] pushViewController:view animated:YES];
6130 #if TryIndexedCollation
6131 + (BOOL) hasIndexedCollation {
6132 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6136 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6137 NSInteger count([sections_ count]);
6138 return count == 0 ? 1 : count;
6141 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6142 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6144 return [[sections_ objectAtIndex:section] name];
6147 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6148 if ([sections_ count] == 0)
6150 return [[sections_ objectAtIndex:section] count];
6153 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6154 @synchronized (database_) {
6155 if ([database_ era] != era_)
6158 Section *section([sections_ objectAtIndex:[path section]]);
6159 NSInteger row([path row]);
6160 Package *package([packages_ objectAtIndex:([section row] + row)]);
6161 return [[package retain] autorelease];
6164 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6165 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6167 cell = [[[PackageCell alloc] init] autorelease];
6169 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6170 [cell setPackage:package asSummary:[self isSummarized]];
6174 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6175 Package *package([self packageAtIndexPath:path]);
6176 package = [database_ packageWithName:[package id]];
6177 [self didSelectPackage:package];
6180 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6181 if (![self showsSections])
6187 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6188 #if TryIndexedCollation
6189 if ([[self class] hasIndexedCollation]) {
6190 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6197 - (void) updateHeight {
6198 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6201 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6202 if ((self = [super init]) != nil) {
6203 database_ = database;
6204 title_ = [title copy];
6205 [[self navigationItem] setTitle:title_];
6210 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6212 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6213 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6214 [[self view] addSubview:list_];
6216 // XXX: is 20 the most optimal number here?
6217 [list_ setSectionIndexMinimumDisplayRowCount:20];
6219 [(UITableView *) list_ setDataSource:self];
6220 [list_ setDelegate:self];
6222 [self updateHeight];
6225 - (void) releaseSubviews {
6233 [super releaseSubviews];
6236 - (void) setDelegate:(id)delegate {
6237 delegate_ = delegate;
6240 - (bool) shouldYield {
6244 - (bool) shouldBlock {
6248 - (NSMutableArray *) _reloadPackages {
6249 @synchronized (database_) {
6250 era_ = [database_ era];
6251 NSArray *packages([database_ packages]);
6253 return [NSMutableArray arrayWithArray:packages];
6256 - (void) _reloadData {
6257 if (reloading_ != 0) {
6264 if ([self shouldYield]) {
6268 if (![self shouldBlock])
6271 hud = [delegate_ addProgressHUD];
6272 [hud setText:UCLocalize("LOADING")];
6276 packages = [self yieldToSelector:@selector(_reloadPackages)];
6279 [delegate_ removeProgressHUD:hud];
6280 } while (reloading_ == 2);
6284 packages = [self _reloadPackages];
6287 packages_ = packages;
6289 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6290 sections_ = [NSMutableArray arrayWithCapacity:16];
6292 Section *section = nil;
6294 #if TryIndexedCollation
6295 if ([[self class] hasIndexedCollation]) {
6296 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6298 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6299 NSArray *titles = [collation sectionIndexTitles];
6302 _profile(PackageTable$reloadData$Section)
6303 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6307 _profile(PackageTable$reloadData$Section$Package)
6308 package = [packages_ objectAtIndex:offset];
6309 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6312 while (secidx < index) {
6315 _profile(PackageTable$reloadData$Section$Allocate)
6316 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6319 _profile(PackageTable$reloadData$Section$Add)
6320 [sections_ addObject:section];
6324 [section addToCount];
6330 index_ = [NSMutableArray arrayWithCapacity:32];
6332 bool sectioned([self showsSections]);
6334 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6335 [sections_ addObject:section];
6338 _profile(PackageTable$reloadData$Section)
6339 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6343 _profile(PackageTable$reloadData$Section$Package)
6344 package = [packages_ objectAtIndex:offset];
6345 index = [package index];
6348 if (sectioned && (section == nil || [section index] != index)) {
6349 _profile(PackageTable$reloadData$Section$Allocate)
6350 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6353 [index_ addObject:[section name]];
6354 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6356 _profile(PackageTable$reloadData$Section$Add)
6357 [sections_ addObject:section];
6361 [section addToCount];
6366 [self updateHeight];
6368 _profile(PackageTable$reloadData$List)
6369 [(UITableView *) list_ setDataSource:self];
6374 - (void) reloadData {
6377 if ([self shouldYield])
6378 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6383 - (void) resetCursor {
6384 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6387 - (void) clearData {
6388 [self updateHeight];
6390 [list_ setDataSource:nil];
6398 /* Filtered Package List Controller {{{ */
6399 @interface FilteredPackageListController : PackageListController {
6402 _H<NSObject> object_;
6405 - (void) setObject:(id)object;
6406 - (void) setObject:(id)object forFilter:(SEL)filter;
6409 - (void) setFilter:(SEL)filter;
6411 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6415 @implementation FilteredPackageListController
6421 - (void) setFilter:(SEL)filter {
6422 @synchronized (self) {
6425 /* XXX: this is an unsafe optimization of doomy hell */
6426 Method method(class_getInstanceMethod([Package class], filter));
6427 _assert(method != NULL);
6428 imp_ = method_getImplementation(method);
6429 _assert(imp_ != NULL);
6432 - (void) setObject:(id)object {
6433 @synchronized (self) {
6437 - (void) setObject:(id)object forFilter:(SEL)filter {
6438 @synchronized (self) {
6439 [self setFilter:filter];
6440 [self setObject:object];
6443 - (NSMutableArray *) _reloadPackages {
6444 @synchronized (database_) {
6445 era_ = [database_ era];
6446 NSArray *packages([database_ packages]);
6448 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6452 _H<NSObject> object;
6454 @synchronized (self) {
6460 _profile(PackageTable$reloadData$Filter)
6461 for (Package *package in packages)
6462 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6463 [filtered addObject:package];
6469 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6470 if ((self = [super initWithDatabase:database title:title]) != nil) {
6471 [self setFilter:filter];
6472 [self setObject:object];
6479 /* Home Controller {{{ */
6480 @interface HomeController : CydiaWebViewController {
6485 @implementation HomeController
6488 if ((self = [super init]) != nil) {
6489 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6494 - (NSURL *) navigationURL {
6495 return [NSURL URLWithString:@"cydia://home"];
6498 - (void) didReceiveMemoryWarning {
6501 - (void) aboutButtonClicked {
6502 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6504 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6505 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6506 [alert setCancelButtonIndex:0];
6509 @"Copyright \u00a9 2008-2011\n"
6512 "Jay Freeman (saurik)\n"
6513 "saurik@saurik.com\n"
6514 "http://www.saurik.com/"
6520 - (UIBarButtonItem *) leftButton {
6521 return [[[UIBarButtonItem alloc]
6522 initWithTitle:UCLocalize("ABOUT")
6523 style:UIBarButtonItemStylePlain
6525 action:@selector(aboutButtonClicked)
6531 /* Manage Controller {{{ */
6532 @interface ManageController : CydiaWebViewController {
6535 - (void) queueStatusDidChange;
6539 @implementation ManageController
6542 if ((self = [super init]) != nil) {
6543 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6547 - (NSURL *) navigationURL {
6548 return [NSURL URLWithString:@"cydia://manage"];
6551 - (UIBarButtonItem *) leftButton {
6552 return [[[UIBarButtonItem alloc]
6553 initWithTitle:UCLocalize("SETTINGS")
6554 style:UIBarButtonItemStylePlain
6556 action:@selector(settingsButtonClicked)
6560 - (void) settingsButtonClicked {
6561 [delegate_ showSettings];
6564 - (void) queueButtonClicked {
6568 - (UIBarButtonItem *) customButton {
6569 return Queuing_ ? [[[UIBarButtonItem alloc]
6570 initWithTitle:UCLocalize("QUEUE")
6571 style:UIBarButtonItemStyleDone
6573 action:@selector(queueButtonClicked)
6574 ] autorelease] : [super customButton];
6577 - (void) queueStatusDidChange {
6578 [self applyRightButton];
6581 - (bool) isLoading {
6582 return !Queuing_ && [super isLoading];
6588 /* Refresh Bar {{{ */
6589 @interface RefreshBar : UINavigationBar {
6590 _H<UIProgressIndicator> indicator_;
6591 _H<UITextLabel> prompt_;
6592 _H<UIProgressBar> progress_;
6593 _H<UINavigationButton> cancel_;
6598 @implementation RefreshBar
6600 - (void) positionViews {
6601 CGRect frame = [cancel_ frame];
6602 frame.size = [cancel_ sizeThatFits:frame.size];
6603 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6604 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6605 [cancel_ setFrame:frame];
6607 CGSize prgsize = {75, 100};
6609 [self frame].size.width - prgsize.width - 10,
6610 ([self frame].size.height - prgsize.height) / 2
6612 [progress_ setFrame:prgrect];
6614 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6615 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6616 CGRect indrect = {{indoffset, indoffset}, indsize};
6617 [indicator_ setFrame:indrect];
6619 CGSize prmsize = {215, indsize.height + 4};
6621 indoffset * 2 + indsize.width,
6622 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6624 [prompt_ setFrame:prmrect];
6627 - (void) setFrame:(CGRect)frame {
6628 [super setFrame:frame];
6629 [self positionViews];
6632 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6633 if ((self = [super initWithFrame:frame]) != nil) {
6634 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6636 [self setBarStyle:UIBarStyleBlack];
6638 UIBarStyle barstyle([self _barStyle:NO]);
6639 bool ugly(barstyle == UIBarStyleDefault);
6641 UIProgressIndicatorStyle style = ugly ?
6642 UIProgressIndicatorStyleMediumBrown :
6643 UIProgressIndicatorStyleMediumWhite;
6645 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6646 [(UIProgressIndicator *) indicator_ setStyle:style];
6647 [indicator_ startAnimation];
6648 [self addSubview:indicator_];
6650 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6651 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6652 [prompt_ setBackgroundColor:[UIColor clearColor]];
6653 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6654 [self addSubview:prompt_];
6656 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6657 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6658 [(UIProgressBar *) progress_ setStyle:0];
6659 [self addSubview:progress_];
6661 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6662 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6663 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6664 [cancel_ setBarStyle:barstyle];
6666 [self positionViews];
6670 - (void) setCancellable:(bool)cancellable {
6672 [self addSubview:cancel_];
6674 [cancel_ removeFromSuperview];
6678 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6679 [progress_ setProgress:0];
6683 [self setCancellable:NO];
6686 - (void) setPrompt:(NSString *)prompt {
6687 [prompt_ setText:prompt];
6690 - (void) setProgress:(float)progress {
6691 [progress_ setProgress:progress];
6697 /* Cydia Navigation Controller Interface {{{ */
6698 @interface UINavigationController (Cydia)
6700 - (NSArray *) navigationURLCollection;
6701 - (void) unloadData;
6706 /* Cydia Tab Bar Controller {{{ */
6707 @interface CYTabBarController : UITabBarController <
6708 UITabBarControllerDelegate,
6711 _transient Database *database_;
6712 _H<RefreshBar, 1> refreshbar_;
6716 // XXX: ok, "updatedelegate_"?...
6717 _transient NSObject<CydiaDelegate> *updatedelegate_;
6719 _H<UIViewController> remembered_;
6720 _transient UIViewController *transient_;
6723 - (NSArray *) navigationURLCollection;
6724 - (void) dropBar:(BOOL)animated;
6725 - (void) beginUpdate;
6726 - (void) raiseBar:(BOOL)animated;
6728 - (void) unloadData;
6732 @implementation CYTabBarController
6734 - (void) setUnselectedViewController:(UIViewController *)transient {
6735 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6736 if (transient != nil) {
6737 if (transient_ == nil)
6738 remembered_ = [controllers objectAtIndex:0];
6739 transient_ = transient;
6740 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6741 [controllers replaceObjectAtIndex:0 withObject:transient_];
6742 [self setSelectedIndex:0];
6743 [self setViewControllers:controllers];
6744 [self concealTabBarSelection];
6745 } else if (remembered_ != nil) {
6746 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6747 transient_ = transient;
6748 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6750 [self setViewControllers:controllers];
6751 [self revealTabBarSelection];
6755 - (UIViewController *) unselectedViewController {
6759 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6760 if ([self unselectedViewController])
6761 [self setUnselectedViewController:nil];
6764 - (NSArray *) navigationURLCollection {
6765 NSMutableArray *items([NSMutableArray array]);
6767 // XXX: Should this deal with transient view controllers?
6768 for (id navigation in [self viewControllers]) {
6769 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6771 [items addObject:stack];
6777 - (void) unloadData {
6780 for (UINavigationController *controller in [self viewControllers])
6781 [controller unloadData];
6783 if (UIViewController *selected = [self selectedViewController])
6784 [selected reloadData];
6786 if (UIViewController *unselected = [self unselectedViewController]) {
6787 [unselected unloadData];
6788 [unselected reloadData];
6793 [[NSNotificationCenter defaultCenter] removeObserver:self];
6798 - (id) initWithDatabase:(Database *)database {
6799 if ((self = [super init]) != nil) {
6800 database_ = database;
6801 [self setDelegate:self];
6803 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6804 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6806 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6810 - (void) setUpdate:(NSDate *)date {
6814 - (void) beginUpdate {
6815 [(RefreshBar *) refreshbar_ start];
6818 [updatedelegate_ retainNetworkActivityIndicator];
6822 detachNewThreadSelector:@selector(performUpdate)
6828 - (void) performUpdate {
6829 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6832 status.setDelegate(self);
6833 [database_ updateWithStatus:status];
6836 performSelectorOnMainThread:@selector(completeUpdate)
6844 - (void) stopUpdateWithSelector:(SEL)selector {
6846 [updatedelegate_ releaseNetworkActivityIndicator];
6848 [self raiseBar:YES];
6851 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6854 - (void) completeUpdate {
6857 [self stopUpdateWithSelector:@selector(reloadData)];
6860 - (void) cancelUpdate {
6861 [self stopUpdateWithSelector:@selector(updateData)];
6864 - (void) cancelPressed {
6865 [self cancelUpdate];
6872 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6873 [refreshbar_ setPrompt:[event compoundMessage]];
6876 - (bool) isProgressCancelled {
6880 - (void) setProgressCancellable:(NSNumber *)cancellable {
6881 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6884 - (void) setProgressPercent:(NSNumber *)percent {
6885 [refreshbar_ setProgress:[percent floatValue]];
6888 - (void) setProgressStatus:(NSDictionary *)status {
6890 [self setProgressPercent:[status objectForKey:@"Percent"]];
6893 - (void) setUpdateDelegate:(id)delegate {
6894 updatedelegate_ = delegate;
6897 - (UIView *) transitionView {
6898 if ([self respondsToSelector:@selector(_transitionView)])
6899 return [self _transitionView];
6901 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6904 - (void) dropBar:(BOOL)animated {
6909 UIView *transition([self transitionView]);
6910 [[self view] addSubview:refreshbar_];
6912 CGRect barframe([refreshbar_ frame]);
6914 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6915 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6917 barframe.origin.y = 0;
6919 [refreshbar_ setFrame:barframe];
6922 [UIView beginAnimations:nil context:NULL];
6924 CGRect viewframe = [transition frame];
6925 viewframe.origin.y += barframe.size.height;
6926 viewframe.size.height -= barframe.size.height;
6927 [transition setFrame:viewframe];
6930 [UIView commitAnimations];
6932 // Ensure bar has the proper width for our view, it might have changed
6933 barframe.size.width = viewframe.size.width;
6934 [refreshbar_ setFrame:barframe];
6937 - (void) raiseBar:(BOOL)animated {
6942 UIView *transition([self transitionView]);
6943 [refreshbar_ removeFromSuperview];
6945 CGRect barframe([refreshbar_ frame]);
6948 [UIView beginAnimations:nil context:NULL];
6950 CGRect viewframe = [transition frame];
6951 viewframe.origin.y -= barframe.size.height;
6952 viewframe.size.height += barframe.size.height;
6953 [transition setFrame:viewframe];
6956 [UIView commitAnimations];
6959 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6960 bool dropped(dropped_);
6965 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6971 - (void) statusBarFrameChanged:(NSNotification *)notification {
6981 /* Cydia Navigation Controller Implementation {{{ */
6982 @implementation UINavigationController (Cydia)
6984 - (NSArray *) navigationURLCollection {
6985 NSMutableArray *stack([NSMutableArray array]);
6987 for (CyteViewController *controller in [self viewControllers]) {
6988 NSString *url = [[controller navigationURL] absoluteString];
6990 [stack addObject:url];
6996 - (void) reloadData {
6999 UIViewController *visible([self visibleViewController]);
7001 [visible reloadData];
7003 // on the iPad, this view controller is ALSO visible. :(
7005 if (UIViewController *top = [self topViewController])
7010 - (void) unloadData {
7011 for (CyteViewController *page in [self viewControllers])
7020 /* Cydia:// Protocol {{{ */
7021 @interface CydiaURLProtocol : NSURLProtocol {
7026 @implementation CydiaURLProtocol
7028 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7029 NSURL *url([request URL]);
7033 NSString *scheme([[url scheme] lowercaseString]);
7034 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7036 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7042 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7046 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7047 id<NSURLProtocolClient> client([self client]);
7049 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7051 NSData *data(UIImagePNGRepresentation(icon));
7053 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7054 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7055 [client URLProtocol:self didLoadData:data];
7056 [client URLProtocolDidFinishLoading:self];
7060 - (void) startLoading {
7061 id<NSURLProtocolClient> client([self client]);
7062 NSURLRequest *request([self request]);
7064 NSURL *url([request URL]);
7065 NSString *href([url absoluteString]);
7066 NSString *scheme([[url scheme] lowercaseString]);
7070 if ([scheme isEqualToString:@"cydia"])
7071 path = [href substringFromIndex:8];
7072 else if ([scheme isEqualToString:@"about"])
7073 path = [href substringFromIndex:12];
7074 else _assert(false);
7076 NSRange slash([path rangeOfString:@"/"]);
7079 if (slash.location == NSNotFound) {
7083 command = [path substringToIndex:slash.location];
7084 path = [path substringFromIndex:(slash.location + 1)];
7087 Database *database([Database sharedInstance]);
7089 if ([command isEqualToString:@"package-icon"]) {
7092 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7093 Package *package([database packageWithName:path]);
7097 UIImage *icon([package icon]);
7098 [self _returnPNGWithImage:icon forRequest:request];
7099 } else if ([command isEqualToString:@"source-icon"]) {
7102 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7103 NSString *source(Simplify(path));
7104 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7106 icon = [UIImage applicationImageNamed:@"unknown.png"];
7107 [self _returnPNGWithImage:icon forRequest:request];
7108 } else if ([command isEqualToString:@"uikit-image"]) {
7111 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7112 UIImage *icon(_UIImageWithName(path));
7113 [self _returnPNGWithImage:icon forRequest:request];
7114 } else if ([command isEqualToString:@"section-icon"]) {
7117 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7118 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7120 icon = [UIImage applicationImageNamed:@"unknown.png"];
7121 [self _returnPNGWithImage:icon forRequest:request];
7123 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7127 - (void) stopLoading {
7133 /* Section Controller {{{ */
7134 @interface SectionController : FilteredPackageListController {
7135 _H<NSString> section_;
7138 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7142 @implementation SectionController
7144 - (NSURL *) navigationURL {
7145 NSString *name = section_;
7149 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7152 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7155 title = UCLocalize("ALL_PACKAGES");
7156 else if (![name isEqual:@""])
7157 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7159 title = UCLocalize("NO_SECTION");
7161 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7168 /* Sections Controller {{{ */
7169 @interface SectionsController : CyteViewController <
7170 UITableViewDataSource,
7173 _transient Database *database_;
7174 _H<NSMutableArray> sections_;
7175 _H<NSMutableArray> filtered_;
7176 _H<UITableView, 2> list_;
7179 - (id) initWithDatabase:(Database *)database;
7180 - (void) editButtonClicked;
7184 @implementation SectionsController
7186 - (NSURL *) navigationURL {
7187 return [NSURL URLWithString:@"cydia://sections"];
7190 - (void) updateNavigationItem {
7191 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7192 if ([sections_ count] == 0) {
7193 [[self navigationItem] setRightBarButtonItem:nil];
7195 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7196 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7198 action:@selector(editButtonClicked)
7199 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7203 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7204 [super setEditing:editing animated:animated];
7209 [delegate_ updateData];
7211 [self updateNavigationItem];
7214 - (void) viewDidAppear:(BOOL)animated {
7215 [super viewDidAppear:animated];
7216 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7219 - (void) viewWillDisappear:(BOOL)animated {
7220 [super viewWillDisappear:animated];
7221 if ([self isEditing]) [self setEditing:NO];
7224 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7225 Section *section = nil;
7226 int index = [indexPath row];
7227 if (![self isEditing]) {
7230 section = [filtered_ objectAtIndex:index];
7232 section = [sections_ objectAtIndex:index];
7237 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7238 if ([self isEditing])
7239 return [sections_ count];
7241 return [filtered_ count] + 1;
7244 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7248 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7249 static NSString *reuseIdentifier = @"SectionCell";
7251 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7253 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7255 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7260 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7261 if ([self isEditing])
7264 Section *section = [self sectionAtIndexPath:indexPath];
7266 SectionController *controller = [[[SectionController alloc]
7267 initWithDatabase:database_
7268 section:[section name]
7270 [controller setDelegate:delegate_];
7272 [[self navigationController] pushViewController:controller animated:YES];
7276 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7278 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7279 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7280 [list_ setRowHeight:45.0f];
7281 [(UITableView *) list_ setDataSource:self];
7282 [list_ setDelegate:self];
7283 [[self view] addSubview:list_];
7286 - (void) viewDidLoad {
7287 [super viewDidLoad];
7289 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7292 - (void) releaseSubviews {
7298 [super releaseSubviews];
7301 - (id) initWithDatabase:(Database *)database {
7302 if ((self = [super init]) != nil) {
7303 database_ = database;
7307 - (void) reloadData {
7310 NSArray *packages = [database_ packages];
7312 sections_ = [NSMutableArray arrayWithCapacity:16];
7313 filtered_ = [NSMutableArray arrayWithCapacity:16];
7315 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7318 for (Package *package in packages) {
7319 NSString *name([package section]);
7320 NSString *key(name == nil ? @"" : name);
7324 _profile(SectionsView$reloadData$Section)
7325 section = [sections objectForKey:key];
7326 if (section == nil) {
7327 _profile(SectionsView$reloadData$Section$Allocate)
7328 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7329 [sections setObject:section forKey:key];
7334 [section addToCount];
7336 _profile(SectionsView$reloadData$Filter)
7337 if (![package valid] || ![package visible])
7345 [sections_ addObjectsFromArray:[sections allValues]];
7347 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7349 for (Section *section in (id) sections_) {
7350 size_t count([section row]);
7354 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7355 [section setCount:count];
7356 [filtered_ addObject:section];
7359 [self updateNavigationItem];
7364 - (void) editButtonClicked {
7365 [self setEditing:![self isEditing] animated:YES];
7371 /* Changes Controller {{{ */
7372 @interface ChangesController : CyteViewController <
7373 UITableViewDataSource,
7376 _transient Database *database_;
7378 _H<NSArray> packages_;
7379 _H<NSMutableArray> sections_;
7380 _H<UITableView, 2> list_;
7384 - (id) initWithDatabase:(Database *)database;
7388 @implementation ChangesController
7390 - (NSURL *) navigationURL {
7391 return [NSURL URLWithString:@"cydia://changes"];
7394 - (void) viewDidAppear:(BOOL)animated {
7395 [super viewDidAppear:animated];
7396 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7399 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7400 NSInteger count([sections_ count]);
7401 return count == 0 ? 1 : count;
7404 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7405 if ([sections_ count] == 0)
7407 return [[sections_ objectAtIndex:section] name];
7410 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7411 if ([sections_ count] == 0)
7413 return [[sections_ objectAtIndex:section] count];
7416 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7417 @synchronized (database_) {
7418 if ([database_ era] != era_)
7421 NSUInteger sectionIndex([path section]);
7422 if (sectionIndex >= [sections_ count])
7424 Section *section([sections_ objectAtIndex:sectionIndex]);
7425 NSInteger row([path row]);
7426 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7429 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7430 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7432 cell = [[[PackageCell alloc] init] autorelease];
7434 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7435 [cell setPackage:package asSummary:false];
7439 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7440 Package *package([self packageAtIndexPath:path]);
7441 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7442 [view setDelegate:delegate_];
7443 [[self navigationController] pushViewController:view animated:YES];
7447 - (void) refreshButtonClicked {
7448 [delegate_ beginUpdate];
7449 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7452 - (void) upgradeButtonClicked {
7453 [delegate_ distUpgrade];
7454 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7458 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7460 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7461 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7462 [list_ setRowHeight:73];
7463 [(UITableView *) list_ setDataSource:self];
7464 [list_ setDelegate:self];
7465 [[self view] addSubview:list_];
7468 - (void) viewDidLoad {
7469 [super viewDidLoad];
7471 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7474 - (void) releaseSubviews {
7480 [super releaseSubviews];
7483 - (id) initWithDatabase:(Database *)database {
7484 if ((self = [super init]) != nil) {
7485 database_ = database;
7489 - (NSMutableArray *) _reloadPackages {
7490 @synchronized (database_) {
7491 era_ = [database_ era];
7492 NSArray *packages([database_ packages]);
7494 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7497 _profile(ChangesController$_reloadPackages$Filter)
7498 for (Package *package in packages)
7499 if ([package upgradableAndEssential:YES] || [package visible])
7500 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7503 _profile(ChangesController$_reloadPackages$radixSort)
7504 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7511 - (void) _reloadData {
7516 UIProgressHUD *hud([delegate_ addProgressHUD]);
7517 [hud setText:UCLocalize("LOADING")];
7518 //NSLog(@"HUD:%@::%@", delegate_, hud);
7519 packages = [self yieldToSelector:@selector(_reloadPackages)];
7520 [delegate_ removeProgressHUD:hud];
7522 packages = [self _reloadPackages];
7525 @synchronized (database_) {
7526 if (era_ != [database_ era])
7529 packages_ = packages;
7530 sections_ = [NSMutableArray arrayWithCapacity:16];
7532 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7533 Section *ignored = nil;
7534 Section *section = nil;
7538 bool unseens = false;
7540 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7542 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7543 Package *package = [packages_ objectAtIndex:offset];
7545 BOOL uae = [package upgradableAndEssential:YES];
7549 time_t seen([package seen]);
7551 if (section == nil || last != seen) {
7555 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7558 _profile(ChangesController$reloadData$Allocate)
7559 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7560 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7561 [sections_ addObject:section];
7565 [section addToCount];
7566 } else if ([package ignored]) {
7567 if (ignored == nil) {
7568 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7570 [ignored addToCount];
7573 [upgradable addToCount];
7578 CFRelease(formatter);
7581 Section *last = [sections_ lastObject];
7582 size_t count = [last count];
7583 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7584 [sections_ removeLastObject];
7587 if ([ignored count] != 0)
7588 [sections_ insertObject:ignored atIndex:0];
7590 [sections_ insertObject:upgradable atIndex:0];
7594 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7595 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7596 style:UIBarButtonItemStylePlain
7598 action:@selector(upgradeButtonClicked)
7599 ] autorelease]) animated:YES];
7601 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7602 initWithTitle:UCLocalize("REFRESH")
7603 style:UIBarButtonItemStylePlain
7605 action:@selector(refreshButtonClicked)
7606 ] autorelease]) animated:YES];
7611 - (void) reloadData {
7613 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7618 /* Search Controller {{{ */
7619 @interface SearchController : FilteredPackageListController <
7622 _H<UISearchBar, 1> search_;
7626 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7627 - (void) reloadData;
7631 @implementation SearchController
7633 - (NSURL *) navigationURL {
7634 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7635 return [NSURL URLWithString:@"cydia://search"];
7637 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7640 - (void) useSearch {
7641 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7646 - (void) viewWillAppear:(BOOL)animated {
7647 [super viewWillAppear:animated];
7649 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7653 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7654 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7659 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7660 [search_ resignFirstResponder];
7664 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7665 [search_ setText:@""];
7666 [self searchBarButtonClicked:searchBar];
7669 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7670 [self searchBarButtonClicked:searchBar];
7673 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7674 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7678 - (bool) shouldYield {
7682 - (bool) shouldBlock {
7683 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7686 - (bool) isSummarized {
7687 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7690 - (bool) showsSections {
7694 - (NSMutableArray *) _reloadPackages {
7695 NSMutableArray *packages([super _reloadPackages]);
7696 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7697 [packages radixSortUsingSelector:@selector(rank)];
7701 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7702 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7703 search_ = [[[UISearchBar alloc] init] autorelease];
7704 [search_ setDelegate:self];
7707 [search_ setText:query];
7711 - (void) viewDidAppear:(BOOL)animated {
7712 [super viewDidAppear:animated];
7714 if (!searchloaded_) {
7715 searchloaded_ = YES;
7716 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7717 [search_ layoutSubviews];
7718 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7720 UITextField *textField;
7721 if ([search_ respondsToSelector:@selector(searchField)])
7722 textField = [search_ searchField];
7724 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7726 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7727 [textField setEnablesReturnKeyAutomatically:NO];
7728 [[self navigationItem] setTitleView:textField];
7732 - (void) reloadData {
7733 id object([search_ text]);
7734 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7735 object = [object componentsSeparatedByString:@" "];
7737 [self setObject:object];
7743 - (void) didSelectPackage:(Package *)package {
7744 [search_ resignFirstResponder];
7745 [super didSelectPackage:package];
7750 /* Package Settings Controller {{{ */
7751 @interface PackageSettingsController : CyteViewController <
7752 UITableViewDataSource,
7755 _transient Database *database_;
7757 _H<Package> package_;
7758 _H<UITableView, 2> table_;
7759 _H<UISwitch> subscribedSwitch_;
7760 _H<UISwitch> ignoredSwitch_;
7761 _H<UITableViewCell> subscribedCell_;
7762 _H<UITableViewCell> ignoredCell_;
7765 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7769 @implementation PackageSettingsController
7771 - (NSURL *) navigationURL {
7772 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7775 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7776 if (package_ == nil)
7779 if ([package_ installed] == nil)
7785 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7786 if (package_ == nil)
7789 // both sections contain just one item right now.
7793 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7797 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7799 return UCLocalize("SHOW_ALL_CHANGES_EX");
7801 return UCLocalize("IGNORE_UPGRADES_EX");
7804 - (void) onSubscribed:(id)control {
7805 bool value([control isOn]);
7806 if (package_ == nil)
7808 if ([package_ setSubscribed:value])
7809 [delegate_ updateData];
7812 - (void) _updateIgnored {
7813 const char *package([name_ UTF8String]);
7814 bool on([ignoredSwitch_ isOn]);
7816 pid_t pid(ExecFork());
7818 FILE *dpkg(popen("dpkg --set-selections", "w"));
7819 fwrite(package, strlen(package), 1, dpkg);
7822 fwrite(" hold\n", 6, 1, dpkg);
7824 fwrite(" install\n", 9, 1, dpkg);
7834 int result(waitpid(pid, &status, 0));
7837 _assert(result == pid);
7843 - (void) onIgnored:(id)control {
7844 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7845 [invocation setTarget:self];
7846 [invocation setSelector:@selector(_updateIgnored)];
7848 [delegate_ reloadDataWithInvocation:invocation];
7851 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7852 if (package_ == nil)
7855 switch ([indexPath section]) {
7856 case 0: return subscribedCell_;
7857 case 1: return ignoredCell_;
7866 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7868 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7869 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7870 [(UITableView *) table_ setDataSource:self];
7871 [table_ setDelegate:self];
7872 [[self view] addSubview:table_];
7874 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7875 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7876 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7878 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7879 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7880 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7882 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7883 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7884 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7885 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7887 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7888 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7889 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7890 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7893 - (void) viewDidLoad {
7894 [super viewDidLoad];
7896 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7899 - (void) releaseSubviews {
7901 subscribedCell_ = nil;
7903 ignoredSwitch_ = nil;
7904 subscribedSwitch_ = nil;
7906 [super releaseSubviews];
7909 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7910 if ((self = [super init]) != nil) {
7911 database_ = database;
7916 - (void) reloadData {
7919 package_ = [database_ packageWithName:name_];
7921 if (package_ != nil) {
7922 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7923 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7924 } // XXX: what now, G?
7926 [table_ reloadData];
7932 /* Installed Controller {{{ */
7933 @interface InstalledController : FilteredPackageListController {
7937 - (id) initWithDatabase:(Database *)database;
7939 - (void) updateRoleButton;
7940 - (void) queueStatusDidChange;
7944 @implementation InstalledController
7946 - (NSURL *) navigationURL {
7947 return [NSURL URLWithString:@"cydia://installed"];
7950 - (id) initWithDatabase:(Database *)database {
7951 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7952 [self updateRoleButton];
7953 [self queueStatusDidChange];
7958 - (void) queueButtonClicked {
7963 - (void) queueStatusDidChange {
7967 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7968 initWithTitle:UCLocalize("QUEUE")
7969 style:UIBarButtonItemStyleDone
7971 action:@selector(queueButtonClicked)
7974 [[self navigationItem] setLeftBarButtonItem:nil];
7980 - (void) updateRoleButton {
7981 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7982 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7983 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7984 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7986 action:@selector(roleButtonClicked)
7990 - (void) roleButtonClicked {
7991 [self setObject:[NSNumber numberWithBool:expert_]];
7995 [self updateRoleButton];
8001 /* Source Cell {{{ */
8002 @interface SourceCell : CyteTableViewCell <
8003 CyteTableViewCellDelegate
8006 _H<NSString> origin_;
8007 _H<NSString> label_;
8010 - (void) setSource:(Source *)source;
8014 @implementation SourceCell
8016 - (void) _setImage:(UIImage *)image {
8018 [content_ setNeedsDisplay];
8021 - (void) _setSource:(Source *)source {
8022 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8024 if (NSString *base = [source base])
8025 if ([base length] != 0) {
8026 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
8028 if (NSData *data = [NSURLConnection
8029 sendSynchronousRequest:[NSURLRequest
8031 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8035 returningResponse:NULL
8038 if (UIImage *image = [UIImage imageWithData:data])
8039 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
8045 - (void) setSource:(Source *)source {
8046 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8048 origin_ = [source name];
8049 label_ = [source uri];
8051 [content_ setNeedsDisplay];
8053 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
8056 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8057 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8058 UIView *content([self contentView]);
8059 CGRect bounds([content bounds]);
8061 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8062 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8063 [content_ setBackgroundColor:[UIColor whiteColor]];
8064 [content addSubview:content_];
8066 [content_ setDelegate:self];
8067 [content_ setOpaque:YES];
8069 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8073 - (NSString *) accessibilityLabel {
8077 - (void) drawContentRect:(CGRect)rect {
8078 bool highlighted(highlighted_);
8079 float width(rect.size.width);
8082 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8089 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 60) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8093 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 75) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8098 /* Source Controller {{{ */
8099 @interface SourceController : FilteredPackageListController {
8100 _transient Source *source_;
8104 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8108 @implementation SourceController
8110 - (NSURL *) navigationURL {
8111 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8114 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8115 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8117 key_ = [source key];
8121 - (void) reloadData {
8122 source_ = [database_ sourceWithKey:key_];
8123 key_ = [source_ key];
8124 [self setObject:source_];
8126 [[self navigationItem] setTitle:[source_ label]];
8133 /* Sources Controller {{{ */
8134 @interface SourcesController : CyteViewController <
8135 UITableViewDataSource,
8138 _transient Database *database_;
8139 _H<UITableView, 2> list_;
8140 _H<NSMutableArray> sources_;
8144 _H<UIProgressHUD> hud_;
8147 //NSURLConnection *installer_;
8148 NSURLConnection *trivial_;
8149 NSURLConnection *trivial_bz2_;
8150 NSURLConnection *trivial_gz_;
8151 //NSURLConnection *automatic_;
8156 - (id) initWithDatabase:(Database *)database;
8157 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8161 @implementation SourcesController
8163 - (void) _releaseConnection:(NSURLConnection *)connection {
8164 if (connection != nil) {
8165 [connection cancel];
8166 //[connection setDelegate:nil];
8167 [connection release];
8172 //[self _releaseConnection:installer_];
8173 [self _releaseConnection:trivial_];
8174 [self _releaseConnection:trivial_gz_];
8175 [self _releaseConnection:trivial_bz2_];
8176 //[self _releaseConnection:automatic_];
8181 - (NSURL *) navigationURL {
8182 return [NSURL URLWithString:@"cydia://sources"];
8185 - (void) viewDidAppear:(BOOL)animated {
8186 [super viewDidAppear:animated];
8187 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8190 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8191 return offset_ == 0 ? 1 : 2;
8194 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8195 switch (section + (offset_ == 0 ? 1 : 0)) {
8196 case 0: return UCLocalize("ENTERED_BY_USER");
8197 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8203 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8204 int count = [sources_ count];
8206 case 0: return (offset_ == 0 ? count : offset_);
8207 case 1: return count - offset_;
8213 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8215 switch (indexPath.section) {
8216 case 0: idx = indexPath.row; break;
8217 case 1: idx = indexPath.row + offset_; break;
8221 return [sources_ objectAtIndex:idx];
8224 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8225 static NSString *cellIdentifier = @"SourceCell";
8227 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8228 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8229 [cell setSource:[self sourceAtIndexPath:indexPath]];
8230 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8235 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8236 Source *source = [self sourceAtIndexPath:indexPath];
8238 SourceController *controller = [[[SourceController alloc]
8239 initWithDatabase:database_
8243 [controller setDelegate:delegate_];
8245 [[self navigationController] pushViewController:controller animated:YES];
8248 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8249 Source *source = [self sourceAtIndexPath:indexPath];
8250 return [source record] != nil;
8253 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8254 if (editingStyle == UITableViewCellEditingStyleDelete) {
8255 Source *source = [self sourceAtIndexPath:indexPath];
8256 [Sources_ removeObjectForKey:[source key]];
8257 [delegate_ syncData];
8262 [delegate_ addTrivialSource:href_];
8263 [delegate_ syncData];
8266 - (NSString *) getWarning {
8267 NSString *href(href_);
8268 NSRange colon([href rangeOfString:@"://"]);
8269 if (colon.location != NSNotFound)
8270 href = [href substringFromIndex:(colon.location + 3)];
8271 href = [href stringByAddingPercentEscapes];
8272 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8273 href = [href stringByCachingURLWithCurrentCDN];
8275 NSURL *url([NSURL URLWithString:href]);
8277 NSStringEncoding encoding;
8278 NSError *error(nil);
8280 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8281 return [warning length] == 0 ? nil : warning;
8285 - (void) _endConnection:(NSURLConnection *)connection {
8286 // XXX: the memory management in this method is horribly awkward
8288 NSURLConnection **field = NULL;
8289 if (connection == trivial_)
8291 else if (connection == trivial_bz2_)
8292 field = &trivial_bz2_;
8293 else if (connection == trivial_gz_)
8294 field = &trivial_gz_;
8295 _assert(field != NULL);
8296 [connection release];
8301 trivial_bz2_ == nil &&
8304 [delegate_ releaseNetworkActivityIndicator];
8306 [delegate_ removeProgressHUD:hud_];
8312 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8315 UIAlertView *alert = [[[UIAlertView alloc]
8316 initWithTitle:UCLocalize("SOURCE_WARNING")
8319 cancelButtonTitle:UCLocalize("CANCEL")
8321 UCLocalize("ADD_ANYWAY"),
8325 [alert setContext:@"warning"];
8326 [alert setNumberOfRows:1];
8330 } else if (error_ != nil) {
8331 UIAlertView *alert = [[[UIAlertView alloc]
8332 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8333 message:[error_ localizedDescription]
8335 cancelButtonTitle:UCLocalize("OK")
8336 otherButtonTitles:nil
8339 [alert setContext:@"urlerror"];
8342 UIAlertView *alert = [[[UIAlertView alloc]
8343 initWithTitle:UCLocalize("NOT_REPOSITORY")
8344 message:UCLocalize("NOT_REPOSITORY_EX")
8346 cancelButtonTitle:UCLocalize("OK")
8347 otherButtonTitles:nil
8350 [alert setContext:@"trivial"];
8359 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8360 switch ([response statusCode]) {
8366 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8367 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8369 [self _endConnection:connection];
8372 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8373 [self _endConnection:connection];
8376 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8377 NSURL *url([NSURL URLWithString:href]);
8379 NSMutableURLRequest *request = [NSMutableURLRequest
8381 cachePolicy:NSURLRequestUseProtocolCachePolicy
8382 timeoutInterval:120.0
8385 [request setHTTPMethod:method];
8387 if (Machine_ != NULL)
8388 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8390 if ([url isCydiaSecure]) {
8391 if (UniqueID_ != nil)
8392 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8395 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8398 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8399 NSString *context([alert context]);
8401 if ([context isEqualToString:@"source"]) {
8404 NSString *href = [[alert textField] text];
8406 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8408 if (![href hasSuffix:@"/"])
8409 href_ = [href stringByAppendingString:@"/"];
8413 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8414 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8415 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8416 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8420 // XXX: this is stupid
8421 hud_ = [delegate_ addProgressHUD];
8422 [hud_ setText:UCLocalize("VERIFYING_URL")];
8423 [delegate_ retainNetworkActivityIndicator];
8432 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8433 } else if ([context isEqualToString:@"trivial"])
8434 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8435 else if ([context isEqualToString:@"urlerror"])
8436 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8437 else if ([context isEqualToString:@"warning"]) {
8451 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8456 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8458 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8459 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8460 [list_ setRowHeight:53];
8461 [(UITableView *) list_ setDataSource:self];
8462 [list_ setDelegate:self];
8463 [[self view] addSubview:list_];
8466 - (void) viewDidLoad {
8467 [super viewDidLoad];
8469 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8470 [self updateButtonsForEditingStatus:NO animated:NO];
8473 - (void) releaseSubviews {
8478 [super releaseSubviews];
8481 - (id) initWithDatabase:(Database *)database {
8482 if ((self = [super init]) != nil) {
8483 database_ = database;
8487 - (void) reloadData {
8491 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8494 sources_ = [NSMutableArray arrayWithCapacity:16];
8495 [sources_ addObjectsFromArray:[database_ sources]];
8497 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8500 int count([sources_ count]);
8502 for (int i = 0; i != count; i++) {
8503 if ([[sources_ objectAtIndex:i] record] == nil)
8508 [list_ setEditing:NO];
8509 [self updateButtonsForEditingStatus:NO animated:NO];
8513 - (void) showAddSourcePrompt {
8514 UIAlertView *alert = [[[UIAlertView alloc]
8515 initWithTitle:UCLocalize("ENTER_APT_URL")
8518 cancelButtonTitle:UCLocalize("CANCEL")
8520 UCLocalize("ADD_SOURCE"),
8524 [alert setContext:@"source"];
8526 [alert setNumberOfRows:1];
8527 [alert addTextFieldWithValue:@"http://" label:@""];
8529 UITextInputTraits *traits = [[alert textField] textInputTraits];
8530 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8531 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8532 [traits setKeyboardType:UIKeyboardTypeURL];
8533 // XXX: UIReturnKeyDone
8534 [traits setReturnKeyType:UIReturnKeyNext];
8539 - (void) addButtonClicked {
8540 [self showAddSourcePrompt];
8543 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8544 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8545 initWithTitle:UCLocalize("ADD")
8546 style:UIBarButtonItemStylePlain
8548 action:@selector(addButtonClicked)
8549 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8551 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8552 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8553 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8555 action:@selector(editButtonClicked)
8556 ] autorelease] animated:animated];
8558 if (IsWildcat_ && !editing)
8559 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8560 initWithTitle:UCLocalize("SETTINGS")
8561 style:UIBarButtonItemStylePlain
8563 action:@selector(settingsButtonClicked)
8567 - (void) settingsButtonClicked {
8568 [delegate_ showSettings];
8571 - (void) editButtonClicked {
8572 [list_ setEditing:![list_ isEditing] animated:YES];
8574 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8580 /* Settings Controller {{{ */
8581 @interface SettingsController : CyteViewController <
8582 UITableViewDataSource,
8585 _transient Database *database_;
8586 // XXX: ok, "roledelegate_"?...
8587 _transient id roledelegate_;
8588 _H<UITableView, 2> table_;
8589 _H<UISegmentedControl> segment_;
8590 _H<UIView> container_;
8593 - (void) showDoneButton;
8594 - (void) resizeSegmentedControl;
8598 @implementation SettingsController
8601 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8603 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8604 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8605 [table_ setDelegate:self];
8606 [(UITableView *) table_ setDataSource:self];
8607 [[self view] addSubview:table_];
8609 NSArray *items = [NSArray arrayWithObjects:
8611 UCLocalize("HACKER"),
8612 UCLocalize("DEVELOPER"),
8614 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8615 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8616 [container_ addSubview:segment_];
8619 - (void) viewDidLoad {
8620 [super viewDidLoad];
8622 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8625 if ([Role_ isEqualToString:@"User"]) index = 0;
8626 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8627 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8629 [segment_ setSelectedSegmentIndex:index];
8630 [self showDoneButton];
8633 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8634 [self resizeSegmentedControl];
8637 - (void) releaseSubviews {
8642 [super releaseSubviews];
8645 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8646 if ((self = [super init]) != nil) {
8647 database_ = database;
8648 roledelegate_ = delegate;
8652 - (void) resizeSegmentedControl {
8653 CGFloat width = [[self view] frame].size.width;
8654 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8657 - (void) viewWillAppear:(BOOL)animated {
8658 [super viewWillAppear:animated];
8660 [self resizeSegmentedControl];
8663 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8664 [self resizeSegmentedControl];
8667 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8668 [self resizeSegmentedControl];
8672 NSString *role(nil);
8674 switch ([segment_ selectedSegmentIndex]) {
8675 case 0: role = @"User"; break;
8676 case 1: role = @"Hacker"; break;
8677 case 2: role = @"Developer"; break;
8682 if (![role isEqualToString:Role_]) {
8683 bool rolling(Role_ == nil);
8686 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8690 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8694 [roledelegate_ loadData];
8696 [roledelegate_ updateData];
8700 - (void) segmentChanged:(UISegmentedControl *)control {
8701 [self showDoneButton];
8704 - (void) saveAndClose {
8707 [[self navigationItem] setRightBarButtonItem:nil];
8708 [[self navigationController] dismissModalViewControllerAnimated:YES];
8711 - (void) doneButtonClicked {
8712 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8713 [spinner startAnimating];
8714 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8715 [[self navigationItem] setRightBarButtonItem:spinItem];
8717 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8720 - (void) showDoneButton {
8721 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8722 initWithTitle:UCLocalize("DONE")
8723 style:UIBarButtonItemStyleDone
8725 action:@selector(doneButtonClicked)
8726 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8729 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8730 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8734 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8738 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8739 return nil; // This method is required by the protocol.
8742 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8744 return UCLocalize("ROLE_EX");
8746 return [NSString stringWithFormat:
8747 @"%@: %@\n%@: %@\n%@: %@",
8748 UCLocalize("USER"), UCLocalize("USER_EX"),
8749 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8750 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8755 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8756 return section == 3 ? 44.0f : 0;
8759 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8760 return section == 3 ? container_ : nil;
8763 - (void) reloadData {
8766 [table_ reloadData];
8771 /* Stash Controller {{{ */
8772 @interface StashController : CyteViewController {
8773 _H<UIActivityIndicatorView> spinner_;
8774 _H<UILabel> status_;
8775 _H<UILabel> caption_;
8780 @implementation StashController
8783 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8784 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8786 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8787 CGRect spinrect = [spinner_ frame];
8788 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8789 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8790 [spinner_ setFrame:spinrect];
8791 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8792 [[self view] addSubview:spinner_];
8793 [spinner_ startAnimating];
8796 captrect.size.width = [[self view] frame].size.width;
8797 captrect.size.height = 40.0f;
8798 captrect.origin.x = 0;
8799 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8800 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8801 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8802 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8803 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8804 [caption_ setTextColor:[UIColor whiteColor]];
8805 [caption_ setBackgroundColor:[UIColor clearColor]];
8806 [caption_ setShadowColor:[UIColor blackColor]];
8807 [caption_ setTextAlignment:UITextAlignmentCenter];
8808 [[self view] addSubview:caption_];
8811 statusrect.size.width = [[self view] frame].size.width;
8812 statusrect.size.height = 30.0f;
8813 statusrect.origin.x = 0;
8814 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8815 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8816 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8817 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8818 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8819 [status_ setTextColor:[UIColor whiteColor]];
8820 [status_ setBackgroundColor:[UIColor clearColor]];
8821 [status_ setShadowColor:[UIColor blackColor]];
8822 [status_ setTextAlignment:UITextAlignmentCenter];
8823 [[self view] addSubview:status_];
8826 - (void) releaseSubviews {
8831 [super releaseSubviews];
8837 @interface CYURLCache : SDURLCache {
8842 @implementation CYURLCache
8844 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8847 else if ([event isEqualToString:@"no-cache"])
8849 else if ([event isEqualToString:@"store"])
8851 else if ([event isEqualToString:@"invalid"])
8853 else if ([event isEqualToString:@"memory"])
8855 else if ([event isEqualToString:@"disk"])
8857 else if ([event isEqualToString:@"miss"])
8860 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8864 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8865 if (NSURLResponse *response = [cached response])
8866 if (NSString *mime = [response MIMEType])
8867 if ([mime isEqualToString:@"text/cache-manifest"]) {
8868 NSURL *url([response URL]);
8871 NSLog(@"###: %@", [url absoluteString]);
8874 @synchronized (HostConfig_) {
8875 [CachedURLs_ addObject:url];
8879 [super storeCachedResponse:cached forRequest:request];
8884 @interface Cydia : UIApplication <
8885 ConfirmationControllerDelegate,
8888 UINavigationControllerDelegate,
8889 UITabBarControllerDelegate
8891 _H<UIWindow> window_;
8892 _H<CYTabBarController> tabbar_;
8893 _H<CydiaLoadingViewController> emulated_;
8895 _H<NSMutableArray> essential_;
8896 _H<NSMutableArray> broken_;
8898 Database *database_;
8900 _H<NSURL> starturl_;
8905 _H<StashController> stash_;
8914 @implementation Cydia
8916 - (void) beginUpdate {
8917 [tabbar_ beginUpdate];
8921 return [tabbar_ updating];
8925 if ([broken_ count] != 0) {
8926 int count = [broken_ count];
8928 UIAlertView *alert = [[[UIAlertView alloc]
8929 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8930 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8932 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8934 UCLocalize("TEMPORARY_IGNORE"),
8938 [alert setContext:@"fixhalf"];
8939 [alert setNumberOfRows:2];
8941 } else if (!Ignored_ && [essential_ count] != 0) {
8942 int count = [essential_ count];
8944 UIAlertView *alert = [[[UIAlertView alloc]
8945 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8946 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8948 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8950 UCLocalize("UPGRADE_ESSENTIAL"),
8951 UCLocalize("COMPLETE_UPGRADE"),
8955 [alert setContext:@"upgrade"];
8960 - (void) returnToCydia {
8964 - (void) _saveConfig {
8970 NSString *error(nil);
8972 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8974 NSError *error(nil);
8975 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8976 NSLog(@"failure to save metadata data: %@", error);
8981 NSLog(@"failure to serialize metadata: %@", error);
8988 // Navigation controller for the queuing badge.
8989 - (UINavigationController *) queueNavigationController {
8990 NSArray *controllers = [tabbar_ viewControllers];
8991 return [controllers objectAtIndex:3];
8994 - (void) unloadData {
8995 [tabbar_ unloadData];
8998 - (void) _updateData {
9002 UINavigationController *navigation = [self queueNavigationController];
9004 id queuedelegate = nil;
9005 if ([[navigation viewControllers] count] > 0)
9006 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9008 [queuedelegate queueStatusDidChange];
9009 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9012 - (void) _refreshIfPossible:(NSDate *)update {
9013 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9015 bool recently = false;
9016 if (update != nil) {
9017 NSTimeInterval interval([update timeIntervalSinceNow]);
9018 if (interval <= 0 && interval > -(15*60))
9022 // Don't automatic refresh if:
9023 // - We already refreshed recently.
9024 // - We already auto-refreshed this launch.
9025 // - Auto-refresh is disabled.
9026 if (recently || loaded_ || ManualRefresh) {
9027 // If we are cancelling, we need to make sure it knows it's already loaded.
9030 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9032 // We are going to load, so remember that.
9035 SCNetworkReachabilityFlags flags; {
9036 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9037 SCNetworkReachabilityGetFlags(reachability, &flags);
9038 CFRelease(reachability);
9041 // XXX: this elaborate mess is what Apple is using to determine this? :(
9042 // XXX: do we care if the user has to intervene? maybe that's ok?
9044 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9045 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9046 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9047 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9048 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9049 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9053 // If we can reach the server, auto-refresh!
9055 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9061 - (void) refreshIfPossible {
9062 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9065 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9066 @synchronized (self) {
9067 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9068 [hud setText:UCLocalize("RELOADING_DATA")];
9070 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9073 [self removeProgressHUD:hud];
9077 [essential_ removeAllObjects];
9078 [broken_ removeAllObjects];
9080 NSArray *packages([database_ packages]);
9081 for (Package *package in packages) {
9083 [broken_ addObject:package];
9084 if ([package upgradableAndEssential:NO]) {
9085 if ([package essential])
9086 [essential_ addObject:package];
9091 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9094 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9095 [changesItem setBadgeValue:badge];
9096 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9097 [self setApplicationIconBadgeNumber:changes];
9100 [changesItem setBadgeValue:nil];
9101 [changesItem setAnimatedBadge:NO];
9102 [self setApplicationIconBadgeNumber:0];
9108 - (void) updateData {
9114 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9117 - (void) disemulate {
9118 if (emulated_ == nil)
9121 [window_ addSubview:[tabbar_ view]];
9122 [[emulated_ view] removeFromSuperview];
9124 [window_ setUserInteractionEnabled:YES];
9127 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9128 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9130 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9132 UIViewController *parent;
9133 if (emulated_ == nil)
9142 [parent presentModalViewController:navigation animated:YES];
9145 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9146 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9148 if (navigation != nil)
9149 [navigation pushViewController:progress animated:YES];
9151 [self presentModalViewController:progress force:YES];
9153 [progress invoke:invocation withTitle:title];
9157 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9158 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9161 - (void) repairWithInvocation:(NSInvocation *)invocation {
9163 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9167 - (void) repairWithSelector:(SEL)selector {
9168 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9171 - (void) reloadData {
9172 [self reloadDataWithInvocation:nil];
9173 if ([database_ progressDelegate] == nil)
9179 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9182 - (void) addSource:(NSDictionary *) source {
9186 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9187 AddSource(href, distribution, sections);
9190 - (void) addTrivialSource:(NSString *)href {
9191 AddSource(href, @"./");
9194 - (void) updateValues {
9199 pkgProblemResolver *resolver = [database_ resolver];
9201 resolver->InstallProtect();
9202 if (!resolver->Resolve(true))
9207 // XXX: this is a really crappy way of doing this.
9208 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9209 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9210 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9211 if ([tabbar_ updating])
9212 [tabbar_ cancelUpdate];
9214 if (![database_ prepare])
9217 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9218 [page setDelegate:self];
9219 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9222 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9223 [tabbar_ presentModalViewController:confirm_ animated:YES];
9229 @synchronized (self) {
9234 - (void) clearPackage:(Package *)package {
9235 @synchronized (self) {
9242 - (void) installPackages:(NSArray *)packages {
9243 @synchronized (self) {
9244 for (Package *package in packages)
9251 - (void) installPackage:(Package *)package {
9252 @synchronized (self) {
9259 - (void) removePackage:(Package *)package {
9260 @synchronized (self) {
9267 - (void) distUpgrade {
9268 @synchronized (self) {
9269 if (![database_ upgrade])
9276 [database_ perform];
9277 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9280 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9283 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9285 [self refreshIfPossible];
9288 - (void) showSettings {
9289 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9292 - (void) retainNetworkActivityIndicator {
9293 if (activity_++ == 0)
9294 [self setNetworkActivityIndicatorVisible:YES];
9297 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9301 - (void) releaseNetworkActivityIndicator {
9302 if (--activity_ == 0)
9303 [self setNetworkActivityIndicatorVisible:NO];
9306 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9311 - (void) cancelAndClear:(bool)clear {
9312 @synchronized (self) {
9324 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9325 NSString *context([alert context]);
9327 if ([context isEqualToString:@"conffile"]) {
9328 FILE *input = [database_ input];
9329 if (button == [alert cancelButtonIndex])
9330 fprintf(input, "N\n");
9331 else if (button == [alert firstOtherButtonIndex])
9332 fprintf(input, "Y\n");
9335 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9336 } else if ([context isEqualToString:@"fixhalf"]) {
9337 if (button == [alert cancelButtonIndex]) {
9338 @synchronized (self) {
9339 for (Package *broken in (id) broken_) {
9342 NSString *id = [broken id];
9343 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9344 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9345 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9346 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9352 } else if (button == [alert firstOtherButtonIndex]) {
9353 [broken_ removeAllObjects];
9357 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9358 } else if ([context isEqualToString:@"upgrade"]) {
9359 if (button == [alert firstOtherButtonIndex]) {
9360 @synchronized (self) {
9361 for (Package *essential in (id) essential_)
9362 [essential install];
9367 } else if (button == [alert firstOtherButtonIndex] + 1) {
9369 } else if (button == [alert cancelButtonIndex]) {
9373 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9377 - (void) system:(NSString *)command {
9378 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9381 system([command UTF8String]);
9387 - (void) applicationWillSuspend {
9389 [super applicationWillSuspend];
9392 - (BOOL) isSafeToSuspend {
9395 NSLog(@"isSafeToSuspend: locked_ != 0");
9400 // Use external process status API internally.
9401 // This is probably a really bad idea.
9402 // XXX: what is the point of this? does this solve anything at all?
9403 uint64_t status = 0;
9405 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9406 notify_get_state(notify_token, &status);
9407 notify_cancel(notify_token);
9412 NSLog(@"isSafeToSuspend: status != 0");
9418 NSLog(@"isSafeToSuspend: -> true");
9423 - (void) applicationSuspend:(__GSEvent *)event {
9424 if ([self isSafeToSuspend])
9425 [super applicationSuspend:event];
9428 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9429 if ([self isSafeToSuspend])
9430 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9433 - (void) _setSuspended:(BOOL)value {
9434 if ([self isSafeToSuspend])
9435 [super _setSuspended:value];
9438 - (UIProgressHUD *) addProgressHUD {
9439 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9440 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9442 [window_ setUserInteractionEnabled:NO];
9444 UIViewController *target(tabbar_);
9445 if (UIViewController *modal = [target modalViewController])
9448 UIView *view([target view]);
9449 [view addSubview:hud];
9451 [hud showInView:[tabbar_ view]];
9457 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9460 [hud removeFromSuperview];
9461 [window_ setUserInteractionEnabled:YES];
9464 - (CyteViewController *) pageForPackage:(NSString *)name {
9465 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9468 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9469 NSString *scheme([[url scheme] lowercaseString]);
9470 if ([[url absoluteString] length] <= [scheme length] + 3)
9472 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9473 NSArray *components([path pathComponents]);
9475 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9476 return [self pageForPackage:[components objectAtIndex:1]];
9478 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9481 NSString *base([components objectAtIndex:0]);
9483 CyteViewController *controller = nil;
9485 if ([base isEqualToString:@"url"]) {
9486 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9487 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9488 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9489 } else if (!external && [components count] == 1) {
9490 if ([base isEqualToString:@"manage"]) {
9491 controller = [[[ManageController alloc] init] autorelease];
9494 if ([base isEqualToString:@"sources"]) {
9495 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9498 if ([base isEqualToString:@"home"]) {
9499 controller = [[[HomeController alloc] init] autorelease];
9502 if ([base isEqualToString:@"sections"]) {
9503 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9506 if ([base isEqualToString:@"search"]) {
9507 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9510 if ([base isEqualToString:@"changes"]) {
9511 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9514 if ([base isEqualToString:@"installed"]) {
9515 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9517 } else if ([components count] == 2) {
9518 NSString *argument = [components objectAtIndex:1];
9520 if ([base isEqualToString:@"package"]) {
9521 controller = [self pageForPackage:argument];
9524 if (!external && [base isEqualToString:@"search"]) {
9525 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9528 if (!external && [base isEqualToString:@"sections"]) {
9529 if ([argument isEqualToString:@"all"])
9531 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9534 if (!external && [base isEqualToString:@"sources"]) {
9535 if ([argument isEqualToString:@"add"]) {
9536 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9537 [(SourcesController *)controller showAddSourcePrompt];
9539 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9540 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9544 if (!external && [base isEqualToString:@"launch"]) {
9545 [self launchApplicationWithIdentifier:argument suspended:NO];
9548 } else if (!external && [components count] == 3) {
9549 NSString *arg1 = [components objectAtIndex:1];
9550 NSString *arg2 = [components objectAtIndex:2];
9552 if ([base isEqualToString:@"package"]) {
9553 if ([arg2 isEqualToString:@"settings"]) {
9554 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9555 } else if ([arg2 isEqualToString:@"files"]) {
9556 if (Package *package = [database_ packageWithName:arg1]) {
9557 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9558 [(FileTable *)controller setPackage:package];
9564 [controller setDelegate:self];
9568 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9569 CyteViewController *page([self pageForURL:url forExternal:external]);
9572 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9573 [nav setViewControllers:[NSArray arrayWithObject:page]];
9574 [tabbar_ setUnselectedViewController:nav];
9580 - (void) applicationOpenURL:(NSURL *)url {
9581 [super applicationOpenURL:url];
9586 [self openCydiaURL:url forExternal:YES];
9589 - (void) applicationWillResignActive:(UIApplication *)application {
9590 // Stop refreshing if you get a phone call or lock the device.
9591 if ([tabbar_ updating])
9592 [tabbar_ cancelUpdate];
9594 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9595 [super applicationWillResignActive:application];
9598 - (void) saveState {
9599 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9600 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9601 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9607 - (void) applicationWillTerminate:(UIApplication *)application {
9611 - (void) setConfigurationData:(NSString *)data {
9612 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9614 if (!conffile_r(data)) {
9615 lprintf("E:invalid conffile\n");
9619 NSString *ofile = conffile_r[1];
9620 //NSString *nfile = conffile_r[2];
9622 UIAlertView *alert = [[[UIAlertView alloc]
9623 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9624 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9626 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9628 UCLocalize("ACCEPT_NEW_COPY"),
9629 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9633 [alert setContext:@"conffile"];
9634 [alert setNumberOfRows:2];
9638 - (void) addStashController {
9640 stash_ = [[[StashController alloc] init] autorelease];
9641 [window_ addSubview:[stash_ view]];
9644 - (void) removeStashController {
9645 [[stash_ view] removeFromSuperview];
9651 [self setIdleTimerDisabled:YES];
9653 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9654 UpdateExternalStatus(1);
9655 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9656 UpdateExternalStatus(0);
9658 [self removeStashController];
9660 if (ExecFork() == 0) {
9661 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9662 perror("launchctl stop");
9666 - (void) setupViewControllers {
9667 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9669 NSMutableArray *items([NSMutableArray arrayWithObjects:
9670 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9671 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9672 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9673 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9677 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9678 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9680 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9683 NSMutableArray *controllers([NSMutableArray array]);
9684 for (UITabBarItem *item in items) {
9685 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9686 [controller setTabBarItem:item];
9687 [controllers addObject:controller];
9689 [tabbar_ setViewControllers:controllers];
9691 [tabbar_ setUpdateDelegate:self];
9694 - (void) _sendMemoryWarningNotification {
9695 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9698 - (void) _sendMemoryWarningNotifications {
9700 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9705 - (void) applicationDidFinishLaunching:(id)unused {
9706 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9709 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9710 [self setApplicationSupportsShakeToEdit:NO];
9712 @synchronized (HostConfig_) {
9713 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9716 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9717 initWithMemoryCapacity:524288
9718 diskCapacity:10485760
9719 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9722 [CydiaWebViewController _initialize];
9724 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9726 // this would disallow http{,s} URLs from accessing this data
9727 //[WebView registerURLSchemeAsLocal:@"cydia"];
9729 Font12_ = [UIFont systemFontOfSize:12];
9730 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9731 Font14_ = [UIFont systemFontOfSize:14];
9732 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9733 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9735 essential_ = [NSMutableArray arrayWithCapacity:4];
9736 broken_ = [NSMutableArray arrayWithCapacity:4];
9738 // XXX: I really need this thing... like, seriously... I'm sorry
9739 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9741 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9742 [window_ orderFront:self];
9743 [window_ makeKey:self];
9744 [window_ setHidden:NO];
9747 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9748 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9749 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9750 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9751 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9752 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9753 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9754 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9755 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9758 [self addStashController];
9759 // XXX: this would be much cleaner as a yieldToSelector:
9760 // that way the removeStashController could happen right here inline
9761 // we also could no longer require the useless stash_ field anymore
9762 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9766 database_ = [Database sharedInstance];
9767 [database_ setDelegate:self];
9769 [window_ setUserInteractionEnabled:NO];
9770 [self setupViewControllers];
9772 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9773 [window_ addSubview:[emulated_ view]];
9775 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9779 - (NSArray *) defaultStartPages {
9780 NSMutableArray *standard = [NSMutableArray array];
9781 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9782 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9783 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9785 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9787 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9788 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9790 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9797 [window_ setUserInteractionEnabled:YES];
9798 [self showSettings];
9801 if ([emulated_ modalViewController] != nil)
9802 [emulated_ dismissModalViewControllerAnimated:YES];
9803 [window_ setUserInteractionEnabled:NO];
9806 [self reloadDataWithInvocation:nil];
9807 [self refreshIfPossible];
9812 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9813 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9814 int standardIndex = 0;
9815 NSArray *standard = [self defaultStartPages];
9822 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9823 if (valid && closed != nil) {
9824 NSTimeInterval interval([closed timeIntervalSinceNow]);
9825 // XXX: Is 15 minutes the optimal time here?
9826 if (interval > 0 && interval <= -(15*60))
9830 if (valid && [saved count] != [standard count])
9834 for (unsigned int i = 0; i < [standard count]; i++) {
9835 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9836 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9837 // but it's good enough for now.
9838 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9845 NSArray *items = nil;
9847 [tabbar_ setSelectedIndex:savedIndex];
9850 [tabbar_ setSelectedIndex:standardIndex];
9854 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9855 NSArray *stack = [items objectAtIndex:tab];
9856 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9857 NSMutableArray *current = [NSMutableArray array];
9859 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9860 NSString *addr = [stack objectAtIndex:nav];
9861 NSURL *url = [NSURL URLWithString:addr];
9862 CyteViewController *page = [self pageForURL:url forExternal:NO];
9864 [current addObject:page];
9867 [navigation setViewControllers:current];
9870 // (Try to) show the startup URL.
9871 if (starturl_ != nil) {
9872 [self openCydiaURL:starturl_ forExternal:NO];
9877 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9878 if (item != nil && IsWildcat_) {
9879 [sheet showFromBarButtonItem:item animated:YES];
9881 [sheet showInView:window_];
9885 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9886 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9887 [progress setTitle:task];
9888 [progress addProgressEvent:event];
9891 - (void) addProgressEventForTask:(NSArray *)data {
9892 CydiaProgressEvent *event([data objectAtIndex:0]);
9893 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9894 [self addProgressEvent:event forTask:task];
9897 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9898 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9904 id Alloc_(id self, SEL selector) {
9905 id object = alloc_(self, selector);
9906 lprintf("[%s]A-%p\n", self->isa->name, object);
9911 id Dealloc_(id self, SEL selector) {
9912 id object = dealloc_(self, selector);
9913 lprintf("[%s]D-%p\n", self->isa->name, object);
9917 Class $WebDefaultUIKitDelegate;
9919 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9920 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9921 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9922 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9925 static NSSet *MobilizedFiles_;
9927 static NSURL *MobilizeURL(NSURL *url) {
9928 NSString *path([url path]);
9929 if ([path hasPrefix:@"/var/root/"]) {
9930 NSString *file([path substringFromIndex:10]);
9931 if ([MobilizedFiles_ containsObject:file])
9932 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9938 Class $CFXPreferencesPropertyListSource;
9939 @class CFXPreferencesPropertyListSource;
9941 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9942 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9943 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9944 url = MobilizeURL(url);
9945 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9946 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9952 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9953 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9954 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9955 url = MobilizeURL(url);
9956 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9957 //NSLog(@"%@ %@", [url absoluteString], value);
9963 Class $NSURLConnection;
9965 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9966 NSMutableURLRequest *copy([request mutableCopy]);
9968 NSURL *url([copy URL]);
9970 NSString *href([url absoluteString]);
9971 NSString *host([url host]);
9972 NSString *scheme([[url scheme] lowercaseString]);
9974 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9976 @synchronized (HostConfig_) {
9977 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9978 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9979 [copy setHTTPShouldUsePipelining:YES];
9981 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9982 if ([control isEqualToString:@"max-age=0"])
9983 if ([CachedURLs_ containsObject:href]) {
9985 NSLog(@"~~~: %@", href);
9988 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9990 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9991 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9992 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9996 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10000 int main(int argc, char *argv[]) {
10001 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10005 UpdateExternalStatus(0);
10007 if (Class $UIDevice = objc_getClass("UIDevice")) {
10008 UIDevice *device([$UIDevice currentDevice]);
10009 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10011 IsWildcat_ = false;
10013 UIScreen *screen([UIScreen mainScreen]);
10014 if ([screen respondsToSelector:@selector(scale)])
10015 ScreenScale_ = [screen scale];
10019 UIDevice *device([UIDevice currentDevice]);
10020 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10021 Idiom_ = @"iphone";
10023 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10024 if (idiom == UIUserInterfaceIdiomPhone)
10025 Idiom_ = @"iphone";
10026 else if (idiom == UIUserInterfaceIdiomPad)
10029 NSLog(@"unknown UIUserInterfaceIdiom!");
10032 Pcre pattern("^([0-9]+\\.[0-9]+)");
10033 if (pattern([device systemVersion]))
10034 Firmware_ = pattern[1];
10036 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10038 HostConfig_ = [[[NSObject alloc] init] autorelease];
10039 @synchronized (HostConfig_) {
10040 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10041 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10042 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10043 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10044 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10047 NSString *ui(@"ui/ios");
10048 if (Firmware_ != nil)
10049 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"-%@", Firmware_]];
10051 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10052 UI_ = CydiaURL(ui);
10054 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10056 MobilizedFiles_ = [NSMutableSet setWithObjects:
10057 @"Library/Preferences/com.apple.Accessibility.plist",
10058 @"Library/Preferences/com.apple.preferences.sounds.plist",
10061 /* Library Hacks {{{ */
10062 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10064 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10066 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10067 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10068 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10069 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10072 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10073 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10074 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10075 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10078 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10079 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10080 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10081 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10082 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10085 $NSURLConnection = objc_getClass("NSURLConnection");
10086 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10087 if (NSURLConnection$init$ != NULL) {
10088 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10089 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10092 /* Set Locale {{{ */
10093 Locale_ = CFLocaleCopyCurrent();
10094 Languages_ = [NSLocale preferredLanguages];
10096 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10097 //NSLog(@"%@", [Languages_ description]);
10100 if (Locale_ != NULL)
10101 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10102 else if (Languages_ != nil && [Languages_ count] != 0)
10103 lang = [[Languages_ objectAtIndex:0] UTF8String];
10105 // XXX: consider just setting to C and then falling through?
10108 if (lang != NULL) {
10109 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10110 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10113 NSLog(@"Setting Language: %s", lang);
10115 if (lang != NULL) {
10116 setenv("LANG", lang, true);
10117 std::setlocale(LC_ALL, lang);
10121 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10123 /* Parse Arguments {{{ */
10124 bool substrate(false);
10130 for (int argi(1); argi != argc; ++argi)
10131 if (strcmp(argv[argi], "--") == 0) {
10133 argv[argi] = argv[0];
10139 for (int argi(1); argi != arge; ++argi)
10140 if (strcmp(args[argi], "--substrate") == 0)
10143 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10147 App_ = [[NSBundle mainBundle] bundlePath];
10153 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10154 alloc_ = alloc->method_imp;
10155 alloc->method_imp = (IMP) &Alloc_;*/
10157 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10158 dealloc_ = dealloc->method_imp;
10159 dealloc->method_imp = (IMP) &Dealloc_;*/
10161 /* System Information {{{ */
10165 size = sizeof(maxproc);
10166 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10167 perror("sysctlbyname(\"kern.maxproc\", ?)");
10168 else if (maxproc < 64) {
10170 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10171 perror("sysctlbyname(\"kern.maxproc\", #)");
10174 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10175 char *osversion = new char[size];
10176 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10177 perror("sysctlbyname(\"kern.osversion\", ?)");
10179 System_ = [NSString stringWithUTF8String:osversion];
10181 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10182 char *machine = new char[size];
10183 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10184 perror("sysctlbyname(\"hw.machine\", ?)");
10186 Machine_ = machine;
10188 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10189 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10190 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10192 UniqueID_ = [device uniqueIdentifier];
10194 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10195 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10196 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10198 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10199 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10200 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10202 if (mcc != NULL && mnc != NULL)
10203 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10210 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10211 Build_ = [system objectForKey:@"ProductBuildVersion"];
10212 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10213 Product_ = [info objectForKey:@"SafariProductVersion"];
10214 Safari_ = [info objectForKey:@"CFBundleVersion"];
10217 /* Load Database {{{ */
10219 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10221 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10223 if (Metadata_ == NULL)
10224 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10226 Settings_ = [Metadata_ objectForKey:@"Settings"];
10228 Packages_ = [Metadata_ objectForKey:@"Packages"];
10230 Values_ = [Metadata_ objectForKey:@"Values"];
10231 Sections_ = [Metadata_ objectForKey:@"Sections"];
10232 Sources_ = [Metadata_ objectForKey:@"Sources"];
10234 Token_ = [Metadata_ objectForKey:@"Token"];
10236 Version_ = [Metadata_ objectForKey:@"Version"];
10238 @synchronized (HostConfig_) {
10239 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10243 if (Settings_ != nil)
10244 Role_ = [Settings_ objectForKey:@"Role"];
10246 if (Values_ == nil) {
10247 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10248 [Metadata_ setObject:Values_ forKey:@"Values"];
10251 if (Sections_ == nil) {
10252 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10253 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10256 if (Sources_ == nil) {
10257 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10258 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10261 if (Version_ == nil) {
10262 Version_ = [NSNumber numberWithUnsignedInt:0];
10263 [Metadata_ setObject:Version_ forKey:@"Version"];
10266 @synchronized (HostConfig_) {
10267 if (CydiaSource_ == nil) {
10268 CydiaSource_ = @"apt.saurik.com";
10269 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10273 if ([Version_ unsignedIntValue] == 0) {
10274 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10275 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10276 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10277 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10279 Version_ = [NSNumber numberWithUnsignedInt:1];
10280 [Metadata_ setObject:Version_ forKey:@"Version"];
10282 [Metadata_ removeObjectForKey:@"LastUpdate"];
10291 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10294 if (Packages_ != nil) {
10296 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10300 [Metadata_ removeObjectForKey:@"Packages"];
10306 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10308 #define MobileSubstrate_(name) \
10309 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10310 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10311 if (handle == NULL) \
10312 NSLog(@"%s", dlerror()); \
10315 MobileSubstrate_(Activator)
10316 MobileSubstrate_(libstatusbar)
10317 MobileSubstrate_(SimulatedKeyEvents)
10318 MobileSubstrate_(WinterBoard)
10320 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10321 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10323 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10325 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10326 unlink("/tmp/.cydia.fw");
10328 } else if (access("/User", F_OK) != 0 || version < 4) {
10331 system("/usr/libexec/cydia/firmware.sh");
10335 _assert([[NSFileManager defaultManager]
10336 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10337 withIntermediateDirectories:YES
10342 if (access("/tmp/cydia.chk", F_OK) == 0) {
10343 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10344 _assert(errno == ENOENT);
10345 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10346 _assert(errno == ENOENT);
10349 /* APT Initialization {{{ */
10350 _assert(pkgInitConfig(*_config));
10351 _assert(pkgInitSystem(*_config, _system));
10354 _config->Set("APT::Acquire::Translation", lang);
10356 // XXX: this timeout might be important :(
10357 //_config->Set("Acquire::http::Timeout", 15);
10359 _config->Set("Acquire::http::MaxParallel", 3);
10361 /* Color Choices {{{ */
10362 space_ = CGColorSpaceCreateDeviceRGB();
10364 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10365 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10366 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10367 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10368 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10369 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10370 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10371 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10372 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10374 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10375 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10377 /* UIKit Configuration {{{ */
10378 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10379 if ($GSFontSetUseLegacyFontMetrics != NULL)
10380 $GSFontSetUseLegacyFontMetrics(YES);
10382 // XXX: I have a feeling this was important
10383 //UIKeyboardDisableAutomaticAppearance();
10386 Colon_ = UCLocalize("COLON_DELIMITED");
10387 Elision_ = UCLocalize("ELISION");
10388 Error_ = UCLocalize("ERROR");
10389 Warning_ = UCLocalize("WARNING");
10392 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10394 CGColorSpaceRelease(space_);
10395 CFRelease(Locale_);