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() {
277 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
278 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? 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_;
718 static NSString *Major_;
720 static _H<NSMutableDictionary> SessionData_;
721 static _H<NSObject> HostConfig_;
722 static _H<NSMutableSet> BridgedHosts_;
723 static _H<NSMutableSet> TokenHosts_;
724 static _H<NSMutableSet> InsecureHosts_;
725 static _H<NSMutableSet> PipelinedHosts_;
726 static _H<NSMutableSet> CachedURLs_;
728 static NSString *kCydiaProgressEventTypeError = @"Error";
729 static NSString *kCydiaProgressEventTypeInformation = @"Information";
730 static NSString *kCydiaProgressEventTypeStatus = @"Status";
731 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
734 static void AddSource(NSDictionary *source) {
735 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
739 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
740 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
743 distribution, @"Distribution",
744 sections ?: [NSMutableArray array], @"Sections",
748 static void WriteSources() {
749 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
750 _assert(file != NULL);
752 NSString *distribution(@"ios");
753 if (Firmware_ != nil)
754 distribution = [distribution stringByAppendingString:[NSString stringWithFormat:@"-%@", Firmware_]];
756 fprintf(file, "deb http://%s/ %s main\n",
757 [CydiaSource_ UTF8String],
758 [distribution UTF8String]
761 for (NSString *key in [Sources_ allKeys]) {
762 NSDictionary *source([Sources_ objectForKey:key]);
764 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
766 fprintf(file, "%s %s %s%s%s\n",
767 [[source objectForKey:@"Type"] UTF8String],
768 [[source objectForKey:@"URI"] UTF8String],
769 [[source objectForKey:@"Distribution"] UTF8String],
770 [sections count] == 0 ? "" : " ",
771 [[sections componentsJoinedByString:@" "] UTF8String]
778 /* Display Helpers {{{ */
779 inline float Interpolate(float begin, float end, float fraction) {
780 return (end - begin) * fraction + begin;
783 static _finline const char *StripVersion_(const char *version) {
784 const char *colon(strchr(version, ':'));
785 return colon == NULL ? version : colon + 1;
788 NSString *LocalizeSection(NSString *section) {
789 static Pcre title_r("^(.*?) \\((.*)\\)$");
790 if (title_r(section)) {
791 NSString *parent(title_r[1]);
792 NSString *child(title_r[2]);
794 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
795 LocalizeSection(parent),
796 LocalizeSection(child)
800 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
803 NSString *Simplify(NSString *title) {
804 const char *data = [title UTF8String];
805 size_t size = [title length];
807 static Pcre square_r("^\\[(.*)\\]$");
808 if (square_r(data, size))
809 return Simplify(square_r[1]);
811 static Pcre paren_r("^\\((.*)\\)$");
812 if (paren_r(data, size))
813 return Simplify(paren_r[1]);
815 static Pcre title_r("^(.*?) \\((.*)\\)$");
816 if (title_r(data, size))
817 return Simplify(title_r[1]);
823 NSString *GetLastUpdate() {
824 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
827 return UCLocalize("NEVER_OR_UNKNOWN");
829 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
830 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
832 CFRelease(formatter);
834 return [(NSString *) formatted autorelease];
837 bool isSectionVisible(NSString *section) {
838 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
839 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
840 return hidden == nil || ![hidden boolValue];
843 static NSObject *CYIOGetValue(const char *path, NSString *property) {
844 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
845 if (entry == MACH_PORT_NULL)
848 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
849 IOObjectRelease(entry);
853 return [(id) value autorelease];
856 static NSString *CYHex(NSData *data, bool reverse = false) {
860 size_t length([data length]);
861 uint8_t bytes[length];
862 [data getBytes:bytes];
864 char string[length * 2 + 1];
865 for (size_t i(0); i != length; ++i)
866 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
868 return [NSString stringWithUTF8String:string];
873 /* Delegate Prototypes {{{ */
876 @class CydiaProgressEvent;
878 @protocol DatabaseDelegate
879 - (void) repairWithSelector:(SEL)selector;
880 - (void) setConfigurationData:(NSString *)data;
881 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
884 @class CYPackageController;
886 @protocol CydiaDelegate
887 - (void) returnToCydia;
889 - (void) retainNetworkActivityIndicator;
890 - (void) releaseNetworkActivityIndicator;
891 - (void) clearPackage:(Package *)package;
892 - (void) installPackage:(Package *)package;
893 - (void) installPackages:(NSArray *)packages;
894 - (void) removePackage:(Package *)package;
895 - (void) beginUpdate;
897 - (void) distUpgrade;
901 - (void) addSource:(NSDictionary *)source;
902 - (void) addTrivialSource:(NSString *)href;
903 - (void) showSettings;
904 - (UIProgressHUD *) addProgressHUD;
905 - (void) removeProgressHUD:(UIProgressHUD *)hud;
906 - (CyteViewController *) pageForPackage:(NSString *)name;
907 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
908 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
912 /* Status Delegation {{{ */
914 public pkgAcquireStatus
917 _transient NSObject<ProgressDelegate> *delegate_;
927 void setDelegate(NSObject<ProgressDelegate> *delegate) {
928 delegate_ = delegate;
931 NSObject<ProgressDelegate> *getDelegate() const {
935 virtual bool MediaChange(std::string media, std::string drive) {
939 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
943 virtual void Fetch(pkgAcquire::ItemDesc &item) {
944 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
945 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
946 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
949 virtual void Done(pkgAcquire::ItemDesc &item) {
950 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
951 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
952 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
955 virtual void Fail(pkgAcquire::ItemDesc &item) {
957 item.Owner->Status == pkgAcquire::Item::StatIdle ||
958 item.Owner->Status == pkgAcquire::Item::StatDone
962 std::string &error(item.Owner->ErrorText);
966 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
967 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
970 virtual bool Pulse(pkgAcquire *Owner) {
971 bool value = pkgAcquireStatus::Pulse(Owner);
974 double(CurrentBytes + CurrentItems) /
975 double(TotalBytes + TotalItems)
978 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
979 [NSNumber numberWithDouble:percent], @"Percent",
981 [NSNumber numberWithDouble:CurrentBytes], @"Current",
982 [NSNumber numberWithDouble:TotalBytes], @"Total",
983 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
984 nil] waitUntilDone:YES];
986 if (value && ![delegate_ isProgressCancelled])
994 _finline bool WasCancelled() const {
998 virtual void Start() {
999 pkgAcquireStatus::Start();
1000 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1003 virtual void Stop() {
1004 pkgAcquireStatus::Stop();
1005 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1006 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1010 /* Database Interface {{{ */
1011 typedef std::map< unsigned long, _H<Source> > SourceMap;
1013 @interface Database : NSObject {
1019 pkgCacheFile cache_;
1020 pkgDepCache::Policy *policy_;
1021 pkgRecords *records_;
1022 pkgProblemResolver *resolver_;
1023 pkgAcquire *fetcher_;
1025 SPtr<pkgPackageManager> manager_;
1026 pkgSourceList *list_;
1028 SourceMap sourceMap_;
1029 _H<NSMutableArray> sourceList_;
1031 CFMutableArrayRef packages_;
1033 _transient NSObject<DatabaseDelegate> *delegate_;
1034 _transient NSObject<ProgressDelegate> *progress_;
1042 std::map<const char *, _H<NSString> > sections_;
1045 + (Database *) sharedInstance;
1048 - (void) _readCydia:(NSNumber *)fd;
1049 - (void) _readStatus:(NSNumber *)fd;
1050 - (void) _readOutput:(NSNumber *)fd;
1054 - (Package *) packageWithName:(NSString *)name;
1056 - (pkgCacheFile &) cache;
1057 - (pkgDepCache::Policy *) policy;
1058 - (pkgRecords *) records;
1059 - (pkgProblemResolver *) resolver;
1060 - (pkgAcquire &) fetcher;
1061 - (pkgSourceList &) list;
1062 - (NSArray *) packages;
1063 - (NSArray *) sources;
1064 - (Source *) sourceWithKey:(NSString *)key;
1065 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1073 - (void) updateWithStatus:(Status &)status;
1075 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1077 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1078 - (NSObject<ProgressDelegate> *) progressDelegate;
1080 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1082 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1086 /* ProgressEvent Implementation {{{ */
1087 @implementation CydiaProgressEvent
1089 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1090 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1093 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1094 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1095 [event setPackage:package];
1099 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1100 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1102 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1103 NSArray *fields([description componentsSeparatedByString:@" "]);
1104 [event setItem:fields];
1106 if ([fields count] > 3) {
1107 [event setPackage:[fields objectAtIndex:2]];
1108 [event setVersion:[fields objectAtIndex:3]];
1111 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1116 + (NSArray *) _attributeKeys {
1117 return [NSArray arrayWithObjects:
1127 - (NSArray *) attributeKeys {
1128 return [[self class] _attributeKeys];
1131 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1132 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1135 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1136 if ((self = [super init]) != nil) {
1142 - (NSString *) message {
1146 - (NSString *) type {
1150 - (NSArray *) item {
1151 return (id) item_ ?: [NSNull null];
1154 - (void) setItem:(NSArray *)item {
1158 - (NSString *) package {
1159 return (id) package_ ?: [NSNull null];
1162 - (void) setPackage:(NSString *)package {
1166 - (NSString *) url {
1167 return (id) url_ ?: [NSNull null];
1170 - (void) setURL:(NSString *)url {
1174 - (void) setVersion:(NSString *)version {
1178 - (NSString *) version {
1179 return (id) version_ ?: [NSNull null];
1182 - (NSString *) compound:(NSString *)value {
1184 NSString *mode(nil); {
1185 NSString *type([self type]);
1186 if ([type isEqualToString:kCydiaProgressEventTypeError])
1187 mode = UCLocalize("ERROR");
1188 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1189 mode = UCLocalize("WARNING");
1193 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1199 - (NSString *) compoundMessage {
1200 return [self compound:[self message]];
1203 - (NSString *) compoundTitle {
1206 if (package_ == nil)
1208 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1209 title = [package name];
1213 return [self compound:title];
1219 // Cytore Definitions {{{
1220 struct PackageValue :
1223 Cytore::Offset<PackageValue> next_;
1225 uint32_t index_ : 23;
1226 uint32_t subscribed_ : 1;
1243 Cytore::Offset<PackageValue> packages_[1 << 16];
1246 static Cytore::File<MetaValue> MetaFile_;
1248 // Cytore Helper Functions {{{
1249 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1250 SplitHash nhash = { hashlittle(name, length) };
1252 PackageValue *metadata;
1254 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1255 offset: if (offset->IsNull()) {
1256 *offset = MetaFile_.New<PackageValue>(length + 1);
1257 metadata = &MetaFile_.Get(*offset);
1259 if (metadata == NULL) {
1263 metadata = new PackageValue();
1264 memset(metadata, 0, sizeof(*metadata));
1267 memcpy(metadata->name_, name, length + 1);
1268 metadata->nhash_ = nhash.u16[1];
1270 metadata = &MetaFile_.Get(*offset);
1272 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1273 offset = &metadata->next_;
1281 static void PackageImport(const void *key, const void *value, void *context) {
1282 bool &fail(*reinterpret_cast<bool *>(context));
1285 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1286 NSLog(@"failed to import package %@", key);
1290 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1291 NSDictionary *package((NSDictionary *) value);
1293 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1294 if ([subscribed boolValue] && !metadata->subscribed_)
1295 metadata->subscribed_ = true;
1297 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1298 time_t time([date timeIntervalSince1970]);
1299 if (metadata->first_ > time || metadata->first_ == 0)
1300 metadata->first_ = time;
1303 NSDate *date([package objectForKey:@"LastSeen"]);
1304 NSString *version([package objectForKey:@"LastVersion"]);
1306 if (date != nil && version != nil) {
1307 time_t time([date timeIntervalSince1970]);
1308 if (metadata->last_ < time || metadata->last_ == 0)
1309 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1310 size_t length(strlen(buffer));
1311 uint16_t vhash(hashlittle(buffer, length));
1313 size_t capped(std::min<size_t>(8, length));
1314 char *latest(buffer + length - capped);
1316 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1317 metadata->vhash_ = vhash;
1319 metadata->last_ = time;
1325 /* Source Class {{{ */
1326 @interface Source : NSObject {
1328 Database *database_;
1331 CYString depiction_;
1332 CYString description_;
1338 CYString distribution_;
1344 _H<NSString> authority_;
1346 CYString defaultIcon_;
1348 _H<NSDictionary> record_;
1352 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1354 - (NSComparisonResult) compareByName:(Source *)source;
1356 - (NSString *) depictionForPackage:(NSString *)package;
1357 - (NSString *) supportForPackage:(NSString *)package;
1359 - (NSDictionary *) record;
1363 - (NSString *) distribution;
1364 - (NSString *) type;
1366 - (NSString *) base;
1369 - (NSString *) host;
1371 - (NSString *) name;
1372 - (NSString *) shortDescription;
1373 - (NSString *) label;
1374 - (NSString *) origin;
1375 - (NSString *) version;
1377 - (NSString *) defaultIcon;
1381 @implementation Source
1385 distribution_.clear();
1390 description_.clear();
1396 defaultIcon_.clear();
1403 + (NSString *) webScriptNameForSelector:(SEL)selector {
1405 else if (selector == @selector(addSection:))
1406 return @"addSection";
1407 else if (selector == @selector(getField:))
1409 else if (selector == @selector(removeSection:))
1410 return @"removeSection";
1411 else if (selector == @selector(remove))
1417 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1418 return [self webScriptNameForSelector:selector] == nil;
1421 + (NSArray *) _attributeKeys {
1422 return [NSArray arrayWithObjects:
1430 @"shortDescription",
1438 - (NSArray *) attributeKeys {
1439 return [[self class] _attributeKeys];
1442 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1443 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1446 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1449 trusted_ = index->IsTrusted();
1451 uri_.set(pool, index->GetURI());
1452 distribution_.set(pool, index->GetDist());
1453 type_.set(pool, index->GetType());
1455 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1456 if (dindex != NULL) {
1457 base_.set(pool, dindex->MetaIndexURI(""));
1460 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1463 pkgTagFile tags(&fd);
1465 pkgTagSection section;
1472 {"default-icon", &defaultIcon_},
1473 {"depiction", &depiction_},
1474 {"description", &description_},
1476 {"origin", &origin_},
1477 {"support", &support_},
1478 {"version", &version_},
1481 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1482 const char *start, *end;
1484 if (section.Find(names[i].name_, start, end)) {
1485 CYString &value(*names[i].value_);
1486 value.set(pool, start, end - start);
1492 record_ = [Sources_ objectForKey:[self key]];
1494 NSURL *url([NSURL URLWithString:uri_]);
1498 host_ = [host_ lowercaseString];
1503 authority_ = [url path];
1506 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1507 if ((self = [super init]) != nil) {
1508 era_ = [database era];
1509 database_ = database;
1512 [self setMetaIndex:index inPool:pool];
1516 - (NSString *) getField:(NSString *)name {
1517 @synchronized (database_) {
1518 if ([database_ era] != era_ || index_ == NULL)
1521 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1526 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1531 pkgTagFile tags(&fd);
1533 pkgTagSection section;
1536 const char *start, *end;
1537 if (!section.Find([name UTF8String], start, end))
1538 return (NSString *) [NSNull null];
1540 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1543 - (NSComparisonResult) compareByName:(Source *)source {
1544 NSString *lhs = [self name];
1545 NSString *rhs = [source name];
1547 if ([lhs length] != 0 && [rhs length] != 0) {
1548 unichar lhc = [lhs characterAtIndex:0];
1549 unichar rhc = [rhs characterAtIndex:0];
1551 if (isalpha(lhc) && !isalpha(rhc))
1552 return NSOrderedAscending;
1553 else if (!isalpha(lhc) && isalpha(rhc))
1554 return NSOrderedDescending;
1557 return [lhs compare:rhs options:LaxCompareOptions_];
1560 - (NSString *) depictionForPackage:(NSString *)package {
1561 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1564 - (NSString *) supportForPackage:(NSString *)package {
1565 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1568 - (NSArray *) sections {
1569 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1572 - (void) _addSection:(NSString *)section {
1575 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1576 if (![sections containsObject:section]) {
1577 [sections addObject:section];
1581 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1586 - (bool) addSection:(NSString *)section {
1590 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1594 - (void) _removeSection:(NSString *)section {
1598 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1599 if ([sections containsObject:section]) {
1600 [sections removeObject:section];
1605 - (bool) removeSection:(NSString *)section {
1609 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1614 [Sources_ removeObjectForKey:[self key]];
1619 bool value(record_ != nil);
1620 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1624 - (NSDictionary *) record {
1632 - (NSString *) uri {
1636 - (NSString *) distribution {
1637 return distribution_;
1640 - (NSString *) type {
1644 - (NSString *) base {
1648 - (NSString *) key {
1649 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1652 - (NSString *) host {
1656 - (NSString *) name {
1657 return origin_.empty() ? (id) authority_ : origin_;
1660 - (NSString *) shortDescription {
1661 return description_;
1664 - (NSString *) label {
1665 return label_.empty() ? (id) authority_ : label_;
1668 - (NSString *) origin {
1672 - (NSString *) version {
1676 - (NSString *) defaultIcon {
1677 return defaultIcon_;
1682 /* CydiaOperation Class {{{ */
1683 @interface CydiaOperation : NSObject {
1684 _H<NSString> operator_;
1685 _H<NSString> value_;
1688 - (NSString *) operator;
1689 - (NSString *) value;
1693 @implementation CydiaOperation
1695 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1696 if ((self = [super init]) != nil) {
1697 operator_ = [NSString stringWithUTF8String:_operator];
1698 value_ = [NSString stringWithUTF8String:value];
1702 + (NSArray *) _attributeKeys {
1703 return [NSArray arrayWithObjects:
1709 - (NSArray *) attributeKeys {
1710 return [[self class] _attributeKeys];
1713 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1714 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1717 - (NSString *) operator {
1721 - (NSString *) value {
1727 /* CydiaClause Class {{{ */
1728 @interface CydiaClause : NSObject {
1729 _H<NSString> package_;
1730 _H<CydiaOperation> version_;
1733 - (NSString *) package;
1734 - (CydiaOperation *) version;
1738 @implementation CydiaClause
1740 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1741 if ((self = [super init]) != nil) {
1742 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1744 if (const char *version = dep.TargetVer())
1745 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1747 version_ = (id) [NSNull null];
1751 + (NSArray *) _attributeKeys {
1752 return [NSArray arrayWithObjects:
1758 - (NSArray *) attributeKeys {
1759 return [[self class] _attributeKeys];
1762 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1763 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1766 - (NSString *) package {
1770 - (CydiaOperation *) version {
1776 /* CydiaRelation Class {{{ */
1777 @interface CydiaRelation : NSObject {
1778 _H<NSString> relationship_;
1779 _H<NSMutableArray> clauses_;
1782 - (NSString *) relationship;
1783 - (NSArray *) clauses;
1787 @implementation CydiaRelation
1789 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1790 if ((self = [super init]) != nil) {
1791 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1792 clauses_ = [NSMutableArray arrayWithCapacity:8];
1794 pkgCache::DepIterator start;
1795 pkgCache::DepIterator end;
1796 dep.GlobOr(start, end); // ++dep
1799 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1801 // yes, seriously. (wtf?)
1809 + (NSArray *) _attributeKeys {
1810 return [NSArray arrayWithObjects:
1816 - (NSArray *) attributeKeys {
1817 return [[self class] _attributeKeys];
1820 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1821 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1824 - (NSString *) relationship {
1825 return relationship_;
1828 - (NSArray *) clauses {
1832 - (void) addClause:(CydiaClause *)clause {
1833 [clauses_ addObject:clause];
1838 /* Package Class {{{ */
1839 struct ParsedPackage {
1843 CYString architecture_;
1846 CYString depiction_;
1856 @interface Package : NSObject {
1859 uint32_t essential_ : 1;
1860 uint32_t obsolete_ : 1;
1861 uint32_t ignored_ : 1;
1862 uint32_t pooled_ : 1;
1868 _transient Database *database_;
1870 pkgCache::VerIterator version_;
1871 pkgCache::PkgIterator iterator_;
1872 pkgCache::VerFileIterator file_;
1878 CYString installed_;
1880 const char *section_;
1881 _transient NSString *section$_;
1885 PackageValue *metadata_;
1886 ParsedPackage *parsed_;
1888 _H<NSMutableArray> tags_;
1891 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1892 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1894 - (pkgCache::PkgIterator) iterator;
1897 - (NSString *) section;
1898 - (NSString *) simpleSection;
1900 - (NSString *) longSection;
1901 - (NSString *) shortSection;
1905 - (MIMEAddress *) maintainer;
1907 - (NSString *) longDescription;
1908 - (NSString *) shortDescription;
1911 - (PackageValue *) metadata;
1914 - (bool) subscribed;
1915 - (bool) setSubscribed:(bool)subscribed;
1919 - (NSString *) latest;
1920 - (NSString *) installed;
1921 - (BOOL) uninstalled;
1924 - (BOOL) upgradableAndEssential:(BOOL)essential;
1927 - (BOOL) unfiltered;
1931 - (BOOL) halfConfigured;
1932 - (BOOL) halfInstalled;
1934 - (NSString *) mode;
1937 - (NSString *) name;
1939 - (NSString *) homepage;
1940 - (NSString *) depiction;
1941 - (MIMEAddress *) author;
1943 - (NSString *) support;
1945 - (NSArray *) files;
1946 - (NSArray *) warnings;
1947 - (NSArray *) applications;
1949 - (Source *) source;
1952 - (BOOL) matches:(NSArray *)query;
1954 - (bool) hasSupportingRole;
1955 - (BOOL) hasTag:(NSString *)tag;
1956 - (NSString *) primaryPurpose;
1957 - (NSArray *) purposes;
1958 - (bool) isCommercial;
1960 - (void) setIndex:(size_t)index;
1962 - (CYString &) cyname;
1964 - (uint32_t) compareBySection:(NSArray *)sections;
1969 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1970 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1971 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1972 - (bool) isVisibleInSection:(NSString *)section;
1973 - (bool) isVisibleInSource:(Source *)source;
1977 uint32_t PackageChangesRadix(Package *self, void *) {
1982 uint32_t timestamp : 30;
1983 uint32_t ignored : 1;
1984 uint32_t upgradable : 1;
1988 bool upgradable([self upgradableAndEssential:YES]);
1989 value.bits.upgradable = upgradable ? 1 : 0;
1992 value.bits.timestamp = 0;
1993 value.bits.ignored = [self ignored] ? 0 : 1;
1994 value.bits.upgradable = 1;
1996 value.bits.timestamp = [self seen] >> 2;
1997 value.bits.ignored = 0;
1998 value.bits.upgradable = 0;
2001 return _not(uint32_t) - value.key;
2004 uint32_t PackagePrefixRadix(Package *self, void *context) {
2005 size_t offset(reinterpret_cast<size_t>(context));
2006 CYString &name([self cyname]);
2008 size_t size(name.size());
2011 char *text(name.data());
2014 if (!isdigit(text[0]))
2018 while (size != digits && isdigit(text[digits]))
2026 if (offset == 0 && zeros != 0) {
2027 memset(data, '0', zeros);
2028 memcpy(data + zeros, text, 4 - zeros);
2030 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2031 if (size <= offset - zeros)
2034 text += offset - zeros;
2035 size -= offset - zeros;
2038 memcpy(data, text, 4);
2040 memcpy(data, text, size);
2041 memset(data + size, 0, 4 - size);
2044 for (size_t i(0); i != 4; ++i)
2045 if (isalpha(data[i]))
2053 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2055 /* XXX: ntohl may be more honest */
2056 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2059 CYString &(*PackageName)(Package *self, SEL sel);
2061 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2062 _profile(PackageNameCompare)
2063 CYString &lhi(PackageName(lhs, @selector(cyname)));
2064 CYString &rhi(PackageName(rhs, @selector(cyname)));
2065 CFStringRef lhn(lhi), rhn(rhi);
2068 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2069 else if (rhn == NULL)
2070 return NSOrderedDescending;
2072 _profile(PackageNameCompare$NumbersLast)
2073 if (!lhi.empty() && !rhi.empty()) {
2074 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2075 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2076 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2077 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2078 return lha ? NSOrderedAscending : NSOrderedDescending;
2082 CFIndex length = CFStringGetLength(lhn);
2084 _profile(PackageNameCompare$Compare)
2085 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2090 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2091 return PackageNameCompare(*lhs, *rhs, context);
2094 struct PackageNameOrdering :
2095 std::binary_function<Package *, Package *, bool>
2097 _finline bool operator ()(Package *lhs, Package *rhs) const {
2098 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2102 @implementation Package
2104 - (NSString *) description {
2105 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2110 apr_pool_destroy(pool_);
2111 if (parsed_ != NULL)
2116 + (NSString *) webScriptNameForSelector:(SEL)selector {
2118 else if (selector == @selector(clear))
2120 else if (selector == @selector(getField:))
2122 else if (selector == @selector(hasTag:))
2124 else if (selector == @selector(install))
2126 else if (selector == @selector(remove))
2132 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2133 return [self webScriptNameForSelector:selector] == nil;
2136 + (NSArray *) _attributeKeys {
2137 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_},
2240 {"md5sum", &parsed->md5sum_},
2243 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2244 const char *start, *end;
2246 if (parser->Find(names[i].name_, start, end)) {
2247 CYString &value(*names[i].value_);
2248 _profile(Package$parse$Value)
2249 value.set(pool_, start, end - start);
2255 _profile(Package$parse$Tagline)
2256 const char *start, *end;
2257 if (parser->ShortDesc(start, end)) {
2258 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2261 while (stop != start && stop[-1] == '\r')
2263 parsed->tagline_.set(pool_, start, stop - start);
2267 _profile(Package$parse$Retain)
2268 if (parsed->homepage_.empty())
2269 parsed->homepage_ = website;
2270 if (parsed->homepage_ == parsed->depiction_)
2271 parsed->homepage_.clear();
2276 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2277 if ((self = [super init]) != nil) {
2278 _profile(Package$initWithVersion)
2280 apr_pool_create(&pool_, NULL);
2286 database_ = database;
2287 era_ = [database era];
2291 pkgCache::PkgIterator iterator(version.ParentPkg());
2292 iterator_ = iterator;
2294 _profile(Package$initWithVersion$Version)
2295 if (!version_.end())
2296 file_ = version_.FileList();
2298 pkgCache &cache([database_ cache]);
2299 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2303 _profile(Package$initWithVersion$Cache)
2304 name_.set(NULL, iterator.Display());
2306 latest_.set(NULL, StripVersion_(version_.VerStr()));
2308 pkgCache::VerIterator current(iterator.CurrentVer());
2310 installed_.set(NULL, StripVersion_(current.VerStr()));
2313 _profile(Package$initWithVersion$Tags)
2314 pkgCache::TagIterator tag(iterator.TagList());
2316 tags_ = [NSMutableArray arrayWithCapacity:8];
2318 const char *name(tag.Name());
2319 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2321 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2322 if (strcmp(name + 6, "enduser") == 0)
2324 else if (strcmp(name + 6, "hacker") == 0)
2326 else if (strcmp(name + 6, "developer") == 0)
2328 else if (strcmp(name + 6, "cydia") == 0)
2334 if (strncmp(name, "cydia::", 7) == 0) {
2335 if (strcmp(name + 7, "essential") == 0)
2337 else if (strcmp(name + 7, "obsolete") == 0)
2342 } while (!tag.end());
2346 _profile(Package$initWithVersion$Metadata)
2347 const char *mixed(iterator.Name());
2348 size_t size(strlen(mixed));
2349 char lower[size + 1];
2351 for (size_t i(0); i != size; ++i)
2352 lower[i] = mixed[i] | 0x20;
2355 PackageValue *metadata(PackageFind(lower, size));
2356 metadata_ = metadata;
2358 id_.set(NULL, metadata->name_, size);
2360 const char *latest(version_.VerStr());
2361 size_t length(strlen(latest));
2363 uint16_t vhash(hashlittle(latest, length));
2365 size_t capped(std::min<size_t>(8, length));
2366 latest = latest + length - capped;
2368 if (metadata->first_ == 0)
2369 metadata->first_ = now_;
2371 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2372 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2373 metadata->vhash_ = vhash;
2374 metadata->last_ = now_;
2375 } else if (metadata->last_ == 0)
2376 metadata->last_ = metadata->first_;
2379 _profile(Package$initWithVersion$Section)
2380 section_ = iterator.Section();
2383 _profile(Package$initWithVersion$Flags)
2384 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2385 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2390 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2391 pkgCache::VerIterator version;
2393 _profile(Package$packageWithIterator$GetCandidateVer)
2394 version = [database policy]->GetCandidateVer(iterator);
2402 _profile(Package$packageWithIterator$Allocate)
2403 package = [Package allocWithZone:zone];
2406 _profile(Package$packageWithIterator$Initialize)
2408 initWithVersion:version
2415 _profile(Package$packageWithIterator$Autorelease)
2416 package = [package autorelease];
2422 - (pkgCache::PkgIterator) iterator {
2426 - (NSString *) section {
2427 if (section$_ == nil) {
2428 if (section_ == NULL)
2431 _profile(Package$section$mappedSectionForPointer)
2432 section$_ = [database_ mappedSectionForPointer:section_];
2437 - (NSString *) simpleSection {
2438 if (NSString *section = [self section])
2439 return Simplify(section);
2444 - (NSString *) longSection {
2445 return LocalizeSection([self section]);
2448 - (NSString *) shortSection {
2449 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2452 - (NSString *) uri {
2455 pkgIndexFile *index;
2456 pkgCache::PkgFileIterator file(file_.File());
2457 if (![database_ list].FindIndex(file, index))
2459 return [NSString stringWithUTF8String:iterator_->Path];
2460 //return [NSString stringWithUTF8String:file.Site()];
2461 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2465 - (MIMEAddress *) maintainer {
2466 @synchronized (database_) {
2467 if ([database_ era] != era_ || file_.end())
2470 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2471 const std::string &maintainer(parser->Maintainer());
2472 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2475 - (NSString *) md5sum {
2476 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2480 @synchronized (database_) {
2481 if ([database_ era] != era_ || version_.end())
2484 return version_->InstalledSize;
2487 - (NSString *) longDescription {
2488 @synchronized (database_) {
2489 if ([database_ era] != era_ || file_.end())
2492 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2493 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2495 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2496 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2497 if ([lines count] < 2)
2500 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2501 for (size_t i(1), e([lines count]); i != e; ++i) {
2502 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2503 [trimmed addObject:trim];
2506 return [trimmed componentsJoinedByString:@"\n"];
2509 - (NSString *) shortDescription {
2510 if (parsed_ != NULL)
2511 return static_cast<NSString *>(parsed_->tagline_);
2513 @synchronized (database_) {
2514 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2516 const char *start, *end;
2517 if (!parser.ShortDesc(start, end))
2520 if (end - start > 200)
2524 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2527 while (end != start && end[-1] == '\r')
2531 return [(id) CYStringCreate(start, end - start) autorelease];
2535 _profile(Package$index)
2536 CFStringRef name((CFStringRef) [self name]);
2537 if (CFStringGetLength(name) == 0)
2539 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2540 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2542 return toupper(character);
2546 - (PackageValue *) metadata {
2551 PackageValue *metadata([self metadata]);
2552 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2555 - (bool) subscribed {
2556 return [self metadata]->subscribed_;
2559 - (bool) setSubscribed:(bool)subscribed {
2560 PackageValue *metadata([self metadata]);
2561 if (metadata->subscribed_ == subscribed)
2563 metadata->subscribed_ = subscribed;
2571 - (NSString *) latest {
2575 - (NSString *) installed {
2579 - (BOOL) uninstalled {
2580 return installed_.empty();
2584 return !version_.end();
2587 - (BOOL) upgradableAndEssential:(BOOL)essential {
2588 _profile(Package$upgradableAndEssential)
2589 pkgCache::VerIterator current(iterator_.CurrentVer());
2591 return essential && essential_;
2593 return !version_.end() && version_ != current;
2597 - (BOOL) essential {
2602 return [database_ cache][iterator_].InstBroken();
2605 - (BOOL) unfiltered {
2606 _profile(Package$unfiltered$obsolete)
2607 if (_unlikely(obsolete_))
2611 _profile(Package$unfiltered$hasSupportingRole)
2612 if (_unlikely(![self hasSupportingRole]))
2620 if (![self unfiltered])
2625 _profile(Package$visible$section)
2626 section = [self section];
2629 _profile(Package$visible$isSectionVisible)
2630 if (!isSectionVisible(section))
2638 unsigned char current(iterator_->CurrentState);
2639 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2642 - (BOOL) halfConfigured {
2643 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2646 - (BOOL) halfInstalled {
2647 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2651 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2652 return state.Mode != pkgDepCache::ModeKeep;
2655 - (NSString *) mode {
2656 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2658 switch (state.Mode) {
2659 case pkgDepCache::ModeDelete:
2660 if ((state.iFlags & pkgDepCache::Purge) != 0)
2664 case pkgDepCache::ModeKeep:
2665 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2666 return @"REINSTALL";
2667 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2671 case pkgDepCache::ModeInstall:
2672 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2673 return @"REINSTALL";
2674 else*/ switch (state.Status) {
2676 return @"DOWNGRADE";
2682 return @"NEW_INSTALL";
2693 - (NSString *) name {
2694 return name_.empty() ? id_ : name_;
2697 - (UIImage *) icon {
2698 NSString *section = [self simpleSection];
2701 if (parsed_ != NULL)
2702 if (NSString *href = parsed_->icon_)
2703 if ([href hasPrefix:@"file:///"])
2704 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2705 if (icon == nil) if (section != nil)
2706 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2707 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2708 if ([dicon hasPrefix:@"file:///"])
2709 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2711 icon = [UIImage applicationImageNamed:@"unknown.png"];
2715 - (NSString *) homepage {
2716 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2719 - (NSString *) depiction {
2720 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2723 - (MIMEAddress *) sponsor {
2724 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2727 - (MIMEAddress *) author {
2728 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2731 - (NSString *) support {
2732 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2735 - (NSArray *) files {
2736 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2737 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2740 fin.open([path UTF8String]);
2745 while (std::getline(fin, line))
2746 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2751 - (NSString *) state {
2752 @synchronized (database_) {
2753 if ([database_ era] != era_ || file_.end())
2756 switch (iterator_->CurrentState) {
2757 case pkgCache::State::NotInstalled:
2758 return @"NotInstalled";
2759 case pkgCache::State::UnPacked:
2761 case pkgCache::State::HalfConfigured:
2762 return @"HalfConfigured";
2763 case pkgCache::State::HalfInstalled:
2764 return @"HalfInstalled";
2765 case pkgCache::State::ConfigFiles:
2766 return @"ConfigFiles";
2767 case pkgCache::State::Installed:
2768 return @"Installed";
2769 case pkgCache::State::TriggersAwaited:
2770 return @"TriggersAwaited";
2771 case pkgCache::State::TriggersPending:
2772 return @"TriggersPending";
2775 return (NSString *) [NSNull null];
2778 - (NSString *) selection {
2779 @synchronized (database_) {
2780 if ([database_ era] != era_ || file_.end())
2783 switch (iterator_->SelectedState) {
2784 case pkgCache::State::Unknown:
2786 case pkgCache::State::Install:
2788 case pkgCache::State::Hold:
2790 case pkgCache::State::DeInstall:
2791 return @"DeInstall";
2792 case pkgCache::State::Purge:
2796 return (NSString *) [NSNull null];
2799 - (NSArray *) warnings {
2800 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2801 const char *name(iterator_.Name());
2803 size_t length(strlen(name));
2804 if (length < 2) invalid:
2805 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2806 else for (size_t i(0); i != length; ++i)
2808 /* XXX: technically this is not allowed */
2809 (name[i] < 'A' || name[i] > 'Z') &&
2810 (name[i] < 'a' || name[i] > 'z') &&
2811 (name[i] < '0' || name[i] > '9') &&
2812 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2815 if (strcmp(name, "cydia") != 0) {
2818 bool _private = false;
2821 bool repository = [[self section] isEqualToString:@"Repositories"];
2823 if (NSArray *files = [self files])
2824 for (NSString *file in files)
2825 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2827 else if (!user && [file isEqualToString:@"/User"])
2829 else if (!_private && [file isEqualToString:@"/private"])
2831 else if (!stash && [file isEqualToString:@"/var/stash"])
2834 /* XXX: this is not sensitive enough. only some folders are valid. */
2835 if (cydia && !repository)
2836 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2838 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2840 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2842 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2845 return [warnings count] == 0 ? nil : warnings;
2848 - (NSArray *) applications {
2849 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2851 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2853 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2854 if (NSArray *files = [self files])
2855 for (NSString *file in files)
2856 if (application_r(file)) {
2857 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2858 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2859 if ([id isEqualToString:me])
2862 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2864 display = application_r[1];
2866 NSString *bundle([file stringByDeletingLastPathComponent]);
2867 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2868 if (icon == nil || [icon length] == 0)
2870 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2872 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2873 [applications addObject:application];
2875 [application addObject:id];
2876 [application addObject:display];
2877 [application addObject:url];
2880 return [applications count] == 0 ? nil : applications;
2883 - (Source *) source {
2884 if (source_ == nil) {
2885 @synchronized (database_) {
2886 if ([database_ era] != era_ || file_.end())
2887 source_ = (Source *) [NSNull null];
2889 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2893 return source_ == (Source *) [NSNull null] ? nil : source_;
2900 - (BOOL) matches:(NSArray *)query {
2901 if (query == nil || [query count] == 0)
2910 string = [self name];
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;
2921 length = [string length];
2923 for (NSString *term in query) {
2924 range = [string rangeOfString:term options:MatchCompareOptions_];
2925 if (range.location != NSNotFound)
2926 rank_ -= 6 * 1000000 / length;
2930 string = [self shortDescription];
2931 length = [string length];
2932 NSUInteger stop(std::min<NSUInteger>(length, 200));
2934 for (NSString *term in query) {
2935 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2936 if (range.location != NSNotFound)
2937 rank_ -= 2 * 100000;
2943 - (bool) hasSupportingRole {
2948 if ([Role_ isEqualToString:@"User"])
2952 if ([Role_ isEqualToString:@"Hacker"])
2956 if ([Role_ isEqualToString:@"Developer"])
2961 - (NSArray *) tags {
2965 - (BOOL) hasTag:(NSString *)tag {
2966 return tags_ == nil ? NO : [tags_ containsObject:tag];
2969 - (NSString *) primaryPurpose {
2970 for (NSString *tag in (NSArray *) tags_)
2971 if ([tag hasPrefix:@"purpose::"])
2972 return [tag substringFromIndex:9];
2976 - (NSArray *) purposes {
2977 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2978 for (NSString *tag in (NSArray *) tags_)
2979 if ([tag hasPrefix:@"purpose::"])
2980 [purposes addObject:[tag substringFromIndex:9]];
2981 return [purposes count] == 0 ? nil : purposes;
2984 - (bool) isCommercial {
2985 return [self hasTag:@"cydia::commercial"];
2988 - (void) setIndex:(size_t)index {
2989 if (metadata_->index_ != index)
2990 metadata_->index_ = index;
2993 - (CYString &) cyname {
2994 return name_.empty() ? id_ : name_;
2997 - (uint32_t) compareBySection:(NSArray *)sections {
2998 NSString *section([self section]);
2999 for (size_t i(0), e([sections count]); i != e; ++i) {
3000 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3004 return _not(uint32_t);
3008 @synchronized (database_) {
3009 pkgProblemResolver *resolver = [database_ resolver];
3010 resolver->Clear(iterator_);
3012 pkgCacheFile &cache([database_ cache]);
3013 cache->SetReInstall(iterator_, false);
3014 cache->MarkKeep(iterator_, false);
3018 @synchronized (database_) {
3019 pkgProblemResolver *resolver = [database_ resolver];
3020 resolver->Clear(iterator_);
3021 resolver->Protect(iterator_);
3023 pkgCacheFile &cache([database_ cache]);
3024 cache->SetReInstall(iterator_, false);
3025 cache->MarkInstall(iterator_, false);
3027 pkgDepCache::StateCache &state((*cache)[iterator_]);
3028 if (!state.Install())
3029 cache->SetReInstall(iterator_, true);
3033 @synchronized (database_) {
3034 pkgProblemResolver *resolver = [database_ resolver];
3035 resolver->Clear(iterator_);
3036 resolver->Remove(iterator_);
3037 resolver->Protect(iterator_);
3039 pkgCacheFile &cache([database_ cache]);
3040 cache->SetReInstall(iterator_, false);
3041 cache->MarkDelete(iterator_, true);
3044 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3045 _profile(Package$isUnfilteredAndSearchedForBy)
3048 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3049 value &= [self unfiltered];
3052 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3053 value &= [self matches:query];
3060 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3061 if ([search length] == 0)
3064 _profile(Package$isUnfilteredAndSelectedForBy)
3067 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3068 value &= [self unfiltered];
3071 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3072 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3079 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3080 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3083 - (bool) isVisibleInSection:(NSString *)name {
3084 NSString *section([self section]);
3088 section == nil && [name length] == 0 ||
3089 [name isEqualToString:section]
3090 ) && [self visible];
3093 - (bool) isVisibleInSource:(Source *)source {
3094 return [self source] == source && [self visible];
3099 /* Section Class {{{ */
3100 @interface Section : NSObject {
3105 _H<NSString> localized_;
3108 - (NSComparisonResult) compareByLocalized:(Section *)section;
3109 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3110 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3111 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3112 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3113 - (NSString *) name;
3120 - (void) addToCount;
3122 - (void) setCount:(size_t)count;
3123 - (NSString *) localized;
3127 @implementation Section
3129 - (NSComparisonResult) compareByLocalized:(Section *)section {
3130 NSString *lhs(localized_);
3131 NSString *rhs([section localized]);
3133 /*if ([lhs length] != 0 && [rhs length] != 0) {
3134 unichar lhc = [lhs characterAtIndex:0];
3135 unichar rhc = [rhs characterAtIndex:0];
3137 if (isalpha(lhc) && !isalpha(rhc))
3138 return NSOrderedAscending;
3139 else if (!isalpha(lhc) && isalpha(rhc))
3140 return NSOrderedDescending;
3143 return [lhs compare:rhs options:LaxCompareOptions_];
3146 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3147 if ((self = [self initWithName:name localize:NO]) != nil) {
3148 if (localized != nil)
3149 localized_ = localized;
3153 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3154 return [self initWithName:name row:0 localize:localize];
3157 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3158 if ((self = [super init]) != nil) {
3163 localized_ = LocalizeSection(name_);
3167 /* XXX: localize the index thingees */
3168 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3169 if ((self = [super init]) != nil) {
3170 name_ = [NSString stringWithCharacters:&index length:1];
3176 - (NSString *) name {
3196 - (void) addToCount {
3200 - (void) setCount:(size_t)count {
3204 - (NSString *) localized {
3211 class CydiaLogCleaner :
3212 public pkgArchiveCleaner
3215 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3220 /* Database Implementation {{{ */
3221 @implementation Database
3223 + (Database *) sharedInstance {
3224 static _H<Database> instance;
3225 if (instance == nil)
3226 instance = [[[Database alloc] init] autorelease];
3234 - (void) releasePackages {
3235 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3236 CFArrayRemoveAllValues(packages_);
3240 // XXX: actually implement this thing
3242 [self releasePackages];
3243 apr_pool_destroy(pool_);
3244 NSRecycleZone(zone_);
3248 - (void) _readCydia:(NSNumber *)fd {
3249 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3250 std::istream is(&ib);
3253 static Pcre finish_r("^finish:([^:]*)$");
3255 while (std::getline(is, line)) {
3256 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3258 const char *data(line.c_str());
3259 size_t size = line.size();
3260 lprintf("C:%s\n", data);
3262 if (finish_r(data, size)) {
3263 NSString *finish = finish_r[1];
3264 int index = [Finishes_ indexOfObject:finish];
3265 if (index != INT_MAX && index > Finish_)
3275 - (void) _readStatus:(NSNumber *)fd {
3276 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3277 std::istream is(&ib);
3280 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3281 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3283 while (std::getline(is, line)) {
3284 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3286 const char *data(line.c_str());
3287 size_t size(line.size());
3288 lprintf("S:%s\n", data);
3290 if (conffile_r(data, size)) {
3291 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3292 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3293 } else if (strncmp(data, "status: ", 8) == 0) {
3294 // status: <package>: {unpacked,half-configured,installed}
3295 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3296 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3297 } else if (strncmp(data, "processing: ", 12) == 0) {
3298 // processing: configure: config-test
3299 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3300 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3301 } else if (pmstatus_r(data, size)) {
3302 std::string type([pmstatus_r[1] UTF8String]);
3304 NSString *package = pmstatus_r[2];
3305 if ([package isEqualToString:@"dpkg-exec"])
3308 float percent([pmstatus_r[3] floatValue]);
3309 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3311 NSString *string = pmstatus_r[4];
3313 if (type == "pmerror") {
3314 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3315 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3316 } else if (type == "pmstatus") {
3317 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3318 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3319 } else if (type == "pmconffile")
3320 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3322 lprintf("E:unknown pmstatus\n");
3324 lprintf("E:unknown status\n");
3332 - (void) _readOutput:(NSNumber *)fd {
3333 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3334 std::istream is(&ib);
3337 while (std::getline(is, line)) {
3338 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3340 lprintf("O:%s\n", line.c_str());
3342 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3343 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3355 - (Package *) packageWithName:(NSString *)name {
3358 @synchronized (self) {
3359 if (static_cast<pkgDepCache *>(cache_) == NULL)
3361 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3362 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3366 if ((self = [super init]) != nil) {
3373 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3374 apr_pool_create(&pool_, NULL);
3376 size_t capacity(MetaFile_->active_);
3382 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3383 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3387 _assert(pipe(fds) != -1);
3390 _config->Set("APT::Keep-Fds::", cydiafd_);
3391 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3394 detachNewThreadSelector:@selector(_readCydia:)
3396 withObject:[NSNumber numberWithInt:fds[0]]
3399 _assert(pipe(fds) != -1);
3403 detachNewThreadSelector:@selector(_readStatus:)
3405 withObject:[NSNumber numberWithInt:fds[0]]
3408 _assert(pipe(fds) != -1);
3409 _assert(dup2(fds[0], 0) != -1);
3410 _assert(close(fds[0]) != -1);
3412 input_ = fdopen(fds[1], "a");
3414 _assert(pipe(fds) != -1);
3415 _assert(dup2(fds[1], 1) != -1);
3416 _assert(close(fds[1]) != -1);
3419 detachNewThreadSelector:@selector(_readOutput:)
3421 withObject:[NSNumber numberWithInt:fds[0]]
3426 - (pkgCacheFile &) cache {
3430 - (pkgDepCache::Policy *) policy {
3434 - (pkgRecords *) records {
3438 - (pkgProblemResolver *) resolver {
3442 - (pkgAcquire &) fetcher {
3446 - (pkgSourceList &) list {
3450 - (NSArray *) packages {
3451 return (NSArray *) packages_;
3454 - (NSArray *) sources {
3458 - (Source *) sourceWithKey:(NSString *)key {
3459 for (Source *source in [self sources]) {
3460 if ([[source key] isEqualToString:key])
3465 - (bool) popErrorWithTitle:(NSString *)title {
3468 while (!_error->empty()) {
3470 bool warning(!_error->PopMessage(error));
3475 size_t size(error.size());
3476 if (size == 0 || error[size - 1] != '\n')
3478 error.resize(size - 1);
3481 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3483 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3489 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3490 return [self popErrorWithTitle:title] || !success;
3493 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3494 @synchronized (self) {
3497 [self releasePackages];
3500 [sourceList_ removeAllObjects];
3520 apr_pool_clear(pool_);
3522 NSRecycleZone(zone_);
3523 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3525 int chk(creat("/tmp/cydia.chk", 0644));
3529 if (invocation != nil)
3530 [invocation invoke];
3532 NSString *title(UCLocalize("DATABASE"));
3535 OpProgress progress;
3536 while (!cache_.Open(progress, true)) { pop:
3538 bool warning(!_error->PopMessage(error));
3539 lprintf("cache_.Open():[%s]\n", error.c_str());
3541 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3542 [delegate_ repairWithSelector:@selector(configure)];
3543 else if (error == "The package lists or status file could not be parsed or opened.")
3544 [delegate_ repairWithSelector:@selector(update)];
3545 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3546 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3547 // else if (error == "Malformed Status line")
3548 // else if (error == "The list of sources could not be read.")
3550 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3560 unlink("/tmp/cydia.chk");
3562 now_ = [[NSDate date] timeIntervalSince1970];
3564 policy_ = new pkgDepCache::Policy();
3565 records_ = new pkgRecords(cache_);
3566 resolver_ = new pkgProblemResolver(cache_);
3567 fetcher_ = new pkgAcquire(&status_);
3570 list_ = new pkgSourceList();
3571 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3574 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3575 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3579 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3582 if (cache_->BrokenCount() != 0) {
3583 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3586 if (cache_->BrokenCount() != 0) {
3587 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3591 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3595 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3596 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3597 [sourceList_ addObject:object];
3599 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3600 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3601 // XXX: this could be more intelligent
3602 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3603 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3605 sourceMap_[cached->ID] = object;
3610 /*std::vector<Package *> packages;
3611 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3616 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3617 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3618 //packages.push_back(package);
3619 CFArrayAppendValue(packages_, CFRetain(package));
3623 /*if (packages.empty())
3624 packages_ = [[NSArray alloc] init];
3626 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3629 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3630 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3631 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3639 /*if (!packages.empty())
3640 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3641 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3643 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3645 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3647 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3651 size_t count(CFArrayGetCount(packages_));
3652 MetaFile_->active_ = count;
3654 for (size_t index(0); index != count; ++index)
3655 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3662 @synchronized (self) {
3664 resolver_ = new pkgProblemResolver(cache_);
3666 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3667 if (!cache_[iterator].Keep())
3668 cache_->MarkKeep(iterator, false);
3669 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3670 cache_->SetReInstall(iterator, false);
3673 - (void) configure {
3674 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3676 system([dpkg UTF8String]);
3681 // XXX: I don't remember this condition
3686 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3688 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3690 if ([self popErrorWithTitle:title])
3694 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3696 CydiaLogCleaner cleaner;
3697 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3704 fetcher_->Shutdown();
3706 pkgRecords records(cache_);
3708 lock_ = new FileFd();
3709 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3711 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3713 if ([self popErrorWithTitle:title])
3717 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3720 manager_ = (_system->CreatePM(cache_));
3721 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3728 bool substrate(RestartSubstrate_);
3729 RestartSubstrate_ = false;
3731 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3733 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3735 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3737 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3738 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3741 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3743 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3745 [self popErrorWithTitle:title];
3749 bool failed = false;
3750 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3751 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3753 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3759 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3767 RestartSubstrate_ = true;
3770 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3772 if (_error->PendingError()) {
3777 if (result == pkgPackageManager::Failed) {
3782 if (result != pkgPackageManager::Completed) {
3787 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3789 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3791 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3792 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3795 if (![before isEqualToArray:after])
3800 NSString *title(UCLocalize("UPGRADE"));
3801 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3807 [self updateWithStatus:status_];
3810 - (void) updateWithStatus:(Status &)status {
3811 NSString *title(UCLocalize("REFRESHING_DATA"));
3814 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3818 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3819 if ([self popErrorWithTitle:title])
3822 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3824 bool success(ListUpdate(status, list, PulseInterval_));
3825 if (status.WasCancelled())
3828 [self popErrorWithTitle:title forOperation:success];
3829 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3833 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3836 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3837 delegate_ = delegate;
3840 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3841 progress_ = delegate;
3842 status_.setDelegate(delegate);
3845 - (NSObject<ProgressDelegate> *) progressDelegate {
3849 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3850 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3851 return i == sourceMap_.end() ? nil : i->second;
3854 - (NSString *) mappedSectionForPointer:(const char *)section {
3855 _H<NSString> *mapped;
3857 _profile(Database$mappedSectionForPointer$Cache)
3858 mapped = §ions_[section];
3861 if (*mapped == NULL) {
3862 size_t length(strlen(section));
3863 char spaced[length + 1];
3865 _profile(Database$mappedSectionForPointer$Replace)
3866 for (size_t index(0); index != length; ++index)
3867 spaced[index] = section[index] == '_' ? ' ' : section[index];
3868 spaced[length] = '\0';
3873 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3874 string = [NSString stringWithUTF8String:spaced];
3877 _profile(Database$mappedSectionForPointer$Map)
3878 string = [SectionMap_ objectForKey:string] ?: string;
3888 static _H<NSMutableSet> Diversions_;
3890 @interface Diversion : NSObject {
3893 _H<NSString> format_;
3898 @implementation Diversion
3900 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3901 if ((self = [super init]) != nil) {
3902 pattern_ = [from UTF8String];
3908 - (NSString *) divert:(NSString *)url {
3909 return !pattern_(url) ? nil : pattern_->*format_;
3912 + (NSURL *) divertURL:(NSURL *)url {
3914 NSString *href([url absoluteString]);
3916 for (Diversion *diversion in (id) Diversions_)
3917 if (NSString *diverted = [diversion divert:href]) {
3919 NSLog(@"div: %@", diverted);
3921 url = [NSURL URLWithString:diverted];
3928 - (NSString *) key {
3932 - (NSUInteger) hash {
3936 - (BOOL) isEqual:(Diversion *)object {
3937 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3942 @interface CydiaObject : NSObject {
3943 _H<IndirectDelegate> indirect_;
3944 _transient id delegate_;
3947 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3951 @interface CydiaWebViewController : CyteWebViewController {
3952 _H<CydiaObject> cydia_;
3955 + (void) addDiversion:(Diversion *)diversion;
3959 /* Web Scripting {{{ */
3960 @implementation CydiaObject
3962 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3963 if ((self = [super init]) != nil) {
3964 indirect_ = indirect;
3968 - (void) setDelegate:(id)delegate {
3969 delegate_ = delegate;
3972 + (NSArray *) _attributeKeys {
3973 return [NSArray arrayWithObjects:
3990 - (NSArray *) attributeKeys {
3991 return [[self class] _attributeKeys];
3994 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3995 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3998 - (NSString *) version {
4002 - (NSString *) device {
4003 return [[UIDevice currentDevice] uniqueIdentifier];
4006 - (NSString *) firmware {
4007 return [[UIDevice currentDevice] systemVersion];
4010 - (NSString *) hostname {
4011 return [[UIDevice currentDevice] name];
4014 - (NSString *) idiom {
4015 return (id) Idiom_ ?: [NSNull null];
4018 - (NSString *) plmn {
4019 return (id) PLMN_ ?: [NSNull null];
4022 - (NSString *) bbsnum {
4023 return (id) BBSNum_ ?: [NSNull null];
4026 - (NSString *) ecid {
4027 return (id) ChipID_ ?: [NSNull null];
4030 - (NSString *) serial {
4031 return SerialNumber_;
4034 - (NSString *) role {
4035 return (id) Role_ ?: [NSNull null];
4038 - (NSString *) model {
4039 return [NSString stringWithUTF8String:Machine_];
4042 - (NSString *) token {
4043 return (id) Token_ ?: [NSNull null];
4046 + (NSString *) webScriptNameForSelector:(SEL)selector {
4048 else if (selector == @selector(addBridgedHost:))
4049 return @"addBridgedHost";
4050 else if (selector == @selector(addInsecureHost:))
4051 return @"addInsecureHost";
4052 else if (selector == @selector(addInternalRedirect::))
4053 return @"addInternalRedirect";
4054 else if (selector == @selector(addPipelinedHost:scheme:))
4055 return @"addPipelinedHost";
4056 else if (selector == @selector(addSource:::))
4057 return @"addSource";
4058 else if (selector == @selector(addTokenHost:))
4059 return @"addTokenHost";
4060 else if (selector == @selector(addTrivialSource:))
4061 return @"addTrivialSource";
4062 else if (selector == @selector(close))
4064 else if (selector == @selector(du:))
4066 else if (selector == @selector(stringWithFormat:arguments:))
4068 else if (selector == @selector(getAllSources))
4069 return @"getAllSourcs";
4070 else if (selector == @selector(getKernelNumber:))
4071 return @"getKernelNumber";
4072 else if (selector == @selector(getKernelString:))
4073 return @"getKernelString";
4074 else if (selector == @selector(getInstalledPackages))
4075 return @"getInstalledPackages";
4076 else if (selector == @selector(getIORegistryEntry::))
4077 return @"getIORegistryEntry";
4078 else if (selector == @selector(getLocaleIdentifier))
4079 return @"getLocaleIdentifier";
4080 else if (selector == @selector(getPreferredLanguages))
4081 return @"getPreferredLanguages";
4082 else if (selector == @selector(getPackageById:))
4083 return @"getPackageById";
4084 else if (selector == @selector(getMetadataKeys))
4085 return @"getMetadataKeys";
4086 else if (selector == @selector(getMetadataValue:))
4087 return @"getMetadataValue";
4088 else if (selector == @selector(getSessionValue:))
4089 return @"getSessionValue";
4090 else if (selector == @selector(installPackages:))
4091 return @"installPackages";
4092 else if (selector == @selector(localizedStringForKey:value:table:))
4094 else if (selector == @selector(popViewController:))
4095 return @"popViewController";
4096 else if (selector == @selector(refreshSources))
4097 return @"refreshSources";
4098 else if (selector == @selector(removeButton))
4099 return @"removeButton";
4100 else if (selector == @selector(saveConfig))
4101 return @"saveConfig";
4102 else if (selector == @selector(setCydiaSource:))
4103 return @"setCydiaSource";
4104 else if (selector == @selector(setMetadataValue::))
4105 return @"setMetadataValue";
4106 else if (selector == @selector(setSessionValue::))
4107 return @"setSessionValue";
4108 else if (selector == @selector(substitutePackageNames:))
4109 return @"substitutePackageNames";
4110 else if (selector == @selector(scrollToBottom:))
4111 return @"scrollToBottom";
4112 else if (selector == @selector(setAllowsNavigationAction:))
4113 return @"setAllowsNavigationAction";
4114 else if (selector == @selector(setBadgeValue:))
4115 return @"setBadgeValue";
4116 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4117 return @"setButtonImage";
4118 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4119 return @"setButtonTitle";
4120 else if (selector == @selector(setHidesBackButton:))
4121 return @"setHidesBackButton";
4122 else if (selector == @selector(setHidesNavigationBar:))
4123 return @"setHidesNavigationBar";
4124 else if (selector == @selector(setNavigationBarStyle:))
4125 return @"setNavigationBarStyle";
4126 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4127 return @"setNavigationBarTintColor";
4128 else if (selector == @selector(setPasteboardString:))
4129 return @"setPasteboardString";
4130 else if (selector == @selector(setPasteboardURL:))
4131 return @"setPasteboardURL";
4132 else if (selector == @selector(setToken:))
4134 else if (selector == @selector(setViewportWidth:))
4135 return @"setViewportWidth";
4136 else if (selector == @selector(statfs:))
4138 else if (selector == @selector(supports:))
4140 else if (selector == @selector(unload))
4146 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4147 return [self webScriptNameForSelector:selector] == nil;
4150 - (BOOL) supports:(NSString *)feature {
4151 return [feature isEqualToString:@"window.open"];
4155 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4158 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4159 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4162 - (NSNumber *) getKernelNumber:(NSString *)name {
4163 const char *string([name UTF8String]);
4166 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4167 return (id) [NSNull null];
4169 if (size != sizeof(int))
4170 return (id) [NSNull null];
4173 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4174 return (id) [NSNull null];
4176 return [NSNumber numberWithInt:value];
4179 - (NSString *) getKernelString:(NSString *)name {
4180 const char *string([name UTF8String]);
4183 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4184 return (id) [NSNull null];
4186 char value[size + 1];
4187 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4188 return (id) [NSNull null];
4190 // XXX: just in case you request something ludicrous
4193 return [NSString stringWithCString:value];
4196 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4197 NSObject *value(CYIOGetValue([path UTF8String], entry));
4200 if ([value isKindOfClass:[NSData class]])
4201 value = CYHex((NSData *) value);
4206 - (void) _setCydiaSource:(NSString *)source {
4207 @synchronized (HostConfig_) {
4208 CydiaSource_ = source;
4209 [Metadata_ setObject:source forKey:@"CydiaSource"];
4215 - (void) setCydiaSource:(NSString *)source {
4216 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4219 - (NSString *) cydiaSource {
4220 @synchronized (HostConfig_) {
4221 return (id) CydiaSource_ ?: [NSNull null];
4225 - (NSArray *) getMetadataKeys {
4226 @synchronized (Values_) {
4227 return [Values_ allKeys];
4230 - (id) getMetadataValue:(NSString *)key {
4231 @synchronized (Values_) {
4232 return [Values_ objectForKey:key];
4235 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4236 @synchronized (Values_) {
4237 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4238 [Values_ removeObjectForKey:key];
4240 [Values_ setObject:value forKey:key];
4242 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4245 - (id) getSessionValue:(NSString *)key {
4246 @synchronized (SessionData_) {
4247 return [SessionData_ objectForKey:key];
4250 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4251 @synchronized (SessionData_) {
4252 if (value == (id) [WebUndefined undefined])
4253 [SessionData_ removeObjectForKey:key];
4255 [SessionData_ setObject:value forKey:key];
4258 - (void) addBridgedHost:(NSString *)host {
4259 @synchronized (HostConfig_) {
4260 [BridgedHosts_ addObject:host];
4263 - (void) addInsecureHost:(NSString *)host {
4264 @synchronized (HostConfig_) {
4265 [InsecureHosts_ addObject:host];
4268 - (void) addTokenHost:(NSString *)host {
4269 @synchronized (HostConfig_) {
4270 [TokenHosts_ addObject:host];
4273 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4274 @synchronized (HostConfig_) {
4275 if (scheme != (id) [WebUndefined undefined])
4276 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4278 [PipelinedHosts_ addObject:host];
4281 - (void) popViewController:(NSNumber *)value {
4282 if (value == (id) [WebUndefined undefined])
4283 value = [NSNumber numberWithBool:YES];
4284 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4287 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4288 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4290 for (NSString *section in sections)
4291 [array addObject:section];
4293 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4296 distribution, @"Distribution",
4298 nil] waitUntilDone:NO];
4301 - (void) addTrivialSource:(NSString *)href {
4302 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4305 - (void) refreshSources {
4306 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4309 - (void) saveConfig {
4310 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4313 - (NSArray *) getAllSources {
4314 return [[Database sharedInstance] sources];
4317 - (NSArray *) getInstalledPackages {
4318 Database *database([Database sharedInstance]);
4319 @synchronized (database) {
4320 NSArray *packages([database packages]);
4321 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4322 for (Package *package in packages)
4323 if (![package uninstalled])
4324 [installed addObject:package];
4328 - (Package *) getPackageById:(NSString *)id {
4329 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4333 return (Package *) [NSNull null];
4336 - (NSString *) getLocaleIdentifier {
4337 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4340 - (NSArray *) getPreferredLanguages {
4344 - (NSArray *) statfs:(NSString *)path {
4347 if (path == nil || statfs([path UTF8String], &stat) == -1)
4350 return [NSArray arrayWithObjects:
4351 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4352 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4353 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4357 - (NSNumber *) du:(NSString *)path {
4358 NSNumber *value(nil);
4361 _assert(pipe(fds) != -1);
4363 pid_t pid(ExecFork());
4365 _assert(dup2(fds[1], 1) != -1);
4366 _assert(close(fds[0]) != -1);
4367 _assert(close(fds[1]) != -1);
4368 /* XXX: this should probably not use du */
4369 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4374 _assert(close(fds[1]) != -1);
4376 if (FILE *du = fdopen(fds[0], "r")) {
4378 while (fgets(line, sizeof(line), du) != NULL) {
4379 size_t length(strlen(line));
4380 while (length != 0 && line[length - 1] == '\n')
4381 line[--length] = '\0';
4382 if (char *tab = strchr(line, '\t')) {
4384 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4389 } else _assert(close(fds[0]));
4393 if (waitpid(pid, &status, 0) == -1)
4396 else _assert(false);
4402 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4405 - (void) installPackages:(NSArray *)packages {
4406 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4409 - (NSString *) substitutePackageNames:(NSString *)message {
4410 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4411 for (size_t i(0), e([words count]); i != e; ++i) {
4412 NSString *word([words objectAtIndex:i]);
4413 if (Package *package = [[Database sharedInstance] packageWithName:word])
4414 [words replaceObjectAtIndex:i withObject:[package name]];
4417 return [words componentsJoinedByString:@" "];
4420 - (void) removeButton {
4421 [indirect_ removeButton];
4424 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4425 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4428 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4429 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4432 - (void) setBadgeValue:(id)value {
4433 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4436 - (void) setAllowsNavigationAction:(NSString *)value {
4437 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4440 - (void) setHidesBackButton:(NSString *)value {
4441 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4444 - (void) setHidesNavigationBar:(NSString *)value {
4445 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4448 - (void) setNavigationBarStyle:(NSString *)value {
4449 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4452 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4453 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4454 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4455 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4458 - (void) setPasteboardString:(NSString *)value {
4459 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4462 - (void) setPasteboardURL:(NSString *)value {
4463 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4466 - (void) _setToken:(NSString *)token {
4470 [Metadata_ removeObjectForKey:@"Token"];
4472 [Metadata_ setObject:Token_ forKey:@"Token"];
4477 - (void) setToken:(NSString *)token {
4478 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4481 - (void) scrollToBottom:(NSNumber *)animated {
4482 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4485 - (void) setViewportWidth:(float)width {
4486 [indirect_ setViewportWidthOnMainThread:width];
4489 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4490 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4491 unsigned count([arguments count]);
4493 for (unsigned i(0); i != count; ++i)
4494 values[i] = [arguments objectAtIndex:i];
4495 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4498 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4499 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4501 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4503 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4509 @interface NSURL (CydiaSecure)
4512 @implementation NSURL (CydiaSecure)
4514 - (bool) isCydiaSecure {
4515 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4518 @synchronized (HostConfig_) {
4519 if ([InsecureHosts_ containsObject:[self host]])
4528 /* Cydia Browser Controller {{{ */
4529 @implementation CydiaWebViewController
4531 - (NSURL *) navigationURL {
4532 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4535 + (void) _initialize {
4536 [super _initialize];
4538 Diversions_ = [NSMutableSet setWithCapacity:0];
4541 + (void) addDiversion:(Diversion *)diversion {
4542 [Diversions_ addObject:diversion];
4545 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4546 [super webView:view didClearWindowObject:window forFrame:frame];
4548 WebDataSource *source([frame dataSource]);
4549 NSURLResponse *response([source response]);
4550 NSURL *url([response URL]);
4551 NSString *scheme([[url scheme] lowercaseString]);
4553 bool bridged(false);
4555 @synchronized (HostConfig_) {
4556 if ([scheme isEqualToString:@"file"])
4558 else if ([scheme isEqualToString:@"https"])
4559 if ([BridgedHosts_ containsObject:[url host]])
4564 [window setValue:cydia_ forKey:@"cydia"];
4567 - (void) _setupMail:(MFMailComposeViewController *)controller {
4568 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4570 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4571 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4574 - (NSURL *) URLWithURL:(NSURL *)url {
4575 return [Diversion divertURL:url];
4578 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4579 NSURL *url([request URL]);
4580 NSString *host([url host]);
4582 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4584 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4585 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4586 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4587 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4590 @synchronized (HostConfig_) {
4591 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4594 if ([url isCydiaSecure] && token) {
4595 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4596 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4602 - (void) setDelegate:(id)delegate {
4603 [super setDelegate:delegate];
4604 [cydia_ setDelegate:delegate];
4607 - (NSString *) applicationNameForUserAgent {
4608 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4611 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4613 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4614 if (Product_ != nil)
4615 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4621 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4622 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4628 @interface AppCacheController : CydiaWebViewController {
4633 @implementation AppCacheController
4635 - (void) didReceiveMemoryWarning {
4642 @interface NSObject (CydiaScript)
4643 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4646 @implementation NSObject (CydiaScript)
4648 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4654 @implementation NSArray (CydiaScript)
4656 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4657 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4658 for (size_t i(0), e([self count]); i != e; ++i)
4659 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4665 @implementation NSDictionary (CydiaScript)
4667 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4668 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4670 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4677 /* Confirmation Controller {{{ */
4678 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4679 if (!iterator.end())
4680 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4681 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4683 pkgCache::PkgIterator package(dep.TargetPkg());
4686 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4693 @protocol ConfirmationControllerDelegate
4694 - (void) cancelAndClear:(bool)clear;
4695 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4699 @interface ConfirmationController : CydiaWebViewController {
4700 _transient Database *database_;
4702 _H<UIAlertView> essential_;
4704 _H<NSDictionary> changes_;
4705 _H<NSMutableArray> issues_;
4706 _H<NSDictionary> sizes_;
4711 - (id) initWithDatabase:(Database *)database;
4715 @implementation ConfirmationController
4719 RestartSubstrate_ = true;
4720 [delegate_ confirmWithNavigationController:[self navigationController]];
4723 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4724 NSString *context([alert context]);
4726 if ([context isEqualToString:@"remove"]) {
4727 if (button == [alert cancelButtonIndex])
4728 [self dismissModalViewControllerAnimated:YES];
4729 else if (button == [alert firstOtherButtonIndex]) {
4733 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4734 } else if ([context isEqualToString:@"unable"]) {
4735 [self dismissModalViewControllerAnimated:YES];
4736 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4738 [super alertView:alert clickedButtonAtIndex:button];
4742 - (void) _doContinue {
4743 [delegate_ cancelAndClear:NO];
4744 [self dismissModalViewControllerAnimated:YES];
4747 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4748 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4752 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4753 [super webView:view didClearWindowObject:window forFrame:frame];
4755 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4756 (id) changes_, @"changes",
4757 (id) issues_, @"issues",
4758 (id) sizes_, @"sizes",
4760 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4763 - (id) initWithDatabase:(Database *)database {
4764 if ((self = [super init]) != nil) {
4765 database_ = database;
4767 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4768 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4769 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4770 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4771 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4775 pkgCacheFile &cache([database_ cache]);
4776 NSArray *packages([database_ packages]);
4777 pkgDepCache::Policy *policy([database_ policy]);
4779 issues_ = [NSMutableArray arrayWithCapacity:4];
4781 for (Package *package in packages) {
4782 pkgCache::PkgIterator iterator([package iterator]);
4783 NSString *name([package id]);
4785 if ([package broken]) {
4786 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4788 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4790 reasons, @"reasons",
4793 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4797 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4798 pkgCache::DepIterator start;
4799 pkgCache::DepIterator end;
4800 dep.GlobOr(start, end); // ++dep
4802 if (!cache->IsImportantDep(end))
4804 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4807 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4809 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4810 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4811 clauses, @"clauses",
4815 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4817 pkgCache::PkgIterator target(start.TargetPkg());
4818 if (target->ProvidesList != 0)
4819 reason = @"missing";
4821 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4823 reason = @"installed";
4824 installed = [NSString stringWithUTF8String:ver.VerStr()];
4825 } else if (!cache[target].CandidateVerIter(cache).end())
4826 reason = @"uninstalled";
4827 else if (target->ProvidesList == 0)
4828 reason = @"uninstallable";
4830 reason = @"virtual";
4833 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4834 [NSString stringWithUTF8String:start.CompType()], @"operator",
4835 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4838 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4839 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4840 version, @"version",
4842 installed, @"installed",
4845 // yes, seriously. (wtf?)
4853 pkgDepCache::StateCache &state(cache[iterator]);
4855 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4857 if (state.NewInstall())
4858 [installs addObject:name];
4859 // XXX: else if (state.Install())
4860 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4861 [reinstalls addObject:name];
4862 // XXX: move before previous if
4863 else if (state.Upgrade())
4864 [upgrades addObject:name];
4865 else if (state.Downgrade())
4866 [downgrades addObject:name];
4867 else if (!state.Delete())
4868 // XXX: _assert(state.Keep());
4870 else if (special_r(name))
4871 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4872 [NSNull null], @"package",
4873 [NSArray arrayWithObjects:
4874 [NSDictionary dictionaryWithObjectsAndKeys:
4875 @"Conflicts", @"relationship",
4876 [NSArray arrayWithObjects:
4877 [NSDictionary dictionaryWithObjectsAndKeys:
4879 [NSNull null], @"version",
4880 @"installed", @"reason",
4887 if ([package essential])
4889 [removes addObject:name];
4892 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4893 substrate_ |= DepSubstrate(iterator.CurrentVer());
4898 else if (Advanced_) {
4899 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4901 essential_ = [[[UIAlertView alloc]
4902 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4903 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4905 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4907 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4911 [essential_ setContext:@"remove"];
4913 essential_ = [[[UIAlertView alloc]
4914 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4915 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4917 cancelButtonTitle:UCLocalize("OKAY")
4918 otherButtonTitles:nil
4921 [essential_ setContext:@"unable"];
4924 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4925 installs, @"installs",
4926 reinstalls, @"reinstalls",
4927 upgrades, @"upgrades",
4928 downgrades, @"downgrades",
4929 removes, @"removes",
4932 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4933 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4934 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4937 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4941 - (UIBarButtonItem *) leftButton {
4942 return [[[UIBarButtonItem alloc]
4943 initWithTitle:UCLocalize("CANCEL")
4944 style:UIBarButtonItemStylePlain
4946 action:@selector(cancelButtonClicked)
4951 - (void) applyRightButton {
4952 if ([issues_ count] == 0 && ![self isLoading])
4953 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4954 initWithTitle:UCLocalize("CONFIRM")
4955 style:UIBarButtonItemStyleDone
4957 action:@selector(confirmButtonClicked)
4960 [[self navigationItem] setRightBarButtonItem:nil];
4964 - (void) cancelButtonClicked {
4965 [self dismissModalViewControllerAnimated:YES];
4966 [delegate_ cancelAndClear:YES];
4970 - (void) confirmButtonClicked {
4971 if (essential_ != nil)
4981 /* Progress Data {{{ */
4982 @interface CydiaProgressData : NSObject {
4983 _transient id delegate_;
4992 _H<NSMutableArray> events_;
4993 _H<NSString> title_;
4995 _H<NSString> status_;
4996 _H<NSString> finish_;
5001 @implementation CydiaProgressData
5003 + (NSArray *) _attributeKeys {
5004 return [NSArray arrayWithObjects:
5016 - (NSArray *) attributeKeys {
5017 return [[self class] _attributeKeys];
5020 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5021 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5025 if ((self = [super init]) != nil) {
5026 events_ = [NSMutableArray arrayWithCapacity:32];
5030 - (void) setDelegate:(id)delegate {
5031 delegate_ = delegate;
5034 - (void) setPercent:(float)value {
5038 - (NSNumber *) percent {
5039 return [NSNumber numberWithFloat:percent_];
5042 - (void) setCurrent:(float)value {
5046 - (NSNumber *) current {
5047 return [NSNumber numberWithFloat:current_];
5050 - (void) setTotal:(float)value {
5054 - (NSNumber *) total {
5055 return [NSNumber numberWithFloat:total_];
5058 - (void) setSpeed:(float)value {
5062 - (NSNumber *) speed {
5063 return [NSNumber numberWithFloat:speed_];
5066 - (NSArray *) events {
5070 - (void) removeAllEvents {
5071 [events_ removeAllObjects];
5074 - (void) addEvent:(CydiaProgressEvent *)event {
5075 [events_ addObject:event];
5078 - (void) setTitle:(NSString *)text {
5082 - (NSString *) title {
5086 - (void) setFinish:(NSString *)text {
5090 - (NSString *) finish {
5091 return (id) finish_ ?: [NSNull null];
5094 - (void) setRunning:(bool)running {
5098 - (NSNumber *) running {
5099 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5104 /* Progress Controller {{{ */
5105 @interface ProgressController : CydiaWebViewController <
5108 _transient Database *database_;
5109 _H<CydiaProgressData, 1> progress_;
5113 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5115 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5117 - (void) setTitle:(NSString *)title;
5118 - (void) setCancellable:(bool)cancellable;
5122 @implementation ProgressController
5125 [database_ setProgressDelegate:nil];
5129 - (UIBarButtonItem *) leftButton {
5130 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5131 initWithTitle:UCLocalize("CANCEL")
5132 style:UIBarButtonItemStylePlain
5134 action:@selector(cancel)
5135 ] autorelease] : nil;
5138 - (void) updateCancel {
5139 [super applyLeftButton];
5142 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5143 if ((self = [super init]) != nil) {
5144 database_ = database;
5145 delegate_ = delegate;
5147 [database_ setProgressDelegate:self];
5149 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5150 [progress_ setDelegate:self];
5152 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5154 [scroller_ setBackgroundColor:[UIColor blackColor]];
5156 [[self navigationItem] setHidesBackButton:YES];
5158 [self updateCancel];
5162 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5163 [super webView:view didClearWindowObject:window forFrame:frame];
5164 [window setValue:progress_ forKey:@"cydiaProgress"];
5167 - (void) updateProgress {
5168 [self dispatchEvent:@"CydiaProgressUpdate"];
5171 - (void) viewWillAppear:(BOOL)animated {
5172 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5173 [super viewWillAppear:animated];
5177 UpdateExternalStatus(0);
5180 [delegate_ saveState];
5184 [delegate_ returnToCydia];
5188 [delegate_ terminateWithSuccess];
5189 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5190 [delegate_ suspendWithAnimation:YES];
5192 [delegate_ suspend];*/
5204 system("/usr/bin/sbreload");
5210 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5211 SBReboot(SBSSpringBoardServerPort());
5213 reboot2(RB_AUTOBOOT);
5220 - (void) setTitle:(NSString *)title {
5221 [progress_ setTitle:title];
5222 [self updateProgress];
5225 - (UIBarButtonItem *) rightButton {
5226 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5227 initWithTitle:UCLocalize("CLOSE")
5228 style:UIBarButtonItemStylePlain
5230 action:@selector(close)
5234 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5235 UpdateExternalStatus(1);
5237 [progress_ setRunning:true];
5238 [self setTitle:title];
5239 // implicit updateProgress
5241 SHA1SumValue notifyconf; {
5243 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5246 MMap mmap(file, MMap::ReadOnly);
5248 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5249 notifyconf = sha1.Result();
5253 SHA1SumValue springlist; {
5255 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5258 MMap mmap(file, MMap::ReadOnly);
5260 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5261 springlist = sha1.Result();
5265 if (invocation != nil) {
5266 [invocation yieldToSelector:@selector(invoke)];
5267 [self setTitle:@"COMPLETE"];
5272 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5275 MMap mmap(file, MMap::ReadOnly);
5277 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5278 if (!(notifyconf == sha1.Result()))
5285 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5288 MMap mmap(file, MMap::ReadOnly);
5290 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5291 if (!(springlist == sha1.Result()))
5297 if (RestartSubstrate_)
5301 RestartSubstrate_ = false;
5304 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5305 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5306 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5307 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5308 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5312 system("su -c /usr/bin/uicache mobile");
5315 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5317 [progress_ setRunning:false];
5318 [self updateProgress];
5320 [self applyRightButton];
5323 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5324 [progress_ addEvent:event];
5325 [self updateProgress];
5328 - (bool) isProgressCancelled {
5329 return cancel_ == 2;
5334 [self updateCancel];
5337 - (void) setCancellable:(bool)cancellable {
5338 unsigned cancel(cancel_);
5342 else if (cancel_ == 0)
5345 if (cancel != cancel_)
5346 [self updateCancel];
5349 - (void) setProgressCancellable:(NSNumber *)cancellable {
5350 [self setCancellable:[cancellable boolValue]];
5353 - (void) setProgressPercent:(NSNumber *)percent {
5354 [progress_ setPercent:[percent floatValue]];
5355 [self updateProgress];
5358 - (void) setProgressStatus:(NSDictionary *)status {
5359 if (status == nil) {
5360 [progress_ setCurrent:0];
5361 [progress_ setTotal:0];
5362 [progress_ setSpeed:0];
5364 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5366 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5367 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5368 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5371 [self updateProgress];
5377 /* Package Cell {{{ */
5378 @interface PackageCell : CyteTableViewCell <
5379 CyteTableViewCellDelegate
5383 _H<NSString> description_;
5385 _H<NSString> source_;
5387 _H<UIImage> placard_;
5391 - (PackageCell *) init;
5392 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5394 - (void) drawContentRect:(CGRect)rect;
5398 @implementation PackageCell
5400 - (PackageCell *) init {
5401 CGRect frame(CGRectMake(0, 0, 320, 74));
5402 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5403 UIView *content([self contentView]);
5404 CGRect bounds([content bounds]);
5406 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5407 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5408 [content addSubview:content_];
5410 [content_ setDelegate:self];
5411 [content_ setOpaque:YES];
5415 - (NSString *) accessibilityLabel {
5416 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5419 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5420 summarized_ = summary;
5430 [content_ setBackgroundColor:[UIColor whiteColor]];
5434 Source *source = [package source];
5436 icon_ = [package icon];
5438 if (NSString *name = [package name])
5439 name_ = [NSString stringWithString:name];
5441 NSString *description(nil);
5443 if (description == nil && IsWildcat_)
5444 description = [package longDescription];
5445 if (description == nil)
5446 description = [package shortDescription];
5448 if (description != nil)
5449 description_ = [NSString stringWithString:description];
5451 commercial_ = [package isCommercial];
5453 NSString *label = nil;
5454 bool trusted = false;
5456 if (source != nil) {
5457 label = [source label];
5458 trusted = [source trusted];
5459 } else if ([[package id] isEqualToString:@"firmware"])
5460 label = UCLocalize("APPLE");
5462 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5464 NSString *from(label);
5466 NSString *section = [package simpleSection];
5467 if (section != nil && ![section isEqualToString:label]) {
5468 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5469 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5472 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5474 if (NSString *purpose = [package primaryPurpose])
5475 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5480 if (NSString *mode = [package mode]) {
5481 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5482 color = RemovingColor_;
5483 //placard = @"removing";
5485 color = InstallingColor_;
5486 //placard = @"installing";
5489 // XXX: the removing/installing placards are not @2x
5492 color = [UIColor whiteColor];
5494 if ([package installed] != nil)
5495 placard = @"installed";
5500 [content_ setBackgroundColor:color];
5503 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5506 [self setNeedsDisplay];
5507 [content_ setNeedsDisplay];
5510 - (void) drawSummaryContentRect:(CGRect)rect {
5511 bool highlighted(highlighted_);
5512 float width([self bounds].size.width);
5516 rect.size = [(UIImage *) icon_ size];
5518 rect.size.width /= 4;
5519 rect.size.height /= 4;
5521 rect.origin.x = 14 - rect.size.width / 4;
5522 rect.origin.y = 14 - rect.size.height / 4;
5524 [icon_ drawInRect:rect];
5527 if (badge_ != nil) {
5529 rect.size = [(UIImage *) badge_ size];
5531 rect.size.width /= 4;
5532 rect.size.height /= 4;
5534 rect.origin.x = 20 - rect.size.width / 4;
5535 rect.origin.y = 20 - rect.size.height / 4;
5537 [badge_ drawInRect:rect];
5544 UISetColor(commercial_ ? Purple_ : Black_);
5545 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5547 if (placard_ != nil)
5548 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5551 - (void) drawNormalContentRect:(CGRect)rect {
5552 bool highlighted(highlighted_);
5553 float width([self bounds].size.width);
5557 rect.size = [(UIImage *) icon_ size];
5559 rect.size.width /= 2;
5560 rect.size.height /= 2;
5562 rect.origin.x = 25 - rect.size.width / 2;
5563 rect.origin.y = 25 - rect.size.height / 2;
5565 [icon_ drawInRect:rect];
5568 if (badge_ != nil) {
5570 rect.size = [(UIImage *) badge_ size];
5572 rect.size.width /= 2;
5573 rect.size.height /= 2;
5575 rect.origin.x = 36 - rect.size.width / 2;
5576 rect.origin.y = 36 - rect.size.height / 2;
5578 [badge_ drawInRect:rect];
5585 UISetColor(commercial_ ? Purple_ : Black_);
5586 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5587 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5590 UISetColor(commercial_ ? Purplish_ : Gray_);
5591 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5593 if (placard_ != nil)
5594 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5597 - (void) drawContentRect:(CGRect)rect {
5599 [self drawSummaryContentRect:rect];
5601 [self drawNormalContentRect:rect];
5606 /* Section Cell {{{ */
5607 @interface SectionCell : CyteTableViewCell <
5608 CyteTableViewCellDelegate
5610 _H<NSString> basic_;
5611 _H<NSString> section_;
5613 _H<NSString> count_;
5615 _H<UISwitch> switch_;
5619 - (void) setSection:(Section *)section editing:(BOOL)editing;
5623 @implementation SectionCell
5625 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5626 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5627 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5628 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5629 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5631 UIView *content([self contentView]);
5632 CGRect bounds([content bounds]);
5634 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5635 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5636 [content addSubview:content_];
5637 [content_ setBackgroundColor:[UIColor whiteColor]];
5639 [content_ setDelegate:self];
5643 - (void) onSwitch:(id)sender {
5644 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5645 if (metadata == nil) {
5646 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5647 [Sections_ setObject:metadata forKey:basic_];
5650 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5654 - (void) setSection:(Section *)section editing:(BOOL)editing {
5655 if (editing != editing_) {
5657 [switch_ removeFromSuperview];
5659 [self addSubview:switch_];
5668 if (section == nil) {
5669 name_ = UCLocalize("ALL_PACKAGES");
5672 basic_ = [section name];
5673 section_ = [section localized];
5675 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5676 count_ = [NSString stringWithFormat:@"%d", [section count]];
5679 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5682 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5683 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5685 [content_ setNeedsDisplay];
5688 - (void) setFrame:(CGRect)frame {
5689 [super setFrame:frame];
5691 CGRect rect([switch_ frame]);
5692 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5695 - (NSString *) accessibilityLabel {
5699 - (void) drawContentRect:(CGRect)rect {
5700 bool highlighted(highlighted_ && !editing_);
5702 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5707 float width(rect.size.width);
5713 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5715 CGSize size = [count_ sizeWithFont:Font14_];
5719 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5725 /* File Table {{{ */
5726 @interface FileTable : CyteViewController <
5727 UITableViewDataSource,
5730 _transient Database *database_;
5731 _H<Package> package_;
5733 _H<NSMutableArray> files_;
5734 _H<UITableView, 2> list_;
5737 - (id) initWithDatabase:(Database *)database;
5738 - (void) setPackage:(Package *)package;
5742 @implementation FileTable
5744 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5745 return files_ == nil ? 0 : [files_ count];
5748 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5752 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5753 static NSString *reuseIdentifier = @"Cell";
5755 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5757 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5758 [cell setFont:[UIFont systemFontOfSize:16]];
5760 [cell setText:[files_ objectAtIndex:indexPath.row]];
5761 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5766 - (NSURL *) navigationURL {
5767 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5771 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5773 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5774 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5775 [list_ setRowHeight:24.0f];
5776 [(UITableView *) list_ setDataSource:self];
5777 [list_ setDelegate:self];
5778 [[self view] addSubview:list_];
5781 - (void) viewDidLoad {
5782 [super viewDidLoad];
5784 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5787 - (void) releaseSubviews {
5793 [super releaseSubviews];
5796 - (id) initWithDatabase:(Database *)database {
5797 if ((self = [super init]) != nil) {
5798 database_ = database;
5802 - (void) setPackage:(Package *)package {
5806 files_ = [NSMutableArray arrayWithCapacity:32];
5808 if (package != nil) {
5810 name_ = [package id];
5812 if (NSArray *files = [package files])
5813 [files_ addObjectsFromArray:files];
5815 if ([files_ count] != 0) {
5816 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5817 [files_ removeObjectAtIndex:0];
5818 [files_ sortUsingSelector:@selector(compareByPath:)];
5820 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5821 [stack addObject:@"/"];
5823 for (int i(0), e([files_ count]); i != e; ++i) {
5824 NSString *file = [files_ objectAtIndex:i];
5825 while (![file hasPrefix:[stack lastObject]])
5826 [stack removeLastObject];
5827 NSString *directory = [stack lastObject];
5828 [stack addObject:[file stringByAppendingString:@"/"]];
5829 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5830 ([stack count] - 2) * 3, "",
5831 [file substringFromIndex:[directory length]]
5840 - (void) reloadData {
5843 [self setPackage:[database_ packageWithName:name_]];
5848 /* Package Controller {{{ */
5849 @interface CYPackageController : CydiaWebViewController <
5850 UIActionSheetDelegate
5852 _transient Database *database_;
5853 _H<Package> package_;
5856 _H<NSMutableArray> buttons_;
5857 _H<UIBarButtonItem> button_;
5860 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5864 @implementation CYPackageController
5866 - (NSURL *) navigationURL {
5867 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5870 /* XXX: this is not safe at all... localization of /fail/ */
5871 - (void) _clickButtonWithName:(NSString *)name {
5872 if ([name isEqualToString:UCLocalize("CLEAR")])
5873 [delegate_ clearPackage:package_];
5874 else if ([name isEqualToString:UCLocalize("INSTALL")])
5875 [delegate_ installPackage:package_];
5876 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5877 [delegate_ installPackage:package_];
5878 else if ([name isEqualToString:UCLocalize("REMOVE")])
5879 [delegate_ removePackage:package_];
5880 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5881 [delegate_ installPackage:package_];
5882 else _assert(false);
5885 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5886 NSString *context([sheet context]);
5888 if ([context isEqualToString:@"modify"]) {
5889 if (button != [sheet cancelButtonIndex]) {
5890 NSString *buttonName = [buttons_ objectAtIndex:button];
5891 [self _clickButtonWithName:buttonName];
5894 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5898 - (bool) _allowJavaScriptPanel {
5903 - (void) _customButtonClicked {
5904 int count([buttons_ count]);
5909 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5911 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5912 [buttons addObjectsFromArray:buttons_];
5914 UIActionSheet *sheet = [[[UIActionSheet alloc]
5917 cancelButtonTitle:nil
5918 destructiveButtonTitle:nil
5919 otherButtonTitles:nil
5922 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5924 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5925 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5927 [sheet setContext:@"modify"];
5929 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5933 // We don't want to allow non-commercial packages to do custom things to the install button,
5934 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5935 - (void) customButtonClicked {
5937 [super customButtonClicked];
5939 [self _customButtonClicked];
5942 - (void) reloadButtonClicked {
5943 // Don't reload a commerical package by tapping the loading button,
5944 // but if it's not an Install button, we should forward it on.
5945 if (![package_ uninstalled])
5946 [self _customButtonClicked];
5949 - (void) applyLoadingTitle {
5950 // Don't show "Loading" as the title. Ever.
5953 - (UIBarButtonItem *) rightButton {
5958 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5959 if ((self = [super init]) != nil) {
5960 database_ = database;
5961 buttons_ = [NSMutableArray arrayWithCapacity:4];
5962 name_ = name == nil ? @"" : [NSString stringWithString:name];
5963 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5967 - (void) reloadData {
5970 package_ = [database_ packageWithName:name_];
5972 [buttons_ removeAllObjects];
5974 if (package_ != nil) {
5975 [(Package *) package_ parse];
5977 commercial_ = [package_ isCommercial];
5979 if ([package_ mode] != nil)
5980 [buttons_ addObject:UCLocalize("CLEAR")];
5981 if ([package_ source] == nil);
5982 else if ([package_ upgradableAndEssential:NO])
5983 [buttons_ addObject:UCLocalize("UPGRADE")];
5984 else if ([package_ uninstalled])
5985 [buttons_ addObject:UCLocalize("INSTALL")];
5987 [buttons_ addObject:UCLocalize("REINSTALL")];
5988 if (![package_ uninstalled])
5989 [buttons_ addObject:UCLocalize("REMOVE")];
5993 switch ([buttons_ count]) {
5994 case 0: title = nil; break;
5995 case 1: title = [buttons_ objectAtIndex:0]; break;
5996 default: title = UCLocalize("MODIFY"); break;
5999 button_ = [[[UIBarButtonItem alloc]
6001 style:UIBarButtonItemStylePlain
6003 action:@selector(customButtonClicked)
6007 - (bool) isLoading {
6008 return commercial_ ? [super isLoading] : false;
6014 /* Package List Controller {{{ */
6015 @interface PackageListController : CyteViewController <
6016 UITableViewDataSource,
6019 _transient Database *database_;
6021 _H<NSArray> packages_;
6022 _H<NSMutableArray> sections_;
6023 _H<UITableView, 2> list_;
6024 _H<NSMutableArray> index_;
6025 _H<NSMutableDictionary> indices_;
6026 _H<NSString> title_;
6027 unsigned reloading_;
6030 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6031 - (void) setDelegate:(id)delegate;
6032 - (void) resetCursor;
6037 @implementation PackageListController
6039 - (bool) isSummarized {
6043 - (bool) showsSections {
6047 - (void) deselectWithAnimation:(BOOL)animated {
6048 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6051 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6052 CGRect base = [[self view] bounds];
6053 base.size.height -= bounds.size.height;
6054 base.origin = [list_ frame].origin;
6056 [UIView beginAnimations:nil context:NULL];
6057 [UIView setAnimationBeginsFromCurrentState:YES];
6058 [UIView setAnimationCurve:curve];
6059 [UIView setAnimationDuration:duration];
6060 [list_ setFrame:base];
6061 [UIView commitAnimations];
6064 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6065 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6068 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6069 [self resizeForKeyboardBounds:bounds duration:0];
6072 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6073 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6074 *curve = UIViewAnimationCurveEaseInOut;
6076 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6078 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6081 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6084 - (void) keyboardWillShow:(NSNotification *)notification {
6087 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6088 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6090 NSTimeInterval duration;
6091 UIViewAnimationCurve curve;
6092 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6094 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);
6095 UIViewController *base = self;
6096 while ([base parentViewController] != nil)
6097 base = [base parentViewController];
6098 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6099 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6101 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6102 intersection.size.height += CYStatusBarHeight();
6104 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6107 - (void) keyboardWillHide:(NSNotification *)notification {
6108 NSTimeInterval duration;
6109 UIViewAnimationCurve curve;
6110 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6112 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6115 - (void) viewWillAppear:(BOOL)animated {
6116 [super viewWillAppear:animated];
6118 [self resizeForKeyboardBounds:CGRectZero];
6119 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6120 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6123 - (void) viewWillDisappear:(BOOL)animated {
6124 [super viewWillDisappear:animated];
6126 [self resizeForKeyboardBounds:CGRectZero];
6127 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6128 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6131 - (void) viewDidAppear:(BOOL)animated {
6132 [super viewDidAppear:animated];
6133 [self deselectWithAnimation:animated];
6136 - (void) didSelectPackage:(Package *)package {
6137 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6138 [view setDelegate:delegate_];
6139 [[self navigationController] pushViewController:view animated:YES];
6142 #if TryIndexedCollation
6143 + (BOOL) hasIndexedCollation {
6144 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6148 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6149 NSInteger count([sections_ count]);
6150 return count == 0 ? 1 : count;
6153 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6154 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6156 return [[sections_ objectAtIndex:section] name];
6159 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6160 if ([sections_ count] == 0)
6162 return [[sections_ objectAtIndex:section] count];
6165 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6166 @synchronized (database_) {
6167 if ([database_ era] != era_)
6170 Section *section([sections_ objectAtIndex:[path section]]);
6171 NSInteger row([path row]);
6172 Package *package([packages_ objectAtIndex:([section row] + row)]);
6173 return [[package retain] autorelease];
6176 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6177 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6179 cell = [[[PackageCell alloc] init] autorelease];
6181 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6182 [cell setPackage:package asSummary:[self isSummarized]];
6186 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6187 Package *package([self packageAtIndexPath:path]);
6188 package = [database_ packageWithName:[package id]];
6189 [self didSelectPackage:package];
6192 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6193 if (![self showsSections])
6199 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6200 #if TryIndexedCollation
6201 if ([[self class] hasIndexedCollation]) {
6202 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6209 - (void) updateHeight {
6210 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6213 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6214 if ((self = [super init]) != nil) {
6215 database_ = database;
6216 title_ = [title copy];
6217 [[self navigationItem] setTitle:title_];
6222 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6224 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6225 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6226 [[self view] addSubview:list_];
6228 // XXX: is 20 the most optimal number here?
6229 [list_ setSectionIndexMinimumDisplayRowCount:20];
6231 [(UITableView *) list_ setDataSource:self];
6232 [list_ setDelegate:self];
6234 [self updateHeight];
6237 - (void) releaseSubviews {
6245 [super releaseSubviews];
6248 - (void) setDelegate:(id)delegate {
6249 delegate_ = delegate;
6252 - (bool) shouldYield {
6256 - (bool) shouldBlock {
6260 - (NSMutableArray *) _reloadPackages {
6261 @synchronized (database_) {
6262 era_ = [database_ era];
6263 NSArray *packages([database_ packages]);
6265 return [NSMutableArray arrayWithArray:packages];
6268 - (void) _reloadData {
6269 if (reloading_ != 0) {
6276 if ([self shouldYield]) {
6280 if (![self shouldBlock])
6283 hud = [delegate_ addProgressHUD];
6284 [hud setText:UCLocalize("LOADING")];
6288 packages = [self yieldToSelector:@selector(_reloadPackages)];
6291 [delegate_ removeProgressHUD:hud];
6292 } while (reloading_ == 2);
6296 packages = [self _reloadPackages];
6299 packages_ = packages;
6301 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6302 sections_ = [NSMutableArray arrayWithCapacity:16];
6304 Section *section = nil;
6306 #if TryIndexedCollation
6307 if ([[self class] hasIndexedCollation]) {
6308 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6310 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6311 NSArray *titles = [collation sectionIndexTitles];
6314 _profile(PackageTable$reloadData$Section)
6315 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6319 _profile(PackageTable$reloadData$Section$Package)
6320 package = [packages_ objectAtIndex:offset];
6321 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6324 while (secidx < index) {
6327 _profile(PackageTable$reloadData$Section$Allocate)
6328 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6331 _profile(PackageTable$reloadData$Section$Add)
6332 [sections_ addObject:section];
6336 [section addToCount];
6342 index_ = [NSMutableArray arrayWithCapacity:32];
6344 bool sectioned([self showsSections]);
6346 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6347 [sections_ addObject:section];
6350 _profile(PackageTable$reloadData$Section)
6351 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6355 _profile(PackageTable$reloadData$Section$Package)
6356 package = [packages_ objectAtIndex:offset];
6357 index = [package index];
6360 if (sectioned && (section == nil || [section index] != index)) {
6361 _profile(PackageTable$reloadData$Section$Allocate)
6362 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6365 [index_ addObject:[section name]];
6366 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6368 _profile(PackageTable$reloadData$Section$Add)
6369 [sections_ addObject:section];
6373 [section addToCount];
6378 [self updateHeight];
6380 _profile(PackageTable$reloadData$List)
6381 [(UITableView *) list_ setDataSource:self];
6386 - (void) reloadData {
6389 if ([self shouldYield])
6390 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6395 - (void) resetCursor {
6396 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6399 - (void) clearData {
6400 [self updateHeight];
6402 [list_ setDataSource:nil];
6410 /* Filtered Package List Controller {{{ */
6411 @interface FilteredPackageListController : PackageListController {
6414 _H<NSObject> object_;
6417 - (void) setObject:(id)object;
6418 - (void) setObject:(id)object forFilter:(SEL)filter;
6421 - (void) setFilter:(SEL)filter;
6423 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6427 @implementation FilteredPackageListController
6433 - (void) setFilter:(SEL)filter {
6434 @synchronized (self) {
6437 /* XXX: this is an unsafe optimization of doomy hell */
6438 Method method(class_getInstanceMethod([Package class], filter));
6439 _assert(method != NULL);
6440 imp_ = method_getImplementation(method);
6441 _assert(imp_ != NULL);
6444 - (void) setObject:(id)object {
6445 @synchronized (self) {
6449 - (void) setObject:(id)object forFilter:(SEL)filter {
6450 @synchronized (self) {
6451 [self setFilter:filter];
6452 [self setObject:object];
6455 - (NSMutableArray *) _reloadPackages {
6456 @synchronized (database_) {
6457 era_ = [database_ era];
6458 NSArray *packages([database_ packages]);
6460 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6464 _H<NSObject> object;
6466 @synchronized (self) {
6472 _profile(PackageTable$reloadData$Filter)
6473 for (Package *package in packages)
6474 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6475 [filtered addObject:package];
6481 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6482 if ((self = [super initWithDatabase:database title:title]) != nil) {
6483 [self setFilter:filter];
6484 [self setObject:object];
6491 /* Home Controller {{{ */
6492 @interface HomeController : CydiaWebViewController {
6497 @implementation HomeController
6500 if ((self = [super init]) != nil) {
6501 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6506 - (NSURL *) navigationURL {
6507 return [NSURL URLWithString:@"cydia://home"];
6510 - (void) didReceiveMemoryWarning {
6513 - (void) aboutButtonClicked {
6514 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6516 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6517 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6518 [alert setCancelButtonIndex:0];
6521 @"Copyright \u00a9 2008-2011\n"
6524 "Jay Freeman (saurik)\n"
6525 "saurik@saurik.com\n"
6526 "http://www.saurik.com/"
6532 - (UIBarButtonItem *) leftButton {
6533 return [[[UIBarButtonItem alloc]
6534 initWithTitle:UCLocalize("ABOUT")
6535 style:UIBarButtonItemStylePlain
6537 action:@selector(aboutButtonClicked)
6543 /* Manage Controller {{{ */
6544 @interface ManageController : CydiaWebViewController {
6547 - (void) queueStatusDidChange;
6551 @implementation ManageController
6554 if ((self = [super init]) != nil) {
6555 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6559 - (NSURL *) navigationURL {
6560 return [NSURL URLWithString:@"cydia://manage"];
6563 - (UIBarButtonItem *) leftButton {
6564 return [[[UIBarButtonItem alloc]
6565 initWithTitle:UCLocalize("SETTINGS")
6566 style:UIBarButtonItemStylePlain
6568 action:@selector(settingsButtonClicked)
6572 - (void) settingsButtonClicked {
6573 [delegate_ showSettings];
6576 - (void) queueButtonClicked {
6580 - (UIBarButtonItem *) customButton {
6581 return Queuing_ ? [[[UIBarButtonItem alloc]
6582 initWithTitle:UCLocalize("QUEUE")
6583 style:UIBarButtonItemStyleDone
6585 action:@selector(queueButtonClicked)
6586 ] autorelease] : [super customButton];
6589 - (void) queueStatusDidChange {
6590 [self applyRightButton];
6593 - (bool) isLoading {
6594 return !Queuing_ && [super isLoading];
6600 /* Refresh Bar {{{ */
6601 @interface RefreshBar : UINavigationBar {
6602 _H<UIProgressIndicator> indicator_;
6603 _H<UITextLabel> prompt_;
6604 _H<UIProgressBar> progress_;
6605 _H<UINavigationButton> cancel_;
6610 @implementation RefreshBar
6612 - (void) positionViews {
6613 CGRect frame = [cancel_ frame];
6614 frame.size = [cancel_ sizeThatFits:frame.size];
6615 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6616 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6617 [cancel_ setFrame:frame];
6619 CGSize prgsize = {75, 100};
6621 [self frame].size.width - prgsize.width - 10,
6622 ([self frame].size.height - prgsize.height) / 2
6624 [progress_ setFrame:prgrect];
6626 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6627 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6628 CGRect indrect = {{indoffset, indoffset}, indsize};
6629 [indicator_ setFrame:indrect];
6631 CGSize prmsize = {215, indsize.height + 4};
6633 indoffset * 2 + indsize.width,
6634 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6636 [prompt_ setFrame:prmrect];
6639 - (void) setFrame:(CGRect)frame {
6640 [super setFrame:frame];
6641 [self positionViews];
6644 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6645 if ((self = [super initWithFrame:frame]) != nil) {
6646 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6648 [self setBarStyle:UIBarStyleBlack];
6650 UIBarStyle barstyle([self _barStyle:NO]);
6651 bool ugly(barstyle == UIBarStyleDefault);
6653 UIProgressIndicatorStyle style = ugly ?
6654 UIProgressIndicatorStyleMediumBrown :
6655 UIProgressIndicatorStyleMediumWhite;
6657 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6658 [(UIProgressIndicator *) indicator_ setStyle:style];
6659 [indicator_ startAnimation];
6660 [self addSubview:indicator_];
6662 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6663 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6664 [prompt_ setBackgroundColor:[UIColor clearColor]];
6665 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6666 [self addSubview:prompt_];
6668 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6669 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6670 [(UIProgressBar *) progress_ setStyle:0];
6671 [self addSubview:progress_];
6673 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6674 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6675 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6676 [cancel_ setBarStyle:barstyle];
6678 [self positionViews];
6682 - (void) setCancellable:(bool)cancellable {
6684 [self addSubview:cancel_];
6686 [cancel_ removeFromSuperview];
6690 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6691 [progress_ setProgress:0];
6695 [self setCancellable:NO];
6698 - (void) setPrompt:(NSString *)prompt {
6699 [prompt_ setText:prompt];
6702 - (void) setProgress:(float)progress {
6703 [progress_ setProgress:progress];
6709 /* Cydia Navigation Controller Interface {{{ */
6710 @interface UINavigationController (Cydia)
6712 - (NSArray *) navigationURLCollection;
6713 - (void) unloadData;
6718 /* Cydia Tab Bar Controller {{{ */
6719 @interface CYTabBarController : UITabBarController <
6720 UITabBarControllerDelegate,
6723 _transient Database *database_;
6724 _H<RefreshBar, 1> refreshbar_;
6728 // XXX: ok, "updatedelegate_"?...
6729 _transient NSObject<CydiaDelegate> *updatedelegate_;
6731 _H<UIViewController> remembered_;
6732 _transient UIViewController *transient_;
6735 - (NSArray *) navigationURLCollection;
6736 - (void) dropBar:(BOOL)animated;
6737 - (void) beginUpdate;
6738 - (void) raiseBar:(BOOL)animated;
6740 - (void) unloadData;
6744 @implementation CYTabBarController
6746 - (void) setUnselectedViewController:(UIViewController *)transient {
6747 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6748 if (transient != nil) {
6749 if (transient_ == nil)
6750 remembered_ = [controllers objectAtIndex:0];
6751 transient_ = transient;
6752 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6753 [controllers replaceObjectAtIndex:0 withObject:transient_];
6754 [self setSelectedIndex:0];
6755 [self setViewControllers:controllers];
6756 [self concealTabBarSelection];
6757 } else if (remembered_ != nil) {
6758 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6759 transient_ = transient;
6760 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6762 [self setViewControllers:controllers];
6763 [self revealTabBarSelection];
6767 - (UIViewController *) unselectedViewController {
6771 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6772 if ([self unselectedViewController])
6773 [self setUnselectedViewController:nil];
6776 - (NSArray *) navigationURLCollection {
6777 NSMutableArray *items([NSMutableArray array]);
6779 // XXX: Should this deal with transient view controllers?
6780 for (id navigation in [self viewControllers]) {
6781 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6783 [items addObject:stack];
6789 - (void) unloadData {
6792 for (UINavigationController *controller in [self viewControllers])
6793 [controller unloadData];
6795 if (UIViewController *selected = [self selectedViewController])
6796 [selected reloadData];
6798 if (UIViewController *unselected = [self unselectedViewController]) {
6799 [unselected unloadData];
6800 [unselected reloadData];
6805 [[NSNotificationCenter defaultCenter] removeObserver:self];
6810 - (id) initWithDatabase:(Database *)database {
6811 if ((self = [super init]) != nil) {
6812 database_ = database;
6813 [self setDelegate:self];
6815 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6816 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6818 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6822 - (void) setUpdate:(NSDate *)date {
6826 - (void) beginUpdate {
6827 [(RefreshBar *) refreshbar_ start];
6830 [updatedelegate_ retainNetworkActivityIndicator];
6834 detachNewThreadSelector:@selector(performUpdate)
6840 - (void) performUpdate {
6841 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6844 status.setDelegate(self);
6845 [database_ updateWithStatus:status];
6848 performSelectorOnMainThread:@selector(completeUpdate)
6856 - (void) stopUpdateWithSelector:(SEL)selector {
6858 [updatedelegate_ releaseNetworkActivityIndicator];
6860 [self raiseBar:YES];
6863 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6866 - (void) completeUpdate {
6869 [self stopUpdateWithSelector:@selector(reloadData)];
6872 - (void) cancelUpdate {
6873 [self stopUpdateWithSelector:@selector(updateData)];
6876 - (void) cancelPressed {
6877 [self cancelUpdate];
6884 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6885 [refreshbar_ setPrompt:[event compoundMessage]];
6888 - (bool) isProgressCancelled {
6892 - (void) setProgressCancellable:(NSNumber *)cancellable {
6893 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6896 - (void) setProgressPercent:(NSNumber *)percent {
6897 [refreshbar_ setProgress:[percent floatValue]];
6900 - (void) setProgressStatus:(NSDictionary *)status {
6902 [self setProgressPercent:[status objectForKey:@"Percent"]];
6905 - (void) setUpdateDelegate:(id)delegate {
6906 updatedelegate_ = delegate;
6909 - (UIView *) transitionView {
6910 if ([self respondsToSelector:@selector(_transitionView)])
6911 return [self _transitionView];
6913 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6916 - (void) dropBar:(BOOL)animated {
6921 UIView *transition([self transitionView]);
6922 [[self view] addSubview:refreshbar_];
6924 CGRect barframe([refreshbar_ frame]);
6926 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6927 barframe.origin.y = CYStatusBarHeight();
6929 barframe.origin.y = 0;
6931 [refreshbar_ setFrame:barframe];
6934 [UIView beginAnimations:nil context:NULL];
6936 CGRect viewframe = [transition frame];
6937 viewframe.origin.y += barframe.size.height;
6938 viewframe.size.height -= barframe.size.height;
6939 [transition setFrame:viewframe];
6942 [UIView commitAnimations];
6944 // Ensure bar has the proper width for our view, it might have changed
6945 barframe.size.width = viewframe.size.width;
6946 [refreshbar_ setFrame:barframe];
6949 - (void) raiseBar:(BOOL)animated {
6954 UIView *transition([self transitionView]);
6955 [refreshbar_ removeFromSuperview];
6957 CGRect barframe([refreshbar_ frame]);
6960 [UIView beginAnimations:nil context:NULL];
6962 CGRect viewframe = [transition frame];
6963 viewframe.origin.y -= barframe.size.height;
6964 viewframe.size.height += barframe.size.height;
6965 [transition setFrame:viewframe];
6968 [UIView commitAnimations];
6971 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6972 bool dropped(dropped_);
6977 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6983 - (void) statusBarFrameChanged:(NSNotification *)notification {
6993 /* Cydia Navigation Controller Implementation {{{ */
6994 @implementation UINavigationController (Cydia)
6996 - (NSArray *) navigationURLCollection {
6997 NSMutableArray *stack([NSMutableArray array]);
6999 for (CyteViewController *controller in [self viewControllers]) {
7000 NSString *url = [[controller navigationURL] absoluteString];
7002 [stack addObject:url];
7008 - (void) reloadData {
7011 UIViewController *visible([self visibleViewController]);
7013 [visible reloadData];
7015 // on the iPad, this view controller is ALSO visible. :(
7017 if (UIViewController *top = [self topViewController])
7022 - (void) unloadData {
7023 for (CyteViewController *page in [self viewControllers])
7032 /* Cydia:// Protocol {{{ */
7033 @interface CydiaURLProtocol : NSURLProtocol {
7038 @implementation CydiaURLProtocol
7040 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7041 NSURL *url([request URL]);
7045 NSString *scheme([[url scheme] lowercaseString]);
7046 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7048 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7054 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7058 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7059 id<NSURLProtocolClient> client([self client]);
7061 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7063 NSData *data(UIImagePNGRepresentation(icon));
7065 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7066 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7067 [client URLProtocol:self didLoadData:data];
7068 [client URLProtocolDidFinishLoading:self];
7072 - (void) startLoading {
7073 id<NSURLProtocolClient> client([self client]);
7074 NSURLRequest *request([self request]);
7076 NSURL *url([request URL]);
7077 NSString *href([url absoluteString]);
7078 NSString *scheme([[url scheme] lowercaseString]);
7082 if ([scheme isEqualToString:@"cydia"])
7083 path = [href substringFromIndex:8];
7084 else if ([scheme isEqualToString:@"about"])
7085 path = [href substringFromIndex:12];
7086 else _assert(false);
7088 NSRange slash([path rangeOfString:@"/"]);
7091 if (slash.location == NSNotFound) {
7095 command = [path substringToIndex:slash.location];
7096 path = [path substringFromIndex:(slash.location + 1)];
7099 Database *database([Database sharedInstance]);
7101 if ([command isEqualToString:@"package-icon"]) {
7104 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7105 Package *package([database packageWithName:path]);
7109 UIImage *icon([package icon]);
7110 [self _returnPNGWithImage:icon forRequest:request];
7111 } else if ([command isEqualToString:@"source-icon"]) {
7114 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7115 NSString *source(Simplify(path));
7116 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7118 icon = [UIImage applicationImageNamed:@"unknown.png"];
7119 [self _returnPNGWithImage:icon forRequest:request];
7120 } else if ([command isEqualToString:@"uikit-image"]) {
7123 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7124 UIImage *icon(_UIImageWithName(path));
7125 [self _returnPNGWithImage:icon forRequest:request];
7126 } else if ([command isEqualToString:@"section-icon"]) {
7129 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7130 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7132 icon = [UIImage applicationImageNamed:@"unknown.png"];
7133 [self _returnPNGWithImage:icon forRequest:request];
7135 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7139 - (void) stopLoading {
7145 /* Section Controller {{{ */
7146 @interface SectionController : FilteredPackageListController {
7147 _H<NSString> section_;
7150 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7154 @implementation SectionController
7156 - (NSURL *) navigationURL {
7157 NSString *name = section_;
7161 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7164 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7167 title = UCLocalize("ALL_PACKAGES");
7168 else if (![name isEqual:@""])
7169 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7171 title = UCLocalize("NO_SECTION");
7173 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7180 /* Sections Controller {{{ */
7181 @interface SectionsController : CyteViewController <
7182 UITableViewDataSource,
7185 _transient Database *database_;
7186 _H<NSMutableArray> sections_;
7187 _H<NSMutableArray> filtered_;
7188 _H<UITableView, 2> list_;
7191 - (id) initWithDatabase:(Database *)database;
7192 - (void) editButtonClicked;
7196 @implementation SectionsController
7198 - (NSURL *) navigationURL {
7199 return [NSURL URLWithString:@"cydia://sections"];
7202 - (void) updateNavigationItem {
7203 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7204 if ([sections_ count] == 0) {
7205 [[self navigationItem] setRightBarButtonItem:nil];
7207 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7208 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7210 action:@selector(editButtonClicked)
7211 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7215 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7216 [super setEditing:editing animated:animated];
7221 [delegate_ updateData];
7223 [self updateNavigationItem];
7226 - (void) viewDidAppear:(BOOL)animated {
7227 [super viewDidAppear:animated];
7228 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7231 - (void) viewWillDisappear:(BOOL)animated {
7232 [super viewWillDisappear:animated];
7233 if ([self isEditing]) [self setEditing:NO];
7236 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7237 Section *section = nil;
7238 int index = [indexPath row];
7239 if (![self isEditing]) {
7242 section = [filtered_ objectAtIndex:index];
7244 section = [sections_ objectAtIndex:index];
7249 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7250 if ([self isEditing])
7251 return [sections_ count];
7253 return [filtered_ count] + 1;
7256 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7260 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7261 static NSString *reuseIdentifier = @"SectionCell";
7263 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7265 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7267 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7272 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7273 if ([self isEditing])
7276 Section *section = [self sectionAtIndexPath:indexPath];
7278 SectionController *controller = [[[SectionController alloc]
7279 initWithDatabase:database_
7280 section:[section name]
7282 [controller setDelegate:delegate_];
7284 [[self navigationController] pushViewController:controller animated:YES];
7288 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7290 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7291 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7292 [list_ setRowHeight:45.0f];
7293 [(UITableView *) list_ setDataSource:self];
7294 [list_ setDelegate:self];
7295 [[self view] addSubview:list_];
7298 - (void) viewDidLoad {
7299 [super viewDidLoad];
7301 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7304 - (void) releaseSubviews {
7310 [super releaseSubviews];
7313 - (id) initWithDatabase:(Database *)database {
7314 if ((self = [super init]) != nil) {
7315 database_ = database;
7319 - (void) reloadData {
7322 NSArray *packages = [database_ packages];
7324 sections_ = [NSMutableArray arrayWithCapacity:16];
7325 filtered_ = [NSMutableArray arrayWithCapacity:16];
7327 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7330 for (Package *package in packages) {
7331 NSString *name([package section]);
7332 NSString *key(name == nil ? @"" : name);
7336 _profile(SectionsView$reloadData$Section)
7337 section = [sections objectForKey:key];
7338 if (section == nil) {
7339 _profile(SectionsView$reloadData$Section$Allocate)
7340 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7341 [sections setObject:section forKey:key];
7346 [section addToCount];
7348 _profile(SectionsView$reloadData$Filter)
7349 if (![package valid] || ![package visible])
7357 [sections_ addObjectsFromArray:[sections allValues]];
7359 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7361 for (Section *section in (id) sections_) {
7362 size_t count([section row]);
7366 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7367 [section setCount:count];
7368 [filtered_ addObject:section];
7371 [self updateNavigationItem];
7376 - (void) editButtonClicked {
7377 [self setEditing:![self isEditing] animated:YES];
7383 /* Changes Controller {{{ */
7384 @interface ChangesController : CyteViewController <
7385 UITableViewDataSource,
7388 _transient Database *database_;
7390 _H<NSArray> packages_;
7391 _H<NSMutableArray> sections_;
7392 _H<UITableView, 2> list_;
7396 - (id) initWithDatabase:(Database *)database;
7400 @implementation ChangesController
7402 - (NSURL *) navigationURL {
7403 return [NSURL URLWithString:@"cydia://changes"];
7406 - (void) viewDidAppear:(BOOL)animated {
7407 [super viewDidAppear:animated];
7408 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7411 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7412 NSInteger count([sections_ count]);
7413 return count == 0 ? 1 : count;
7416 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7417 if ([sections_ count] == 0)
7419 return [[sections_ objectAtIndex:section] name];
7422 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7423 if ([sections_ count] == 0)
7425 return [[sections_ objectAtIndex:section] count];
7428 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7429 @synchronized (database_) {
7430 if ([database_ era] != era_)
7433 NSUInteger sectionIndex([path section]);
7434 if (sectionIndex >= [sections_ count])
7436 Section *section([sections_ objectAtIndex:sectionIndex]);
7437 NSInteger row([path row]);
7438 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7441 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7442 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7444 cell = [[[PackageCell alloc] init] autorelease];
7446 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7447 [cell setPackage:package asSummary:false];
7451 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7452 Package *package([self packageAtIndexPath:path]);
7453 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7454 [view setDelegate:delegate_];
7455 [[self navigationController] pushViewController:view animated:YES];
7459 - (void) refreshButtonClicked {
7460 [delegate_ beginUpdate];
7461 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7464 - (void) upgradeButtonClicked {
7465 [delegate_ distUpgrade];
7466 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7470 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7472 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7473 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7474 [list_ setRowHeight:73];
7475 [(UITableView *) list_ setDataSource:self];
7476 [list_ setDelegate:self];
7477 [[self view] addSubview:list_];
7480 - (void) viewDidLoad {
7481 [super viewDidLoad];
7483 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7486 - (void) releaseSubviews {
7492 [super releaseSubviews];
7495 - (id) initWithDatabase:(Database *)database {
7496 if ((self = [super init]) != nil) {
7497 database_ = database;
7501 - (NSMutableArray *) _reloadPackages {
7502 @synchronized (database_) {
7503 era_ = [database_ era];
7504 NSArray *packages([database_ packages]);
7506 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7509 _profile(ChangesController$_reloadPackages$Filter)
7510 for (Package *package in packages)
7511 if ([package upgradableAndEssential:YES] || [package visible])
7512 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7515 _profile(ChangesController$_reloadPackages$radixSort)
7516 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7523 - (void) _reloadData {
7528 UIProgressHUD *hud([delegate_ addProgressHUD]);
7529 [hud setText:UCLocalize("LOADING")];
7530 //NSLog(@"HUD:%@::%@", delegate_, hud);
7531 packages = [self yieldToSelector:@selector(_reloadPackages)];
7532 [delegate_ removeProgressHUD:hud];
7534 packages = [self _reloadPackages];
7537 @synchronized (database_) {
7538 if (era_ != [database_ era])
7541 packages_ = packages;
7542 sections_ = [NSMutableArray arrayWithCapacity:16];
7544 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7545 Section *ignored = nil;
7546 Section *section = nil;
7550 bool unseens = false;
7552 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7554 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7555 Package *package = [packages_ objectAtIndex:offset];
7557 BOOL uae = [package upgradableAndEssential:YES];
7561 time_t seen([package seen]);
7563 if (section == nil || last != seen) {
7567 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7570 _profile(ChangesController$reloadData$Allocate)
7571 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7572 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7573 [sections_ addObject:section];
7577 [section addToCount];
7578 } else if ([package ignored]) {
7579 if (ignored == nil) {
7580 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7582 [ignored addToCount];
7585 [upgradable addToCount];
7590 CFRelease(formatter);
7593 Section *last = [sections_ lastObject];
7594 size_t count = [last count];
7595 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7596 [sections_ removeLastObject];
7599 if ([ignored count] != 0)
7600 [sections_ insertObject:ignored atIndex:0];
7602 [sections_ insertObject:upgradable atIndex:0];
7606 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7607 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7608 style:UIBarButtonItemStylePlain
7610 action:@selector(upgradeButtonClicked)
7611 ] autorelease]) animated:YES];
7613 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7614 initWithTitle:UCLocalize("REFRESH")
7615 style:UIBarButtonItemStylePlain
7617 action:@selector(refreshButtonClicked)
7618 ] autorelease]) animated:YES];
7623 - (void) reloadData {
7625 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7630 /* Search Controller {{{ */
7631 @interface SearchController : FilteredPackageListController <
7634 _H<UISearchBar, 1> search_;
7638 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7639 - (void) reloadData;
7643 @implementation SearchController
7645 - (NSURL *) navigationURL {
7646 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7647 return [NSURL URLWithString:@"cydia://search"];
7649 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7652 - (void) useSearch {
7653 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7658 - (void) viewWillAppear:(BOOL)animated {
7659 [super viewWillAppear:animated];
7661 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7665 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7666 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7671 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7672 [search_ resignFirstResponder];
7676 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7677 [search_ setText:@""];
7678 [self searchBarButtonClicked:searchBar];
7681 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7682 [self searchBarButtonClicked:searchBar];
7685 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7686 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7690 - (bool) shouldYield {
7694 - (bool) shouldBlock {
7695 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7698 - (bool) isSummarized {
7699 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7702 - (bool) showsSections {
7706 - (NSMutableArray *) _reloadPackages {
7707 NSMutableArray *packages([super _reloadPackages]);
7708 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7709 [packages radixSortUsingSelector:@selector(rank)];
7713 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7714 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7715 search_ = [[[UISearchBar alloc] init] autorelease];
7716 [search_ setDelegate:self];
7719 [search_ setText:query];
7723 - (void) viewDidAppear:(BOOL)animated {
7724 [super viewDidAppear:animated];
7726 if (!searchloaded_) {
7727 searchloaded_ = YES;
7728 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7729 [search_ layoutSubviews];
7730 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7732 UITextField *textField;
7733 if ([search_ respondsToSelector:@selector(searchField)])
7734 textField = [search_ searchField];
7736 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7738 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7739 [textField setEnablesReturnKeyAutomatically:NO];
7740 [[self navigationItem] setTitleView:textField];
7744 - (void) reloadData {
7745 id object([search_ text]);
7746 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7747 object = [object componentsSeparatedByString:@" "];
7749 [self setObject:object];
7755 - (void) didSelectPackage:(Package *)package {
7756 [search_ resignFirstResponder];
7757 [super didSelectPackage:package];
7762 /* Package Settings Controller {{{ */
7763 @interface PackageSettingsController : CyteViewController <
7764 UITableViewDataSource,
7767 _transient Database *database_;
7769 _H<Package> package_;
7770 _H<UITableView, 2> table_;
7771 _H<UISwitch> subscribedSwitch_;
7772 _H<UISwitch> ignoredSwitch_;
7773 _H<UITableViewCell> subscribedCell_;
7774 _H<UITableViewCell> ignoredCell_;
7777 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7781 @implementation PackageSettingsController
7783 - (NSURL *) navigationURL {
7784 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7787 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7788 if (package_ == nil)
7791 if ([package_ installed] == nil)
7797 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7798 if (package_ == nil)
7801 // both sections contain just one item right now.
7805 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7809 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7811 return UCLocalize("SHOW_ALL_CHANGES_EX");
7813 return UCLocalize("IGNORE_UPGRADES_EX");
7816 - (void) onSubscribed:(id)control {
7817 bool value([control isOn]);
7818 if (package_ == nil)
7820 if ([package_ setSubscribed:value])
7821 [delegate_ updateData];
7824 - (void) _updateIgnored {
7825 const char *package([name_ UTF8String]);
7826 bool on([ignoredSwitch_ isOn]);
7828 pid_t pid(ExecFork());
7830 FILE *dpkg(popen("dpkg --set-selections", "w"));
7831 fwrite(package, strlen(package), 1, dpkg);
7834 fwrite(" hold\n", 6, 1, dpkg);
7836 fwrite(" install\n", 9, 1, dpkg);
7846 int result(waitpid(pid, &status, 0));
7849 _assert(result == pid);
7855 - (void) onIgnored:(id)control {
7856 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7857 [invocation setTarget:self];
7858 [invocation setSelector:@selector(_updateIgnored)];
7860 [delegate_ reloadDataWithInvocation:invocation];
7863 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7864 if (package_ == nil)
7867 switch ([indexPath section]) {
7868 case 0: return subscribedCell_;
7869 case 1: return ignoredCell_;
7878 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7880 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7881 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7882 [(UITableView *) table_ setDataSource:self];
7883 [table_ setDelegate:self];
7884 [[self view] addSubview:table_];
7886 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7887 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7888 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7890 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7891 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7892 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7894 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7895 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7896 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7897 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7899 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7900 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7901 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7902 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7905 - (void) viewDidLoad {
7906 [super viewDidLoad];
7908 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7911 - (void) releaseSubviews {
7913 subscribedCell_ = nil;
7915 ignoredSwitch_ = nil;
7916 subscribedSwitch_ = nil;
7918 [super releaseSubviews];
7921 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7922 if ((self = [super init]) != nil) {
7923 database_ = database;
7928 - (void) reloadData {
7931 package_ = [database_ packageWithName:name_];
7933 if (package_ != nil) {
7934 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7935 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7936 } // XXX: what now, G?
7938 [table_ reloadData];
7944 /* Installed Controller {{{ */
7945 @interface InstalledController : FilteredPackageListController {
7949 - (id) initWithDatabase:(Database *)database;
7951 - (void) updateRoleButton;
7952 - (void) queueStatusDidChange;
7956 @implementation InstalledController
7958 - (NSURL *) navigationURL {
7959 return [NSURL URLWithString:@"cydia://installed"];
7962 - (id) initWithDatabase:(Database *)database {
7963 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7964 [self updateRoleButton];
7965 [self queueStatusDidChange];
7970 - (void) queueButtonClicked {
7975 - (void) queueStatusDidChange {
7979 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7980 initWithTitle:UCLocalize("QUEUE")
7981 style:UIBarButtonItemStyleDone
7983 action:@selector(queueButtonClicked)
7986 [[self navigationItem] setLeftBarButtonItem:nil];
7992 - (void) updateRoleButton {
7993 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7994 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7995 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7996 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7998 action:@selector(roleButtonClicked)
8002 - (void) roleButtonClicked {
8003 [self setObject:[NSNumber numberWithBool:expert_]];
8007 [self updateRoleButton];
8013 /* Source Cell {{{ */
8014 @interface SourceCell : CyteTableViewCell <
8015 CyteTableViewCellDelegate
8018 _H<NSString> origin_;
8019 _H<NSString> label_;
8022 - (void) setSource:(Source *)source;
8026 @implementation SourceCell
8028 - (void) _setImage:(UIImage *)image {
8030 [content_ setNeedsDisplay];
8033 - (void) _setSource:(Source *)source {
8034 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8036 if (NSString *base = [source base])
8037 if ([base length] != 0) {
8038 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
8040 if (NSData *data = [NSURLConnection
8041 sendSynchronousRequest:[NSURLRequest
8043 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8047 returningResponse:NULL
8050 if (UIImage *image = [UIImage imageWithData:data])
8051 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
8057 - (void) setSource:(Source *)source {
8058 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8060 origin_ = [source name];
8061 label_ = [source uri];
8063 [content_ setNeedsDisplay];
8065 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
8068 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8069 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8070 UIView *content([self contentView]);
8071 CGRect bounds([content bounds]);
8073 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8074 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8075 [content_ setBackgroundColor:[UIColor whiteColor]];
8076 [content addSubview:content_];
8078 [content_ setDelegate:self];
8079 [content_ setOpaque:YES];
8081 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8085 - (NSString *) accessibilityLabel {
8089 - (void) drawContentRect:(CGRect)rect {
8090 bool highlighted(highlighted_);
8091 float width(rect.size.width);
8094 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8101 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 60) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8105 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 75) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8110 /* Source Controller {{{ */
8111 @interface SourceController : FilteredPackageListController {
8112 _transient Source *source_;
8116 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8120 @implementation SourceController
8122 - (NSURL *) navigationURL {
8123 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8126 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8127 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8129 key_ = [source key];
8133 - (void) reloadData {
8134 source_ = [database_ sourceWithKey:key_];
8135 key_ = [source_ key];
8136 [self setObject:source_];
8138 [[self navigationItem] setTitle:[source_ label]];
8145 /* Sources Controller {{{ */
8146 @interface SourcesController : CyteViewController <
8147 UITableViewDataSource,
8150 _transient Database *database_;
8151 _H<UITableView, 2> list_;
8152 _H<NSMutableArray> sources_;
8156 _H<UIProgressHUD> hud_;
8159 //NSURLConnection *installer_;
8160 NSURLConnection *trivial_;
8161 NSURLConnection *trivial_bz2_;
8162 NSURLConnection *trivial_gz_;
8163 //NSURLConnection *automatic_;
8168 - (id) initWithDatabase:(Database *)database;
8169 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8173 @implementation SourcesController
8175 - (void) _releaseConnection:(NSURLConnection *)connection {
8176 if (connection != nil) {
8177 [connection cancel];
8178 //[connection setDelegate:nil];
8179 [connection release];
8184 //[self _releaseConnection:installer_];
8185 [self _releaseConnection:trivial_];
8186 [self _releaseConnection:trivial_gz_];
8187 [self _releaseConnection:trivial_bz2_];
8188 //[self _releaseConnection:automatic_];
8193 - (NSURL *) navigationURL {
8194 return [NSURL URLWithString:@"cydia://sources"];
8197 - (void) viewDidAppear:(BOOL)animated {
8198 [super viewDidAppear:animated];
8199 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8202 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8206 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8210 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8211 return [sources_ count];
8214 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8215 return [sources_ objectAtIndex:[indexPath row]];
8218 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8219 static NSString *cellIdentifier = @"SourceCell";
8221 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8222 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8223 [cell setSource:[self sourceAtIndexPath:indexPath]];
8224 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8229 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8230 Source *source = [self sourceAtIndexPath:indexPath];
8232 SourceController *controller = [[[SourceController alloc]
8233 initWithDatabase:database_
8237 [controller setDelegate:delegate_];
8239 [[self navigationController] pushViewController:controller animated:YES];
8242 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8243 Source *source = [self sourceAtIndexPath:indexPath];
8244 return [source record] != nil;
8247 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8248 if (editingStyle == UITableViewCellEditingStyleDelete) {
8249 Source *source = [self sourceAtIndexPath:indexPath];
8250 [Sources_ removeObjectForKey:[source key]];
8251 [delegate_ syncData];
8256 [delegate_ addTrivialSource:href_];
8257 [delegate_ syncData];
8260 - (NSString *) getWarning {
8261 NSString *href(href_);
8262 NSRange colon([href rangeOfString:@"://"]);
8263 if (colon.location != NSNotFound)
8264 href = [href substringFromIndex:(colon.location + 3)];
8265 href = [href stringByAddingPercentEscapes];
8266 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8267 href = [href stringByCachingURLWithCurrentCDN];
8269 NSURL *url([NSURL URLWithString:href]);
8271 NSStringEncoding encoding;
8272 NSError *error(nil);
8274 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8275 return [warning length] == 0 ? nil : warning;
8279 - (void) _endConnection:(NSURLConnection *)connection {
8280 // XXX: the memory management in this method is horribly awkward
8282 NSURLConnection **field = NULL;
8283 if (connection == trivial_)
8285 else if (connection == trivial_bz2_)
8286 field = &trivial_bz2_;
8287 else if (connection == trivial_gz_)
8288 field = &trivial_gz_;
8289 _assert(field != NULL);
8290 [connection release];
8295 trivial_bz2_ == nil &&
8298 [delegate_ releaseNetworkActivityIndicator];
8300 [delegate_ removeProgressHUD:hud_];
8306 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8309 UIAlertView *alert = [[[UIAlertView alloc]
8310 initWithTitle:UCLocalize("SOURCE_WARNING")
8313 cancelButtonTitle:UCLocalize("CANCEL")
8315 UCLocalize("ADD_ANYWAY"),
8319 [alert setContext:@"warning"];
8320 [alert setNumberOfRows:1];
8324 } else if (error_ != nil) {
8325 UIAlertView *alert = [[[UIAlertView alloc]
8326 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8327 message:[error_ localizedDescription]
8329 cancelButtonTitle:UCLocalize("OK")
8330 otherButtonTitles:nil
8333 [alert setContext:@"urlerror"];
8336 UIAlertView *alert = [[[UIAlertView alloc]
8337 initWithTitle:UCLocalize("NOT_REPOSITORY")
8338 message:UCLocalize("NOT_REPOSITORY_EX")
8340 cancelButtonTitle:UCLocalize("OK")
8341 otherButtonTitles:nil
8344 [alert setContext:@"trivial"];
8353 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8354 switch ([response statusCode]) {
8360 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8361 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8363 [self _endConnection:connection];
8366 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8367 [self _endConnection:connection];
8370 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8371 NSURL *url([NSURL URLWithString:href]);
8373 NSMutableURLRequest *request = [NSMutableURLRequest
8375 cachePolicy:NSURLRequestUseProtocolCachePolicy
8376 timeoutInterval:120.0
8379 [request setHTTPMethod:method];
8381 if (Machine_ != NULL)
8382 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8384 if ([url isCydiaSecure]) {
8385 if (UniqueID_ != nil)
8386 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8389 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8392 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8393 NSString *context([alert context]);
8395 if ([context isEqualToString:@"source"]) {
8398 NSString *href = [[alert textField] text];
8400 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8402 if (![href hasSuffix:@"/"])
8403 href_ = [href stringByAppendingString:@"/"];
8407 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8408 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8409 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8410 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8414 // XXX: this is stupid
8415 hud_ = [delegate_ addProgressHUD];
8416 [hud_ setText:UCLocalize("VERIFYING_URL")];
8417 [delegate_ retainNetworkActivityIndicator];
8426 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8427 } else if ([context isEqualToString:@"trivial"])
8428 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8429 else if ([context isEqualToString:@"urlerror"])
8430 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8431 else if ([context isEqualToString:@"warning"]) {
8445 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8450 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8452 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8453 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8454 [list_ setRowHeight:53];
8455 [(UITableView *) list_ setDataSource:self];
8456 [list_ setDelegate:self];
8457 [[self view] addSubview:list_];
8460 - (void) viewDidLoad {
8461 [super viewDidLoad];
8463 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8464 [self updateButtonsForEditingStatus:NO animated:NO];
8467 - (void) releaseSubviews {
8472 [super releaseSubviews];
8475 - (id) initWithDatabase:(Database *)database {
8476 if ((self = [super init]) != nil) {
8477 database_ = database;
8481 - (void) reloadData {
8485 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8488 sources_ = [NSMutableArray arrayWithCapacity:16];
8489 [sources_ addObjectsFromArray:[database_ sources]];
8491 [sources_ sortUsingSelector:@selector(compareByName:)];
8494 int count([sources_ count]);
8496 for (int i = 0; i != count; i++) {
8497 if ([[sources_ objectAtIndex:i] record] == nil)
8502 [list_ setEditing:NO];
8503 [self updateButtonsForEditingStatus:NO animated:NO];
8507 - (void) showAddSourcePrompt {
8508 UIAlertView *alert = [[[UIAlertView alloc]
8509 initWithTitle:UCLocalize("ENTER_APT_URL")
8512 cancelButtonTitle:UCLocalize("CANCEL")
8514 UCLocalize("ADD_SOURCE"),
8518 [alert setContext:@"source"];
8520 [alert setNumberOfRows:1];
8521 [alert addTextFieldWithValue:@"http://" label:@""];
8523 UITextInputTraits *traits = [[alert textField] textInputTraits];
8524 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8525 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8526 [traits setKeyboardType:UIKeyboardTypeURL];
8527 // XXX: UIReturnKeyDone
8528 [traits setReturnKeyType:UIReturnKeyNext];
8533 - (void) addButtonClicked {
8534 [self showAddSourcePrompt];
8537 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8538 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8539 initWithTitle:UCLocalize("ADD")
8540 style:UIBarButtonItemStylePlain
8542 action:@selector(addButtonClicked)
8543 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8545 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8546 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8547 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8549 action:@selector(editButtonClicked)
8550 ] autorelease] animated:animated];
8552 if (IsWildcat_ && !editing)
8553 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8554 initWithTitle:UCLocalize("SETTINGS")
8555 style:UIBarButtonItemStylePlain
8557 action:@selector(settingsButtonClicked)
8561 - (void) settingsButtonClicked {
8562 [delegate_ showSettings];
8565 - (void) editButtonClicked {
8566 [list_ setEditing:![list_ isEditing] animated:YES];
8568 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8574 /* Settings Controller {{{ */
8575 @interface SettingsController : CyteViewController <
8576 UITableViewDataSource,
8579 _transient Database *database_;
8580 // XXX: ok, "roledelegate_"?...
8581 _transient id roledelegate_;
8582 _H<UITableView, 2> table_;
8583 _H<UISegmentedControl> segment_;
8584 _H<UIView> container_;
8587 - (void) showDoneButton;
8588 - (void) resizeSegmentedControl;
8592 @implementation SettingsController
8595 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8597 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8598 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8599 [table_ setDelegate:self];
8600 [(UITableView *) table_ setDataSource:self];
8601 [[self view] addSubview:table_];
8603 NSArray *items = [NSArray arrayWithObjects:
8605 UCLocalize("HACKER"),
8606 UCLocalize("DEVELOPER"),
8608 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8609 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8610 [container_ addSubview:segment_];
8613 - (void) viewDidLoad {
8614 [super viewDidLoad];
8616 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8619 if ([Role_ isEqualToString:@"User"]) index = 0;
8620 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8621 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8623 [segment_ setSelectedSegmentIndex:index];
8624 [self showDoneButton];
8627 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8628 [self resizeSegmentedControl];
8631 - (void) releaseSubviews {
8636 [super releaseSubviews];
8639 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8640 if ((self = [super init]) != nil) {
8641 database_ = database;
8642 roledelegate_ = delegate;
8646 - (void) resizeSegmentedControl {
8647 CGFloat width = [[self view] frame].size.width;
8648 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8651 - (void) viewWillAppear:(BOOL)animated {
8652 [super viewWillAppear:animated];
8654 [self resizeSegmentedControl];
8657 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8658 [self resizeSegmentedControl];
8661 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8662 [self resizeSegmentedControl];
8666 NSString *role(nil);
8668 switch ([segment_ selectedSegmentIndex]) {
8669 case 0: role = @"User"; break;
8670 case 1: role = @"Hacker"; break;
8671 case 2: role = @"Developer"; break;
8676 if (![role isEqualToString:Role_]) {
8677 bool rolling(Role_ == nil);
8680 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8684 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8688 [roledelegate_ loadData];
8690 [roledelegate_ updateData];
8694 - (void) segmentChanged:(UISegmentedControl *)control {
8695 [self showDoneButton];
8698 - (void) saveAndClose {
8701 [[self navigationItem] setRightBarButtonItem:nil];
8702 [[self navigationController] dismissModalViewControllerAnimated:YES];
8705 - (void) doneButtonClicked {
8706 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8707 [spinner startAnimating];
8708 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8709 [[self navigationItem] setRightBarButtonItem:spinItem];
8711 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8714 - (void) showDoneButton {
8715 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8716 initWithTitle:UCLocalize("DONE")
8717 style:UIBarButtonItemStyleDone
8719 action:@selector(doneButtonClicked)
8720 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8723 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8724 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8728 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8732 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8733 return nil; // This method is required by the protocol.
8736 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8738 return UCLocalize("ROLE_EX");
8740 return [NSString stringWithFormat:
8741 @"%@: %@\n%@: %@\n%@: %@",
8742 UCLocalize("USER"), UCLocalize("USER_EX"),
8743 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8744 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8749 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8750 return section == 3 ? 44.0f : 0;
8753 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8754 return section == 3 ? container_ : nil;
8757 - (void) reloadData {
8760 [table_ reloadData];
8765 /* Stash Controller {{{ */
8766 @interface StashController : CyteViewController {
8767 _H<UIActivityIndicatorView> spinner_;
8768 _H<UILabel> status_;
8769 _H<UILabel> caption_;
8774 @implementation StashController
8777 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8778 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8780 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8781 CGRect spinrect = [spinner_ frame];
8782 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8783 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8784 [spinner_ setFrame:spinrect];
8785 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8786 [[self view] addSubview:spinner_];
8787 [spinner_ startAnimating];
8790 captrect.size.width = [[self view] frame].size.width;
8791 captrect.size.height = 40.0f;
8792 captrect.origin.x = 0;
8793 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8794 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8795 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8796 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8797 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8798 [caption_ setTextColor:[UIColor whiteColor]];
8799 [caption_ setBackgroundColor:[UIColor clearColor]];
8800 [caption_ setShadowColor:[UIColor blackColor]];
8801 [caption_ setTextAlignment:UITextAlignmentCenter];
8802 [[self view] addSubview:caption_];
8805 statusrect.size.width = [[self view] frame].size.width;
8806 statusrect.size.height = 30.0f;
8807 statusrect.origin.x = 0;
8808 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8809 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8810 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8811 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8812 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8813 [status_ setTextColor:[UIColor whiteColor]];
8814 [status_ setBackgroundColor:[UIColor clearColor]];
8815 [status_ setShadowColor:[UIColor blackColor]];
8816 [status_ setTextAlignment:UITextAlignmentCenter];
8817 [[self view] addSubview:status_];
8820 - (void) releaseSubviews {
8825 [super releaseSubviews];
8831 @interface CYURLCache : SDURLCache {
8836 @implementation CYURLCache
8838 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8841 else if ([event isEqualToString:@"no-cache"])
8843 else if ([event isEqualToString:@"store"])
8845 else if ([event isEqualToString:@"invalid"])
8847 else if ([event isEqualToString:@"memory"])
8849 else if ([event isEqualToString:@"disk"])
8851 else if ([event isEqualToString:@"miss"])
8854 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8858 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8859 if (NSURLResponse *response = [cached response])
8860 if (NSString *mime = [response MIMEType])
8861 if ([mime isEqualToString:@"text/cache-manifest"]) {
8862 NSURL *url([response URL]);
8865 NSLog(@"###: %@", [url absoluteString]);
8868 @synchronized (HostConfig_) {
8869 [CachedURLs_ addObject:url];
8873 [super storeCachedResponse:cached forRequest:request];
8878 @interface Cydia : UIApplication <
8879 ConfirmationControllerDelegate,
8882 UINavigationControllerDelegate,
8883 UITabBarControllerDelegate
8885 _H<UIWindow> window_;
8886 _H<CYTabBarController> tabbar_;
8887 _H<CydiaLoadingViewController> emulated_;
8889 _H<NSMutableArray> essential_;
8890 _H<NSMutableArray> broken_;
8892 Database *database_;
8894 _H<NSURL> starturl_;
8899 _H<StashController> stash_;
8908 @implementation Cydia
8910 - (void) beginUpdate {
8911 [tabbar_ beginUpdate];
8915 return [tabbar_ updating];
8919 if ([broken_ count] != 0) {
8920 int count = [broken_ count];
8922 UIAlertView *alert = [[[UIAlertView alloc]
8923 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8924 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8926 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8928 UCLocalize("TEMPORARY_IGNORE"),
8932 [alert setContext:@"fixhalf"];
8933 [alert setNumberOfRows:2];
8935 } else if (!Ignored_ && [essential_ count] != 0) {
8936 int count = [essential_ count];
8938 UIAlertView *alert = [[[UIAlertView alloc]
8939 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8940 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8942 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8944 UCLocalize("UPGRADE_ESSENTIAL"),
8945 UCLocalize("COMPLETE_UPGRADE"),
8949 [alert setContext:@"upgrade"];
8954 - (void) returnToCydia {
8958 - (void) _saveConfig {
8964 NSString *error(nil);
8966 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8968 NSError *error(nil);
8969 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8970 NSLog(@"failure to save metadata data: %@", error);
8975 NSLog(@"failure to serialize metadata: %@", error);
8982 // Navigation controller for the queuing badge.
8983 - (UINavigationController *) queueNavigationController {
8984 NSArray *controllers = [tabbar_ viewControllers];
8985 return [controllers objectAtIndex:3];
8988 - (void) unloadData {
8989 [tabbar_ unloadData];
8992 - (void) _updateData {
8996 UINavigationController *navigation = [self queueNavigationController];
8998 id queuedelegate = nil;
8999 if ([[navigation viewControllers] count] > 0)
9000 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9002 [queuedelegate queueStatusDidChange];
9003 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9006 - (void) _refreshIfPossible:(NSDate *)update {
9007 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9009 bool recently = false;
9010 if (update != nil) {
9011 NSTimeInterval interval([update timeIntervalSinceNow]);
9012 if (interval <= 0 && interval > -(15*60))
9016 // Don't automatic refresh if:
9017 // - We already refreshed recently.
9018 // - We already auto-refreshed this launch.
9019 // - Auto-refresh is disabled.
9020 if (recently || loaded_ || ManualRefresh) {
9021 // If we are cancelling, we need to make sure it knows it's already loaded.
9024 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9026 // We are going to load, so remember that.
9029 SCNetworkReachabilityFlags flags; {
9030 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9031 SCNetworkReachabilityGetFlags(reachability, &flags);
9032 CFRelease(reachability);
9035 // XXX: this elaborate mess is what Apple is using to determine this? :(
9036 // XXX: do we care if the user has to intervene? maybe that's ok?
9038 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9039 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9040 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9041 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9042 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9043 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9047 // If we can reach the server, auto-refresh!
9049 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9055 - (void) refreshIfPossible {
9056 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9059 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9060 @synchronized (self) {
9061 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9062 [hud setText:UCLocalize("RELOADING_DATA")];
9064 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9067 [self removeProgressHUD:hud];
9071 [essential_ removeAllObjects];
9072 [broken_ removeAllObjects];
9074 NSArray *packages([database_ packages]);
9075 for (Package *package in packages) {
9077 [broken_ addObject:package];
9078 if ([package upgradableAndEssential:NO]) {
9079 if ([package essential])
9080 [essential_ addObject:package];
9085 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9088 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9089 [changesItem setBadgeValue:badge];
9090 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9091 [self setApplicationIconBadgeNumber:changes];
9094 [changesItem setBadgeValue:nil];
9095 [changesItem setAnimatedBadge:NO];
9096 [self setApplicationIconBadgeNumber:0];
9102 - (void) updateData {
9108 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9111 - (void) disemulate {
9112 if (emulated_ == nil)
9115 [window_ addSubview:[tabbar_ view]];
9116 [[emulated_ view] removeFromSuperview];
9118 [window_ setUserInteractionEnabled:YES];
9121 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9122 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9124 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9126 UIViewController *parent;
9127 if (emulated_ == nil)
9136 [parent presentModalViewController:navigation animated:YES];
9139 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9140 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9142 if (navigation != nil)
9143 [navigation pushViewController:progress animated:YES];
9145 [self presentModalViewController:progress force:YES];
9147 [progress invoke:invocation withTitle:title];
9151 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9152 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9155 - (void) repairWithInvocation:(NSInvocation *)invocation {
9157 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9161 - (void) repairWithSelector:(SEL)selector {
9162 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9165 - (void) reloadData {
9166 [self reloadDataWithInvocation:nil];
9167 if ([database_ progressDelegate] == nil)
9173 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9176 - (void) addSource:(NSDictionary *) source {
9180 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9181 AddSource(href, distribution, sections);
9184 - (void) addTrivialSource:(NSString *)href {
9185 AddSource(href, @"./");
9188 - (void) updateValues {
9193 pkgProblemResolver *resolver = [database_ resolver];
9195 resolver->InstallProtect();
9196 if (!resolver->Resolve(true))
9201 // XXX: this is a really crappy way of doing this.
9202 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9203 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9204 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9205 if ([tabbar_ updating])
9206 [tabbar_ cancelUpdate];
9208 if (![database_ prepare])
9211 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9212 [page setDelegate:self];
9213 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9216 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9217 [tabbar_ presentModalViewController:confirm_ animated:YES];
9223 @synchronized (self) {
9228 - (void) clearPackage:(Package *)package {
9229 @synchronized (self) {
9236 - (void) installPackages:(NSArray *)packages {
9237 @synchronized (self) {
9238 for (Package *package in packages)
9245 - (void) installPackage:(Package *)package {
9246 @synchronized (self) {
9253 - (void) removePackage:(Package *)package {
9254 @synchronized (self) {
9261 - (void) distUpgrade {
9262 @synchronized (self) {
9263 if (![database_ upgrade])
9270 [database_ perform];
9271 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9274 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9277 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9279 [self refreshIfPossible];
9282 - (void) showSettings {
9283 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9286 - (void) retainNetworkActivityIndicator {
9287 if (activity_++ == 0)
9288 [self setNetworkActivityIndicatorVisible:YES];
9291 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9295 - (void) releaseNetworkActivityIndicator {
9296 if (--activity_ == 0)
9297 [self setNetworkActivityIndicatorVisible:NO];
9300 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9305 - (void) cancelAndClear:(bool)clear {
9306 @synchronized (self) {
9318 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9319 NSString *context([alert context]);
9321 if ([context isEqualToString:@"conffile"]) {
9322 FILE *input = [database_ input];
9323 if (button == [alert cancelButtonIndex])
9324 fprintf(input, "N\n");
9325 else if (button == [alert firstOtherButtonIndex])
9326 fprintf(input, "Y\n");
9329 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9330 } else if ([context isEqualToString:@"fixhalf"]) {
9331 if (button == [alert cancelButtonIndex]) {
9332 @synchronized (self) {
9333 for (Package *broken in (id) broken_) {
9336 NSString *id = [broken id];
9337 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9338 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9339 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9340 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9346 } else if (button == [alert firstOtherButtonIndex]) {
9347 [broken_ removeAllObjects];
9351 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9352 } else if ([context isEqualToString:@"upgrade"]) {
9353 if (button == [alert firstOtherButtonIndex]) {
9354 @synchronized (self) {
9355 for (Package *essential in (id) essential_)
9356 [essential install];
9361 } else if (button == [alert firstOtherButtonIndex] + 1) {
9363 } else if (button == [alert cancelButtonIndex]) {
9367 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9371 - (void) system:(NSString *)command {
9372 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9375 system([command UTF8String]);
9381 - (void) applicationWillSuspend {
9383 [super applicationWillSuspend];
9386 - (BOOL) isSafeToSuspend {
9389 NSLog(@"isSafeToSuspend: locked_ != 0");
9394 // Use external process status API internally.
9395 // This is probably a really bad idea.
9396 // XXX: what is the point of this? does this solve anything at all?
9397 uint64_t status = 0;
9399 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9400 notify_get_state(notify_token, &status);
9401 notify_cancel(notify_token);
9406 NSLog(@"isSafeToSuspend: status != 0");
9412 NSLog(@"isSafeToSuspend: -> true");
9417 - (void) applicationSuspend:(__GSEvent *)event {
9418 if ([self isSafeToSuspend])
9419 [super applicationSuspend:event];
9422 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9423 if ([self isSafeToSuspend])
9424 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9427 - (void) _setSuspended:(BOOL)value {
9428 if ([self isSafeToSuspend])
9429 [super _setSuspended:value];
9432 - (UIProgressHUD *) addProgressHUD {
9433 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9434 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9436 [window_ setUserInteractionEnabled:NO];
9438 UIViewController *target(tabbar_);
9439 if (UIViewController *modal = [target modalViewController])
9442 UIView *view([target view]);
9443 [view addSubview:hud];
9445 [hud showInView:[tabbar_ view]];
9451 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9454 [hud removeFromSuperview];
9455 [window_ setUserInteractionEnabled:YES];
9458 - (CyteViewController *) pageForPackage:(NSString *)name {
9459 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9462 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9463 NSString *scheme([[url scheme] lowercaseString]);
9464 if ([[url absoluteString] length] <= [scheme length] + 3)
9466 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9467 NSArray *components([path pathComponents]);
9469 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9470 return [self pageForPackage:[components objectAtIndex:1]];
9472 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9475 NSString *base([components objectAtIndex:0]);
9477 CyteViewController *controller = nil;
9479 if ([base isEqualToString:@"url"]) {
9480 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9481 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9482 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9483 } else if (!external && [components count] == 1) {
9484 if ([base isEqualToString:@"manage"]) {
9485 controller = [[[ManageController alloc] init] autorelease];
9488 if ([base isEqualToString:@"sources"]) {
9489 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9492 if ([base isEqualToString:@"home"]) {
9493 controller = [[[HomeController alloc] init] autorelease];
9496 if ([base isEqualToString:@"sections"]) {
9497 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9500 if ([base isEqualToString:@"search"]) {
9501 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9504 if ([base isEqualToString:@"changes"]) {
9505 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9508 if ([base isEqualToString:@"installed"]) {
9509 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9511 } else if ([components count] == 2) {
9512 NSString *argument = [components objectAtIndex:1];
9514 if ([base isEqualToString:@"package"]) {
9515 controller = [self pageForPackage:argument];
9518 if (!external && [base isEqualToString:@"search"]) {
9519 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9522 if (!external && [base isEqualToString:@"sections"]) {
9523 if ([argument isEqualToString:@"all"])
9525 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9528 if (!external && [base isEqualToString:@"sources"]) {
9529 if ([argument isEqualToString:@"add"]) {
9530 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9531 [(SourcesController *)controller showAddSourcePrompt];
9533 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9534 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9538 if (!external && [base isEqualToString:@"launch"]) {
9539 [self launchApplicationWithIdentifier:argument suspended:NO];
9542 } else if (!external && [components count] == 3) {
9543 NSString *arg1 = [components objectAtIndex:1];
9544 NSString *arg2 = [components objectAtIndex:2];
9546 if ([base isEqualToString:@"package"]) {
9547 if ([arg2 isEqualToString:@"settings"]) {
9548 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9549 } else if ([arg2 isEqualToString:@"files"]) {
9550 if (Package *package = [database_ packageWithName:arg1]) {
9551 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9552 [(FileTable *)controller setPackage:package];
9558 [controller setDelegate:self];
9562 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9563 CyteViewController *page([self pageForURL:url forExternal:external]);
9566 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9567 [nav setViewControllers:[NSArray arrayWithObject:page]];
9568 [tabbar_ setUnselectedViewController:nav];
9574 - (void) applicationOpenURL:(NSURL *)url {
9575 [super applicationOpenURL:url];
9580 [self openCydiaURL:url forExternal:YES];
9583 - (void) applicationWillResignActive:(UIApplication *)application {
9584 // Stop refreshing if you get a phone call or lock the device.
9585 if ([tabbar_ updating])
9586 [tabbar_ cancelUpdate];
9588 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9589 [super applicationWillResignActive:application];
9592 - (void) saveState {
9593 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9594 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9595 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9601 - (void) applicationWillTerminate:(UIApplication *)application {
9605 - (void) setConfigurationData:(NSString *)data {
9606 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9608 if (!conffile_r(data)) {
9609 lprintf("E:invalid conffile\n");
9613 NSString *ofile = conffile_r[1];
9614 //NSString *nfile = conffile_r[2];
9616 UIAlertView *alert = [[[UIAlertView alloc]
9617 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9618 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9620 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9622 UCLocalize("ACCEPT_NEW_COPY"),
9623 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9627 [alert setContext:@"conffile"];
9628 [alert setNumberOfRows:2];
9632 - (void) addStashController {
9634 stash_ = [[[StashController alloc] init] autorelease];
9635 [window_ addSubview:[stash_ view]];
9638 - (void) removeStashController {
9639 [[stash_ view] removeFromSuperview];
9645 [self setIdleTimerDisabled:YES];
9647 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9648 UpdateExternalStatus(1);
9649 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9650 UpdateExternalStatus(0);
9652 [self removeStashController];
9654 if (ExecFork() == 0) {
9655 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9656 perror("launchctl stop");
9660 - (void) setupViewControllers {
9661 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9663 NSMutableArray *items([NSMutableArray arrayWithObjects:
9664 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9665 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9666 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9667 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9671 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9672 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9674 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9677 NSMutableArray *controllers([NSMutableArray array]);
9678 for (UITabBarItem *item in items) {
9679 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9680 [controller setTabBarItem:item];
9681 [controllers addObject:controller];
9683 [tabbar_ setViewControllers:controllers];
9685 [tabbar_ setUpdateDelegate:self];
9688 - (void) _sendMemoryWarningNotification {
9689 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9692 - (void) _sendMemoryWarningNotifications {
9694 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9699 - (void) applicationDidFinishLaunching:(id)unused {
9700 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9703 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9704 [self setApplicationSupportsShakeToEdit:NO];
9706 @synchronized (HostConfig_) {
9707 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9710 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9711 initWithMemoryCapacity:524288
9712 diskCapacity:10485760
9713 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9716 [CydiaWebViewController _initialize];
9718 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9720 // this would disallow http{,s} URLs from accessing this data
9721 //[WebView registerURLSchemeAsLocal:@"cydia"];
9723 Font12_ = [UIFont systemFontOfSize:12];
9724 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9725 Font14_ = [UIFont systemFontOfSize:14];
9726 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9727 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9729 essential_ = [NSMutableArray arrayWithCapacity:4];
9730 broken_ = [NSMutableArray arrayWithCapacity:4];
9732 // XXX: I really need this thing... like, seriously... I'm sorry
9733 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9735 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9736 [window_ orderFront:self];
9737 [window_ makeKey:self];
9738 [window_ setHidden:NO];
9741 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9742 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9743 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9744 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9745 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9746 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9747 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9748 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9749 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9752 [self addStashController];
9753 // XXX: this would be much cleaner as a yieldToSelector:
9754 // that way the removeStashController could happen right here inline
9755 // we also could no longer require the useless stash_ field anymore
9756 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9760 database_ = [Database sharedInstance];
9761 [database_ setDelegate:self];
9763 [window_ setUserInteractionEnabled:NO];
9764 [self setupViewControllers];
9766 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9767 [window_ addSubview:[emulated_ view]];
9769 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9773 - (NSArray *) defaultStartPages {
9774 NSMutableArray *standard = [NSMutableArray array];
9775 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9776 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9777 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9779 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9781 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9782 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9784 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9791 [window_ setUserInteractionEnabled:YES];
9792 [self showSettings];
9795 if ([emulated_ modalViewController] != nil)
9796 [emulated_ dismissModalViewControllerAnimated:YES];
9797 [window_ setUserInteractionEnabled:NO];
9800 [self reloadDataWithInvocation:nil];
9801 [self refreshIfPossible];
9806 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9807 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9808 int standardIndex = 0;
9809 NSArray *standard = [self defaultStartPages];
9816 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9817 if (valid && closed != nil) {
9818 NSTimeInterval interval([closed timeIntervalSinceNow]);
9819 // XXX: Is 15 minutes the optimal time here?
9820 if (interval > 0 && interval <= -(15*60))
9824 if (valid && [saved count] != [standard count])
9828 for (unsigned int i = 0; i < [standard count]; i++) {
9829 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9830 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9831 // but it's good enough for now.
9832 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9839 NSArray *items = nil;
9841 [tabbar_ setSelectedIndex:savedIndex];
9844 [tabbar_ setSelectedIndex:standardIndex];
9848 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9849 NSArray *stack = [items objectAtIndex:tab];
9850 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9851 NSMutableArray *current = [NSMutableArray array];
9853 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9854 NSString *addr = [stack objectAtIndex:nav];
9855 NSURL *url = [NSURL URLWithString:addr];
9856 CyteViewController *page = [self pageForURL:url forExternal:NO];
9858 [current addObject:page];
9861 [navigation setViewControllers:current];
9864 // (Try to) show the startup URL.
9865 if (starturl_ != nil) {
9866 [self openCydiaURL:starturl_ forExternal:NO];
9871 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9872 if (item != nil && IsWildcat_) {
9873 [sheet showFromBarButtonItem:item animated:YES];
9875 [sheet showInView:window_];
9879 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9880 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9881 [progress setTitle:task];
9882 [progress addProgressEvent:event];
9885 - (void) addProgressEventForTask:(NSArray *)data {
9886 CydiaProgressEvent *event([data objectAtIndex:0]);
9887 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9888 [self addProgressEvent:event forTask:task];
9891 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9892 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9898 id Alloc_(id self, SEL selector) {
9899 id object = alloc_(self, selector);
9900 lprintf("[%s]A-%p\n", self->isa->name, object);
9905 id Dealloc_(id self, SEL selector) {
9906 id object = dealloc_(self, selector);
9907 lprintf("[%s]D-%p\n", self->isa->name, object);
9911 Class $WebDefaultUIKitDelegate;
9913 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9914 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9915 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9916 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9919 static NSSet *MobilizedFiles_;
9921 static NSURL *MobilizeURL(NSURL *url) {
9922 NSString *path([url path]);
9923 if ([path hasPrefix:@"/var/root/"]) {
9924 NSString *file([path substringFromIndex:10]);
9925 if ([MobilizedFiles_ containsObject:file])
9926 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9932 Class $CFXPreferencesPropertyListSource;
9933 @class CFXPreferencesPropertyListSource;
9935 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9936 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9937 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9938 url = MobilizeURL(url);
9939 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9940 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9946 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9947 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9948 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9949 url = MobilizeURL(url);
9950 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9951 //NSLog(@"%@ %@", [url absoluteString], value);
9957 Class $NSURLConnection;
9959 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9960 NSMutableURLRequest *copy([request mutableCopy]);
9962 NSURL *url([copy URL]);
9964 NSString *href([url absoluteString]);
9965 NSString *host([url host]);
9966 NSString *scheme([[url scheme] lowercaseString]);
9968 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9970 @synchronized (HostConfig_) {
9971 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9972 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9973 [copy setHTTPShouldUsePipelining:YES];
9975 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9976 if ([control isEqualToString:@"max-age=0"])
9977 if ([CachedURLs_ containsObject:href]) {
9979 NSLog(@"~~~: %@", href);
9982 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9984 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9985 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9986 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9990 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9994 int main(int argc, char *argv[]) {
9995 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9999 UpdateExternalStatus(0);
10001 if (Class $UIDevice = objc_getClass("UIDevice")) {
10002 UIDevice *device([$UIDevice currentDevice]);
10003 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10005 IsWildcat_ = false;
10007 UIScreen *screen([UIScreen mainScreen]);
10008 if ([screen respondsToSelector:@selector(scale)])
10009 ScreenScale_ = [screen scale];
10013 UIDevice *device([UIDevice currentDevice]);
10014 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10015 Idiom_ = @"iphone";
10017 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10018 if (idiom == UIUserInterfaceIdiomPhone)
10019 Idiom_ = @"iphone";
10020 else if (idiom == UIUserInterfaceIdiomPad)
10023 NSLog(@"unknown UIUserInterfaceIdiom!");
10026 Pcre pattern("^([0-9]+\\.[0-9]+)");
10028 if (pattern([device systemVersion]))
10029 Firmware_ = pattern[1];
10030 if (pattern(Cydia_))
10031 Major_ = pattern[1];
10033 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10035 HostConfig_ = [[[NSObject alloc] init] autorelease];
10036 @synchronized (HostConfig_) {
10037 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10038 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10039 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10040 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10041 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10044 NSString *ui(@"ui/ios");
10046 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10047 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10048 UI_ = CydiaURL(ui);
10050 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10052 MobilizedFiles_ = [NSMutableSet setWithObjects:
10053 @"Library/Preferences/com.apple.Accessibility.plist",
10054 @"Library/Preferences/com.apple.preferences.sounds.plist",
10057 /* Library Hacks {{{ */
10058 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10060 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10062 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10063 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10064 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10065 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10068 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10069 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10070 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10071 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10074 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10075 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10076 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10077 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10078 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10081 $NSURLConnection = objc_getClass("NSURLConnection");
10082 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10083 if (NSURLConnection$init$ != NULL) {
10084 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10085 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10088 /* Set Locale {{{ */
10089 Locale_ = CFLocaleCopyCurrent();
10090 Languages_ = [NSLocale preferredLanguages];
10092 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10093 //NSLog(@"%@", [Languages_ description]);
10096 if (Locale_ != NULL)
10097 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10098 else if (Languages_ != nil && [Languages_ count] != 0)
10099 lang = [[Languages_ objectAtIndex:0] UTF8String];
10101 // XXX: consider just setting to C and then falling through?
10104 if (lang != NULL) {
10105 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10106 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10109 NSLog(@"Setting Language: %s", lang);
10111 if (lang != NULL) {
10112 setenv("LANG", lang, true);
10113 std::setlocale(LC_ALL, lang);
10117 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10119 /* Parse Arguments {{{ */
10120 bool substrate(false);
10126 for (int argi(1); argi != argc; ++argi)
10127 if (strcmp(argv[argi], "--") == 0) {
10129 argv[argi] = argv[0];
10135 for (int argi(1); argi != arge; ++argi)
10136 if (strcmp(args[argi], "--substrate") == 0)
10139 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10143 App_ = [[NSBundle mainBundle] bundlePath];
10149 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10150 alloc_ = alloc->method_imp;
10151 alloc->method_imp = (IMP) &Alloc_;*/
10153 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10154 dealloc_ = dealloc->method_imp;
10155 dealloc->method_imp = (IMP) &Dealloc_;*/
10157 /* System Information {{{ */
10161 size = sizeof(maxproc);
10162 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10163 perror("sysctlbyname(\"kern.maxproc\", ?)");
10164 else if (maxproc < 64) {
10166 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10167 perror("sysctlbyname(\"kern.maxproc\", #)");
10170 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10171 char *osversion = new char[size];
10172 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10173 perror("sysctlbyname(\"kern.osversion\", ?)");
10175 System_ = [NSString stringWithUTF8String:osversion];
10177 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10178 char *machine = new char[size];
10179 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10180 perror("sysctlbyname(\"hw.machine\", ?)");
10182 Machine_ = machine;
10184 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10185 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10186 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10188 UniqueID_ = [device uniqueIdentifier];
10190 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10191 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10192 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10194 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10195 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10196 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10198 if (mcc != NULL && mnc != NULL)
10199 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10206 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10207 Build_ = [system objectForKey:@"ProductBuildVersion"];
10208 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10209 Product_ = [info objectForKey:@"SafariProductVersion"];
10210 Safari_ = [info objectForKey:@"CFBundleVersion"];
10213 /* Load Database {{{ */
10215 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10217 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10219 if (Metadata_ == NULL)
10220 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10222 Settings_ = [Metadata_ objectForKey:@"Settings"];
10224 Packages_ = [Metadata_ objectForKey:@"Packages"];
10226 Values_ = [Metadata_ objectForKey:@"Values"];
10227 Sections_ = [Metadata_ objectForKey:@"Sections"];
10228 Sources_ = [Metadata_ objectForKey:@"Sources"];
10230 Token_ = [Metadata_ objectForKey:@"Token"];
10232 Version_ = [Metadata_ objectForKey:@"Version"];
10234 @synchronized (HostConfig_) {
10235 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10239 if (Settings_ != nil)
10240 Role_ = [Settings_ objectForKey:@"Role"];
10242 if (Values_ == nil) {
10243 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10244 [Metadata_ setObject:Values_ forKey:@"Values"];
10247 if (Sections_ == nil) {
10248 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10249 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10252 if (Sources_ == nil) {
10253 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10254 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10257 if (Version_ == nil) {
10258 Version_ = [NSNumber numberWithUnsignedInt:0];
10259 [Metadata_ setObject:Version_ forKey:@"Version"];
10262 @synchronized (HostConfig_) {
10263 if (CydiaSource_ == nil) {
10264 CydiaSource_ = @"apt.saurik.com";
10265 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10269 if ([Version_ unsignedIntValue] == 0) {
10270 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10271 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10272 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10273 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10275 Version_ = [NSNumber numberWithUnsignedInt:1];
10276 [Metadata_ setObject:Version_ forKey:@"Version"];
10278 [Metadata_ removeObjectForKey:@"LastUpdate"];
10287 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10290 if (Packages_ != nil) {
10292 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10296 [Metadata_ removeObjectForKey:@"Packages"];
10302 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10304 #define MobileSubstrate_(name) \
10305 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10306 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10307 if (handle == NULL) \
10308 NSLog(@"%s", dlerror()); \
10311 MobileSubstrate_(Activator)
10312 MobileSubstrate_(libstatusbar)
10313 MobileSubstrate_(SimulatedKeyEvents)
10314 MobileSubstrate_(WinterBoard)
10316 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10317 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10319 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10321 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10322 unlink("/tmp/.cydia.fw");
10324 } else if (access("/User", F_OK) != 0 || version < 4) {
10327 system("/usr/libexec/cydia/firmware.sh");
10331 _assert([[NSFileManager defaultManager]
10332 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10333 withIntermediateDirectories:YES
10338 if (access("/tmp/cydia.chk", F_OK) == 0) {
10339 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10340 _assert(errno == ENOENT);
10341 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10342 _assert(errno == ENOENT);
10345 /* APT Initialization {{{ */
10346 _assert(pkgInitConfig(*_config));
10347 _assert(pkgInitSystem(*_config, _system));
10350 _config->Set("APT::Acquire::Translation", lang);
10352 // XXX: this timeout might be important :(
10353 //_config->Set("Acquire::http::Timeout", 15);
10355 _config->Set("Acquire::http::MaxParallel", 3);
10357 /* Color Choices {{{ */
10358 space_ = CGColorSpaceCreateDeviceRGB();
10360 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10361 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10362 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10363 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10364 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10365 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10366 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10367 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10368 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10370 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10371 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10373 /* UIKit Configuration {{{ */
10374 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10375 if ($GSFontSetUseLegacyFontMetrics != NULL)
10376 $GSFontSetUseLegacyFontMetrics(YES);
10378 // XXX: I have a feeling this was important
10379 //UIKeyboardDisableAutomaticAppearance();
10382 Colon_ = UCLocalize("COLON_DELIMITED");
10383 Elision_ = UCLocalize("ELISION");
10384 Error_ = UCLocalize("ERROR");
10385 Warning_ = UCLocalize("WARNING");
10388 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10390 CGColorSpaceRelease(space_);
10391 CFRelease(Locale_);