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;
1362 - (NSString *) rooturi;
1363 - (NSString *) distribution;
1364 - (NSString *) type;
1367 - (NSString *) host;
1369 - (NSString *) name;
1370 - (NSString *) shortDescription;
1371 - (NSString *) label;
1372 - (NSString *) origin;
1373 - (NSString *) version;
1375 - (NSString *) defaultIcon;
1376 - (NSURL *) iconURL;
1380 @implementation Source
1384 distribution_.clear();
1389 description_.clear();
1395 defaultIcon_.clear();
1402 + (NSString *) webScriptNameForSelector:(SEL)selector {
1404 else if (selector == @selector(addSection:))
1405 return @"addSection";
1406 else if (selector == @selector(getField:))
1408 else if (selector == @selector(removeSection:))
1409 return @"removeSection";
1410 else if (selector == @selector(remove))
1416 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1417 return [self webScriptNameForSelector:selector] == nil;
1420 + (NSArray *) _attributeKeys {
1421 return [NSArray arrayWithObjects:
1432 @"shortDescription",
1439 - (NSArray *) attributeKeys {
1440 return [[self class] _attributeKeys];
1443 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1444 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1447 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1450 trusted_ = index->IsTrusted();
1452 uri_.set(pool, index->GetURI());
1453 distribution_.set(pool, index->GetDist());
1454 type_.set(pool, index->GetType());
1456 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1457 if (dindex != NULL) {
1458 base_.set(pool, dindex->MetaIndexURI(""));
1461 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1464 pkgTagFile tags(&fd);
1466 pkgTagSection section;
1473 {"default-icon", &defaultIcon_},
1474 {"depiction", &depiction_},
1475 {"description", &description_},
1477 {"origin", &origin_},
1478 {"support", &support_},
1479 {"version", &version_},
1482 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1483 const char *start, *end;
1485 if (section.Find(names[i].name_, start, end)) {
1486 CYString &value(*names[i].value_);
1487 value.set(pool, start, end - start);
1493 record_ = [Sources_ objectForKey:[self key]];
1495 NSURL *url([NSURL URLWithString:uri_]);
1499 host_ = [host_ lowercaseString];
1504 authority_ = [url path];
1507 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1508 if ((self = [super init]) != nil) {
1509 era_ = [database era];
1510 database_ = database;
1513 [self setMetaIndex:index inPool:pool];
1517 - (NSString *) getField:(NSString *)name {
1518 @synchronized (database_) {
1519 if ([database_ era] != era_ || index_ == NULL)
1522 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1527 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1532 pkgTagFile tags(&fd);
1534 pkgTagSection section;
1537 const char *start, *end;
1538 if (!section.Find([name UTF8String], start, end))
1539 return (NSString *) [NSNull null];
1541 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1544 - (NSComparisonResult) compareByName:(Source *)source {
1545 NSString *lhs = [self name];
1546 NSString *rhs = [source name];
1548 if ([lhs length] != 0 && [rhs length] != 0) {
1549 unichar lhc = [lhs characterAtIndex:0];
1550 unichar rhc = [rhs characterAtIndex:0];
1552 if (isalpha(lhc) && !isalpha(rhc))
1553 return NSOrderedAscending;
1554 else if (!isalpha(lhc) && isalpha(rhc))
1555 return NSOrderedDescending;
1558 return [lhs compare:rhs options:LaxCompareOptions_];
1561 - (NSString *) depictionForPackage:(NSString *)package {
1562 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1565 - (NSString *) supportForPackage:(NSString *)package {
1566 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1569 - (NSArray *) sections {
1570 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1573 - (void) _addSection:(NSString *)section {
1576 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1577 if (![sections containsObject:section]) {
1578 [sections addObject:section];
1582 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1587 - (bool) addSection:(NSString *)section {
1591 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1595 - (void) _removeSection:(NSString *)section {
1599 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1600 if ([sections containsObject:section]) {
1601 [sections removeObject:section];
1606 - (bool) removeSection:(NSString *)section {
1610 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1615 [Sources_ removeObjectForKey:[self key]];
1620 bool value(record_ != nil);
1621 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1625 - (NSDictionary *) record {
1633 - (NSString *) rooturi {
1637 - (NSString *) distribution {
1638 return distribution_;
1641 - (NSString *) type {
1645 - (NSString *) baseuri {
1646 return base_.empty() ? nil : (id) base_;
1649 - (NSString *) iconuri {
1650 if (NSString *base = [self baseuri])
1651 return [base stringByAppendingString:@"CydiaIcon.png"];
1656 - (NSURL *) iconURL {
1657 if (NSString *uri = [self iconuri])
1658 return [NSURL URLWithString:uri];
1662 - (NSString *) key {
1663 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1666 - (NSString *) host {
1670 - (NSString *) name {
1671 return origin_.empty() ? (id) authority_ : origin_;
1674 - (NSString *) shortDescription {
1675 return description_;
1678 - (NSString *) label {
1679 return label_.empty() ? (id) authority_ : label_;
1682 - (NSString *) origin {
1686 - (NSString *) version {
1690 - (NSString *) defaultIcon {
1691 return defaultIcon_;
1696 /* CydiaOperation Class {{{ */
1697 @interface CydiaOperation : NSObject {
1698 _H<NSString> operator_;
1699 _H<NSString> value_;
1702 - (NSString *) operator;
1703 - (NSString *) value;
1707 @implementation CydiaOperation
1709 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1710 if ((self = [super init]) != nil) {
1711 operator_ = [NSString stringWithUTF8String:_operator];
1712 value_ = [NSString stringWithUTF8String:value];
1716 + (NSArray *) _attributeKeys {
1717 return [NSArray arrayWithObjects:
1723 - (NSArray *) attributeKeys {
1724 return [[self class] _attributeKeys];
1727 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1728 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1731 - (NSString *) operator {
1735 - (NSString *) value {
1741 /* CydiaClause Class {{{ */
1742 @interface CydiaClause : NSObject {
1743 _H<NSString> package_;
1744 _H<CydiaOperation> version_;
1747 - (NSString *) package;
1748 - (CydiaOperation *) version;
1752 @implementation CydiaClause
1754 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1755 if ((self = [super init]) != nil) {
1756 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1758 if (const char *version = dep.TargetVer())
1759 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1761 version_ = (id) [NSNull null];
1765 + (NSArray *) _attributeKeys {
1766 return [NSArray arrayWithObjects:
1772 - (NSArray *) attributeKeys {
1773 return [[self class] _attributeKeys];
1776 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1777 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1780 - (NSString *) package {
1784 - (CydiaOperation *) version {
1790 /* CydiaRelation Class {{{ */
1791 @interface CydiaRelation : NSObject {
1792 _H<NSString> relationship_;
1793 _H<NSMutableArray> clauses_;
1796 - (NSString *) relationship;
1797 - (NSArray *) clauses;
1801 @implementation CydiaRelation
1803 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1804 if ((self = [super init]) != nil) {
1805 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1806 clauses_ = [NSMutableArray arrayWithCapacity:8];
1808 pkgCache::DepIterator start;
1809 pkgCache::DepIterator end;
1810 dep.GlobOr(start, end); // ++dep
1813 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1815 // yes, seriously. (wtf?)
1823 + (NSArray *) _attributeKeys {
1824 return [NSArray arrayWithObjects:
1830 - (NSArray *) attributeKeys {
1831 return [[self class] _attributeKeys];
1834 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1835 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1838 - (NSString *) relationship {
1839 return relationship_;
1842 - (NSArray *) clauses {
1846 - (void) addClause:(CydiaClause *)clause {
1847 [clauses_ addObject:clause];
1852 /* Package Class {{{ */
1853 struct ParsedPackage {
1857 CYString architecture_;
1860 CYString depiction_;
1870 @interface Package : NSObject {
1873 uint32_t essential_ : 1;
1874 uint32_t obsolete_ : 1;
1875 uint32_t ignored_ : 1;
1876 uint32_t pooled_ : 1;
1882 _transient Database *database_;
1884 pkgCache::VerIterator version_;
1885 pkgCache::PkgIterator iterator_;
1886 pkgCache::VerFileIterator file_;
1892 CYString installed_;
1894 const char *section_;
1895 _transient NSString *section$_;
1899 PackageValue *metadata_;
1900 ParsedPackage *parsed_;
1902 _H<NSMutableArray> tags_;
1905 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1906 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1908 - (pkgCache::PkgIterator) iterator;
1911 - (NSString *) section;
1912 - (NSString *) simpleSection;
1914 - (NSString *) longSection;
1915 - (NSString *) shortSection;
1919 - (MIMEAddress *) maintainer;
1921 - (NSString *) longDescription;
1922 - (NSString *) shortDescription;
1925 - (PackageValue *) metadata;
1928 - (bool) subscribed;
1929 - (bool) setSubscribed:(bool)subscribed;
1933 - (NSString *) latest;
1934 - (NSString *) installed;
1935 - (BOOL) uninstalled;
1938 - (BOOL) upgradableAndEssential:(BOOL)essential;
1941 - (BOOL) unfiltered;
1945 - (BOOL) halfConfigured;
1946 - (BOOL) halfInstalled;
1948 - (NSString *) mode;
1951 - (NSString *) name;
1953 - (NSString *) homepage;
1954 - (NSString *) depiction;
1955 - (MIMEAddress *) author;
1957 - (NSString *) support;
1959 - (NSArray *) files;
1960 - (NSArray *) warnings;
1961 - (NSArray *) applications;
1963 - (Source *) source;
1966 - (BOOL) matches:(NSArray *)query;
1968 - (bool) hasSupportingRole;
1969 - (BOOL) hasTag:(NSString *)tag;
1970 - (NSString *) primaryPurpose;
1971 - (NSArray *) purposes;
1972 - (bool) isCommercial;
1974 - (void) setIndex:(size_t)index;
1976 - (CYString &) cyname;
1978 - (uint32_t) compareBySection:(NSArray *)sections;
1983 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1984 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1985 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1986 - (bool) isVisibleInSection:(NSString *)section;
1987 - (bool) isVisibleInSource:(Source *)source;
1991 uint32_t PackageChangesRadix(Package *self, void *) {
1996 uint32_t timestamp : 30;
1997 uint32_t ignored : 1;
1998 uint32_t upgradable : 1;
2002 bool upgradable([self upgradableAndEssential:YES]);
2003 value.bits.upgradable = upgradable ? 1 : 0;
2006 value.bits.timestamp = 0;
2007 value.bits.ignored = [self ignored] ? 0 : 1;
2008 value.bits.upgradable = 1;
2010 value.bits.timestamp = [self seen] >> 2;
2011 value.bits.ignored = 0;
2012 value.bits.upgradable = 0;
2015 return _not(uint32_t) - value.key;
2018 uint32_t PackagePrefixRadix(Package *self, void *context) {
2019 size_t offset(reinterpret_cast<size_t>(context));
2020 CYString &name([self cyname]);
2022 size_t size(name.size());
2025 char *text(name.data());
2028 if (!isdigit(text[0]))
2032 while (size != digits && isdigit(text[digits]))
2040 if (offset == 0 && zeros != 0) {
2041 memset(data, '0', zeros);
2042 memcpy(data + zeros, text, 4 - zeros);
2044 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2045 if (size <= offset - zeros)
2048 text += offset - zeros;
2049 size -= offset - zeros;
2052 memcpy(data, text, 4);
2054 memcpy(data, text, size);
2055 memset(data + size, 0, 4 - size);
2058 for (size_t i(0); i != 4; ++i)
2059 if (isalpha(data[i]))
2067 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2069 /* XXX: ntohl may be more honest */
2070 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2073 CYString &(*PackageName)(Package *self, SEL sel);
2075 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2076 _profile(PackageNameCompare)
2077 CYString &lhi(PackageName(lhs, @selector(cyname)));
2078 CYString &rhi(PackageName(rhs, @selector(cyname)));
2079 CFStringRef lhn(lhi), rhn(rhi);
2082 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2083 else if (rhn == NULL)
2084 return NSOrderedDescending;
2086 _profile(PackageNameCompare$NumbersLast)
2087 if (!lhi.empty() && !rhi.empty()) {
2088 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2089 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2090 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2091 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2092 return lha ? NSOrderedAscending : NSOrderedDescending;
2096 CFIndex length = CFStringGetLength(lhn);
2098 _profile(PackageNameCompare$Compare)
2099 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2104 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2105 return PackageNameCompare(*lhs, *rhs, context);
2108 struct PackageNameOrdering :
2109 std::binary_function<Package *, Package *, bool>
2111 _finline bool operator ()(Package *lhs, Package *rhs) const {
2112 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2116 @implementation Package
2118 - (NSString *) description {
2119 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2124 apr_pool_destroy(pool_);
2125 if (parsed_ != NULL)
2130 + (NSString *) webScriptNameForSelector:(SEL)selector {
2132 else if (selector == @selector(clear))
2134 else if (selector == @selector(getField:))
2136 else if (selector == @selector(hasTag:))
2138 else if (selector == @selector(install))
2140 else if (selector == @selector(remove))
2146 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2147 return [self webScriptNameForSelector:selector] == nil;
2150 + (NSArray *) _attributeKeys {
2151 return [NSArray arrayWithObjects:
2172 @"shortDescription",
2185 - (NSArray *) attributeKeys {
2186 return [[self class] _attributeKeys];
2189 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2190 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2193 - (NSArray *) relations {
2194 @synchronized (database_) {
2195 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2196 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2197 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2201 - (NSString *) architecture {
2203 @synchronized (database_) {
2204 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2207 - (NSString *) getField:(NSString *)name {
2208 @synchronized (database_) {
2209 if ([database_ era] != era_ || file_.end())
2212 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2214 const char *start, *end;
2215 if (!parser.Find([name UTF8String], start, end))
2216 return (NSString *) [NSNull null];
2218 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2222 if (parsed_ != NULL)
2224 @synchronized (database_) {
2225 if ([database_ era] != era_ || file_.end())
2228 ParsedPackage *parsed(new ParsedPackage);
2231 _profile(Package$parse)
2232 pkgRecords::Parser *parser;
2234 _profile(Package$parse$Lookup)
2235 parser = &[database_ records]->Lookup(file_);
2240 _profile(Package$parse$Find)
2245 {"architecture", &parsed->architecture_},
2246 {"icon", &parsed->icon_},
2247 {"depiction", &parsed->depiction_},
2248 {"homepage", &parsed->homepage_},
2249 {"website", &website},
2250 {"bugs", &parsed->bugs_},
2251 {"support", &parsed->support_},
2252 {"sponsor", &parsed->sponsor_},
2253 {"author", &parsed->author_},
2254 {"md5sum", &parsed->md5sum_},
2257 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2258 const char *start, *end;
2260 if (parser->Find(names[i].name_, start, end)) {
2261 CYString &value(*names[i].value_);
2262 _profile(Package$parse$Value)
2263 value.set(pool_, start, end - start);
2269 _profile(Package$parse$Tagline)
2270 const char *start, *end;
2271 if (parser->ShortDesc(start, end)) {
2272 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2275 while (stop != start && stop[-1] == '\r')
2277 parsed->tagline_.set(pool_, start, stop - start);
2281 _profile(Package$parse$Retain)
2282 if (parsed->homepage_.empty())
2283 parsed->homepage_ = website;
2284 if (parsed->homepage_ == parsed->depiction_)
2285 parsed->homepage_.clear();
2290 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2291 if ((self = [super init]) != nil) {
2292 _profile(Package$initWithVersion)
2294 apr_pool_create(&pool_, NULL);
2300 database_ = database;
2301 era_ = [database era];
2305 pkgCache::PkgIterator iterator(version.ParentPkg());
2306 iterator_ = iterator;
2308 _profile(Package$initWithVersion$Version)
2309 if (!version_.end())
2310 file_ = version_.FileList();
2312 pkgCache &cache([database_ cache]);
2313 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2317 _profile(Package$initWithVersion$Cache)
2318 name_.set(NULL, iterator.Display());
2320 latest_.set(NULL, StripVersion_(version_.VerStr()));
2322 pkgCache::VerIterator current(iterator.CurrentVer());
2324 installed_.set(NULL, StripVersion_(current.VerStr()));
2327 _profile(Package$initWithVersion$Tags)
2328 pkgCache::TagIterator tag(iterator.TagList());
2330 tags_ = [NSMutableArray arrayWithCapacity:8];
2332 const char *name(tag.Name());
2333 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2335 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2336 if (strcmp(name + 6, "enduser") == 0)
2338 else if (strcmp(name + 6, "hacker") == 0)
2340 else if (strcmp(name + 6, "developer") == 0)
2342 else if (strcmp(name + 6, "cydia") == 0)
2348 if (strncmp(name, "cydia::", 7) == 0) {
2349 if (strcmp(name + 7, "essential") == 0)
2351 else if (strcmp(name + 7, "obsolete") == 0)
2356 } while (!tag.end());
2360 _profile(Package$initWithVersion$Metadata)
2361 const char *mixed(iterator.Name());
2362 size_t size(strlen(mixed));
2363 char lower[size + 1];
2365 for (size_t i(0); i != size; ++i)
2366 lower[i] = mixed[i] | 0x20;
2369 PackageValue *metadata(PackageFind(lower, size));
2370 metadata_ = metadata;
2372 id_.set(NULL, metadata->name_, size);
2374 const char *latest(version_.VerStr());
2375 size_t length(strlen(latest));
2377 uint16_t vhash(hashlittle(latest, length));
2379 size_t capped(std::min<size_t>(8, length));
2380 latest = latest + length - capped;
2382 if (metadata->first_ == 0)
2383 metadata->first_ = now_;
2385 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2386 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2387 metadata->vhash_ = vhash;
2388 metadata->last_ = now_;
2389 } else if (metadata->last_ == 0)
2390 metadata->last_ = metadata->first_;
2393 _profile(Package$initWithVersion$Section)
2394 section_ = iterator.Section();
2397 _profile(Package$initWithVersion$Flags)
2398 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2399 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2404 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2405 pkgCache::VerIterator version;
2407 _profile(Package$packageWithIterator$GetCandidateVer)
2408 version = [database policy]->GetCandidateVer(iterator);
2416 _profile(Package$packageWithIterator$Allocate)
2417 package = [Package allocWithZone:zone];
2420 _profile(Package$packageWithIterator$Initialize)
2422 initWithVersion:version
2429 _profile(Package$packageWithIterator$Autorelease)
2430 package = [package autorelease];
2436 - (pkgCache::PkgIterator) iterator {
2440 - (NSString *) section {
2441 if (section$_ == nil) {
2442 if (section_ == NULL)
2445 _profile(Package$section$mappedSectionForPointer)
2446 section$_ = [database_ mappedSectionForPointer:section_];
2451 - (NSString *) simpleSection {
2452 if (NSString *section = [self section])
2453 return Simplify(section);
2458 - (NSString *) longSection {
2459 return LocalizeSection([self section]);
2462 - (NSString *) shortSection {
2463 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2466 - (NSString *) uri {
2469 pkgIndexFile *index;
2470 pkgCache::PkgFileIterator file(file_.File());
2471 if (![database_ list].FindIndex(file, index))
2473 return [NSString stringWithUTF8String:iterator_->Path];
2474 //return [NSString stringWithUTF8String:file.Site()];
2475 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2479 - (MIMEAddress *) maintainer {
2480 @synchronized (database_) {
2481 if ([database_ era] != era_ || file_.end())
2484 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2485 const std::string &maintainer(parser->Maintainer());
2486 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2489 - (NSString *) md5sum {
2490 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2494 @synchronized (database_) {
2495 if ([database_ era] != era_ || version_.end())
2498 return version_->InstalledSize;
2501 - (NSString *) longDescription {
2502 @synchronized (database_) {
2503 if ([database_ era] != era_ || file_.end())
2506 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2507 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2509 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2510 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2511 if ([lines count] < 2)
2514 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2515 for (size_t i(1), e([lines count]); i != e; ++i) {
2516 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2517 [trimmed addObject:trim];
2520 return [trimmed componentsJoinedByString:@"\n"];
2523 - (NSString *) shortDescription {
2524 if (parsed_ != NULL)
2525 return static_cast<NSString *>(parsed_->tagline_);
2527 @synchronized (database_) {
2528 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2530 const char *start, *end;
2531 if (!parser.ShortDesc(start, end))
2534 if (end - start > 200)
2538 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2541 while (end != start && end[-1] == '\r')
2545 return [(id) CYStringCreate(start, end - start) autorelease];
2549 _profile(Package$index)
2550 CFStringRef name((CFStringRef) [self name]);
2551 if (CFStringGetLength(name) == 0)
2553 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2554 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2556 return toupper(character);
2560 - (PackageValue *) metadata {
2565 PackageValue *metadata([self metadata]);
2566 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2569 - (bool) subscribed {
2570 return [self metadata]->subscribed_;
2573 - (bool) setSubscribed:(bool)subscribed {
2574 PackageValue *metadata([self metadata]);
2575 if (metadata->subscribed_ == subscribed)
2577 metadata->subscribed_ = subscribed;
2585 - (NSString *) latest {
2589 - (NSString *) installed {
2593 - (BOOL) uninstalled {
2594 return installed_.empty();
2598 return !version_.end();
2601 - (BOOL) upgradableAndEssential:(BOOL)essential {
2602 _profile(Package$upgradableAndEssential)
2603 pkgCache::VerIterator current(iterator_.CurrentVer());
2605 return essential && essential_;
2607 return !version_.end() && version_ != current;
2611 - (BOOL) essential {
2616 return [database_ cache][iterator_].InstBroken();
2619 - (BOOL) unfiltered {
2620 _profile(Package$unfiltered$obsolete)
2621 if (_unlikely(obsolete_))
2625 _profile(Package$unfiltered$hasSupportingRole)
2626 if (_unlikely(![self hasSupportingRole]))
2634 if (![self unfiltered])
2639 _profile(Package$visible$section)
2640 section = [self section];
2643 _profile(Package$visible$isSectionVisible)
2644 if (!isSectionVisible(section))
2652 unsigned char current(iterator_->CurrentState);
2653 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2656 - (BOOL) halfConfigured {
2657 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2660 - (BOOL) halfInstalled {
2661 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2665 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2666 return state.Mode != pkgDepCache::ModeKeep;
2669 - (NSString *) mode {
2670 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2672 switch (state.Mode) {
2673 case pkgDepCache::ModeDelete:
2674 if ((state.iFlags & pkgDepCache::Purge) != 0)
2678 case pkgDepCache::ModeKeep:
2679 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2680 return @"REINSTALL";
2681 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2685 case pkgDepCache::ModeInstall:
2686 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2687 return @"REINSTALL";
2688 else*/ switch (state.Status) {
2690 return @"DOWNGRADE";
2696 return @"NEW_INSTALL";
2707 - (NSString *) name {
2708 return name_.empty() ? id_ : name_;
2711 - (UIImage *) icon {
2712 NSString *section = [self simpleSection];
2715 if (parsed_ != NULL)
2716 if (NSString *href = parsed_->icon_)
2717 if ([href hasPrefix:@"file:///"])
2718 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2719 if (icon == nil) if (section != nil)
2720 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2721 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2722 if ([dicon hasPrefix:@"file:///"])
2723 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2725 icon = [UIImage applicationImageNamed:@"unknown.png"];
2729 - (NSString *) homepage {
2730 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2733 - (NSString *) depiction {
2734 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2737 - (MIMEAddress *) sponsor {
2738 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2741 - (MIMEAddress *) author {
2742 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2745 - (NSString *) support {
2746 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2749 - (NSArray *) files {
2750 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2751 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2754 fin.open([path UTF8String]);
2759 while (std::getline(fin, line))
2760 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2765 - (NSString *) state {
2766 @synchronized (database_) {
2767 if ([database_ era] != era_ || file_.end())
2770 switch (iterator_->CurrentState) {
2771 case pkgCache::State::NotInstalled:
2772 return @"NotInstalled";
2773 case pkgCache::State::UnPacked:
2775 case pkgCache::State::HalfConfigured:
2776 return @"HalfConfigured";
2777 case pkgCache::State::HalfInstalled:
2778 return @"HalfInstalled";
2779 case pkgCache::State::ConfigFiles:
2780 return @"ConfigFiles";
2781 case pkgCache::State::Installed:
2782 return @"Installed";
2783 case pkgCache::State::TriggersAwaited:
2784 return @"TriggersAwaited";
2785 case pkgCache::State::TriggersPending:
2786 return @"TriggersPending";
2789 return (NSString *) [NSNull null];
2792 - (NSString *) selection {
2793 @synchronized (database_) {
2794 if ([database_ era] != era_ || file_.end())
2797 switch (iterator_->SelectedState) {
2798 case pkgCache::State::Unknown:
2800 case pkgCache::State::Install:
2802 case pkgCache::State::Hold:
2804 case pkgCache::State::DeInstall:
2805 return @"DeInstall";
2806 case pkgCache::State::Purge:
2810 return (NSString *) [NSNull null];
2813 - (NSArray *) warnings {
2814 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2815 const char *name(iterator_.Name());
2817 size_t length(strlen(name));
2818 if (length < 2) invalid:
2819 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2820 else for (size_t i(0); i != length; ++i)
2822 /* XXX: technically this is not allowed */
2823 (name[i] < 'A' || name[i] > 'Z') &&
2824 (name[i] < 'a' || name[i] > 'z') &&
2825 (name[i] < '0' || name[i] > '9') &&
2826 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2829 if (strcmp(name, "cydia") != 0) {
2832 bool _private = false;
2835 bool repository = [[self section] isEqualToString:@"Repositories"];
2837 if (NSArray *files = [self files])
2838 for (NSString *file in files)
2839 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2841 else if (!user && [file isEqualToString:@"/User"])
2843 else if (!_private && [file isEqualToString:@"/private"])
2845 else if (!stash && [file isEqualToString:@"/var/stash"])
2848 /* XXX: this is not sensitive enough. only some folders are valid. */
2849 if (cydia && !repository)
2850 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2852 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2854 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2856 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2859 return [warnings count] == 0 ? nil : warnings;
2862 - (NSArray *) applications {
2863 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2865 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2867 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2868 if (NSArray *files = [self files])
2869 for (NSString *file in files)
2870 if (application_r(file)) {
2871 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2872 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2873 if ([id isEqualToString:me])
2876 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2878 display = application_r[1];
2880 NSString *bundle([file stringByDeletingLastPathComponent]);
2881 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2882 if (icon == nil || [icon length] == 0)
2884 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2886 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2887 [applications addObject:application];
2889 [application addObject:id];
2890 [application addObject:display];
2891 [application addObject:url];
2894 return [applications count] == 0 ? nil : applications;
2897 - (Source *) source {
2898 if (source_ == nil) {
2899 @synchronized (database_) {
2900 if ([database_ era] != era_ || file_.end())
2901 source_ = (Source *) [NSNull null];
2903 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2907 return source_ == (Source *) [NSNull null] ? nil : source_;
2914 - (BOOL) matches:(NSArray *)query {
2915 if (query == nil || [query count] == 0)
2924 string = [self name];
2925 length = [string length];
2927 for (NSString *term in query) {
2928 range = [string rangeOfString:term options:MatchCompareOptions_];
2929 if (range.location != NSNotFound)
2930 rank_ -= 6 * 1000000 / length;
2935 length = [string length];
2937 for (NSString *term in query) {
2938 range = [string rangeOfString:term options:MatchCompareOptions_];
2939 if (range.location != NSNotFound)
2940 rank_ -= 6 * 1000000 / length;
2944 string = [self shortDescription];
2945 length = [string length];
2946 NSUInteger stop(std::min<NSUInteger>(length, 200));
2948 for (NSString *term in query) {
2949 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2950 if (range.location != NSNotFound)
2951 rank_ -= 2 * 100000;
2957 - (bool) hasSupportingRole {
2962 if ([Role_ isEqualToString:@"User"])
2966 if ([Role_ isEqualToString:@"Hacker"])
2970 if ([Role_ isEqualToString:@"Developer"])
2975 - (NSArray *) tags {
2979 - (BOOL) hasTag:(NSString *)tag {
2980 return tags_ == nil ? NO : [tags_ containsObject:tag];
2983 - (NSString *) primaryPurpose {
2984 for (NSString *tag in (NSArray *) tags_)
2985 if ([tag hasPrefix:@"purpose::"])
2986 return [tag substringFromIndex:9];
2990 - (NSArray *) purposes {
2991 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2992 for (NSString *tag in (NSArray *) tags_)
2993 if ([tag hasPrefix:@"purpose::"])
2994 [purposes addObject:[tag substringFromIndex:9]];
2995 return [purposes count] == 0 ? nil : purposes;
2998 - (bool) isCommercial {
2999 return [self hasTag:@"cydia::commercial"];
3002 - (void) setIndex:(size_t)index {
3003 if (metadata_->index_ != index)
3004 metadata_->index_ = index;
3007 - (CYString &) cyname {
3008 return name_.empty() ? id_ : name_;
3011 - (uint32_t) compareBySection:(NSArray *)sections {
3012 NSString *section([self section]);
3013 for (size_t i(0), e([sections count]); i != e; ++i) {
3014 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3018 return _not(uint32_t);
3022 @synchronized (database_) {
3023 pkgProblemResolver *resolver = [database_ resolver];
3024 resolver->Clear(iterator_);
3026 pkgCacheFile &cache([database_ cache]);
3027 cache->SetReInstall(iterator_, false);
3028 cache->MarkKeep(iterator_, false);
3032 @synchronized (database_) {
3033 pkgProblemResolver *resolver = [database_ resolver];
3034 resolver->Clear(iterator_);
3035 resolver->Protect(iterator_);
3037 pkgCacheFile &cache([database_ cache]);
3038 cache->SetReInstall(iterator_, false);
3039 cache->MarkInstall(iterator_, false);
3041 pkgDepCache::StateCache &state((*cache)[iterator_]);
3042 if (!state.Install())
3043 cache->SetReInstall(iterator_, true);
3047 @synchronized (database_) {
3048 pkgProblemResolver *resolver = [database_ resolver];
3049 resolver->Clear(iterator_);
3050 resolver->Remove(iterator_);
3051 resolver->Protect(iterator_);
3053 pkgCacheFile &cache([database_ cache]);
3054 cache->SetReInstall(iterator_, false);
3055 cache->MarkDelete(iterator_, true);
3058 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3059 _profile(Package$isUnfilteredAndSearchedForBy)
3062 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3063 value &= [self unfiltered];
3066 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3067 value &= [self matches:query];
3074 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3075 if ([search length] == 0)
3078 _profile(Package$isUnfilteredAndSelectedForBy)
3081 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3082 value &= [self unfiltered];
3085 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3086 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3093 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3094 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3097 - (bool) isVisibleInSection:(NSString *)name {
3098 NSString *section([self section]);
3102 section == nil && [name length] == 0 ||
3103 [name isEqualToString:section]
3104 ) && [self visible];
3107 - (bool) isVisibleInSource:(Source *)source {
3108 return [self source] == source && [self visible];
3113 /* Section Class {{{ */
3114 @interface Section : NSObject {
3119 _H<NSString> localized_;
3122 - (NSComparisonResult) compareByLocalized:(Section *)section;
3123 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3124 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3125 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3126 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3127 - (NSString *) name;
3134 - (void) addToCount;
3136 - (void) setCount:(size_t)count;
3137 - (NSString *) localized;
3141 @implementation Section
3143 - (NSComparisonResult) compareByLocalized:(Section *)section {
3144 NSString *lhs(localized_);
3145 NSString *rhs([section localized]);
3147 /*if ([lhs length] != 0 && [rhs length] != 0) {
3148 unichar lhc = [lhs characterAtIndex:0];
3149 unichar rhc = [rhs characterAtIndex:0];
3151 if (isalpha(lhc) && !isalpha(rhc))
3152 return NSOrderedAscending;
3153 else if (!isalpha(lhc) && isalpha(rhc))
3154 return NSOrderedDescending;
3157 return [lhs compare:rhs options:LaxCompareOptions_];
3160 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3161 if ((self = [self initWithName:name localize:NO]) != nil) {
3162 if (localized != nil)
3163 localized_ = localized;
3167 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3168 return [self initWithName:name row:0 localize:localize];
3171 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3172 if ((self = [super init]) != nil) {
3177 localized_ = LocalizeSection(name_);
3181 /* XXX: localize the index thingees */
3182 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3183 if ((self = [super init]) != nil) {
3184 name_ = [NSString stringWithCharacters:&index length:1];
3190 - (NSString *) name {
3210 - (void) addToCount {
3214 - (void) setCount:(size_t)count {
3218 - (NSString *) localized {
3225 class CydiaLogCleaner :
3226 public pkgArchiveCleaner
3229 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3234 /* Database Implementation {{{ */
3235 @implementation Database
3237 + (Database *) sharedInstance {
3238 static _H<Database> instance;
3239 if (instance == nil)
3240 instance = [[[Database alloc] init] autorelease];
3248 - (void) releasePackages {
3249 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3250 CFArrayRemoveAllValues(packages_);
3254 // XXX: actually implement this thing
3256 [self releasePackages];
3257 apr_pool_destroy(pool_);
3258 NSRecycleZone(zone_);
3262 - (void) _readCydia:(NSNumber *)fd {
3263 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3264 std::istream is(&ib);
3267 static Pcre finish_r("^finish:([^:]*)$");
3269 while (std::getline(is, line)) {
3270 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3272 const char *data(line.c_str());
3273 size_t size = line.size();
3274 lprintf("C:%s\n", data);
3276 if (finish_r(data, size)) {
3277 NSString *finish = finish_r[1];
3278 int index = [Finishes_ indexOfObject:finish];
3279 if (index != INT_MAX && index > Finish_)
3289 - (void) _readStatus:(NSNumber *)fd {
3290 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3291 std::istream is(&ib);
3294 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3295 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3297 while (std::getline(is, line)) {
3298 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3300 const char *data(line.c_str());
3301 size_t size(line.size());
3302 lprintf("S:%s\n", data);
3304 if (conffile_r(data, size)) {
3305 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3306 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3307 } else if (strncmp(data, "status: ", 8) == 0) {
3308 // status: <package>: {unpacked,half-configured,installed}
3309 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3310 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3311 } else if (strncmp(data, "processing: ", 12) == 0) {
3312 // processing: configure: config-test
3313 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3314 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3315 } else if (pmstatus_r(data, size)) {
3316 std::string type([pmstatus_r[1] UTF8String]);
3318 NSString *package = pmstatus_r[2];
3319 if ([package isEqualToString:@"dpkg-exec"])
3322 float percent([pmstatus_r[3] floatValue]);
3323 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3325 NSString *string = pmstatus_r[4];
3327 if (type == "pmerror") {
3328 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3329 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3330 } else if (type == "pmstatus") {
3331 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3332 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3333 } else if (type == "pmconffile")
3334 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3336 lprintf("E:unknown pmstatus\n");
3338 lprintf("E:unknown status\n");
3346 - (void) _readOutput:(NSNumber *)fd {
3347 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3348 std::istream is(&ib);
3351 while (std::getline(is, line)) {
3352 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3354 lprintf("O:%s\n", line.c_str());
3356 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3357 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3369 - (Package *) packageWithName:(NSString *)name {
3372 @synchronized (self) {
3373 if (static_cast<pkgDepCache *>(cache_) == NULL)
3375 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3376 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3380 if ((self = [super init]) != nil) {
3387 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3388 apr_pool_create(&pool_, NULL);
3390 size_t capacity(MetaFile_->active_);
3396 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3397 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3401 _assert(pipe(fds) != -1);
3404 _config->Set("APT::Keep-Fds::", cydiafd_);
3405 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3408 detachNewThreadSelector:@selector(_readCydia:)
3410 withObject:[NSNumber numberWithInt:fds[0]]
3413 _assert(pipe(fds) != -1);
3417 detachNewThreadSelector:@selector(_readStatus:)
3419 withObject:[NSNumber numberWithInt:fds[0]]
3422 _assert(pipe(fds) != -1);
3423 _assert(dup2(fds[0], 0) != -1);
3424 _assert(close(fds[0]) != -1);
3426 input_ = fdopen(fds[1], "a");
3428 _assert(pipe(fds) != -1);
3429 _assert(dup2(fds[1], 1) != -1);
3430 _assert(close(fds[1]) != -1);
3433 detachNewThreadSelector:@selector(_readOutput:)
3435 withObject:[NSNumber numberWithInt:fds[0]]
3440 - (pkgCacheFile &) cache {
3444 - (pkgDepCache::Policy *) policy {
3448 - (pkgRecords *) records {
3452 - (pkgProblemResolver *) resolver {
3456 - (pkgAcquire &) fetcher {
3460 - (pkgSourceList &) list {
3464 - (NSArray *) packages {
3465 return (NSArray *) packages_;
3468 - (NSArray *) sources {
3472 - (Source *) sourceWithKey:(NSString *)key {
3473 for (Source *source in [self sources]) {
3474 if ([[source key] isEqualToString:key])
3479 - (bool) popErrorWithTitle:(NSString *)title {
3482 while (!_error->empty()) {
3484 bool warning(!_error->PopMessage(error));
3489 size_t size(error.size());
3490 if (size == 0 || error[size - 1] != '\n')
3492 error.resize(size - 1);
3495 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3497 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3503 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3504 return [self popErrorWithTitle:title] || !success;
3507 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3508 @synchronized (self) {
3511 [self releasePackages];
3514 [sourceList_ removeAllObjects];
3534 apr_pool_clear(pool_);
3536 NSRecycleZone(zone_);
3537 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3539 int chk(creat("/tmp/cydia.chk", 0644));
3543 if (invocation != nil)
3544 [invocation invoke];
3546 NSString *title(UCLocalize("DATABASE"));
3549 OpProgress progress;
3550 while (!cache_.Open(progress, true)) { pop:
3552 bool warning(!_error->PopMessage(error));
3553 lprintf("cache_.Open():[%s]\n", error.c_str());
3555 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3556 [delegate_ repairWithSelector:@selector(configure)];
3557 else if (error == "The package lists or status file could not be parsed or opened.")
3558 [delegate_ repairWithSelector:@selector(update)];
3559 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3560 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3561 // else if (error == "Malformed Status line")
3562 // else if (error == "The list of sources could not be read.")
3564 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3574 unlink("/tmp/cydia.chk");
3576 now_ = [[NSDate date] timeIntervalSince1970];
3578 policy_ = new pkgDepCache::Policy();
3579 records_ = new pkgRecords(cache_);
3580 resolver_ = new pkgProblemResolver(cache_);
3581 fetcher_ = new pkgAcquire(&status_);
3584 list_ = new pkgSourceList();
3585 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3588 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3589 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3593 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3596 if (cache_->BrokenCount() != 0) {
3597 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3600 if (cache_->BrokenCount() != 0) {
3601 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3605 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3609 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3610 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3611 [sourceList_ addObject:object];
3613 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3614 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3615 // XXX: this could be more intelligent
3616 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3617 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3619 sourceMap_[cached->ID] = object;
3624 /*std::vector<Package *> packages;
3625 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3630 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3631 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3632 //packages.push_back(package);
3633 CFArrayAppendValue(packages_, CFRetain(package));
3637 /*if (packages.empty())
3638 packages_ = [[NSArray alloc] init];
3640 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3643 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3644 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3645 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3653 /*if (!packages.empty())
3654 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3655 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3657 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3659 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3661 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3665 size_t count(CFArrayGetCount(packages_));
3666 MetaFile_->active_ = count;
3668 for (size_t index(0); index != count; ++index)
3669 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3676 @synchronized (self) {
3678 resolver_ = new pkgProblemResolver(cache_);
3680 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3681 if (!cache_[iterator].Keep())
3682 cache_->MarkKeep(iterator, false);
3683 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3684 cache_->SetReInstall(iterator, false);
3687 - (void) configure {
3688 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3690 system([dpkg UTF8String]);
3695 // XXX: I don't remember this condition
3700 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3702 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3704 if ([self popErrorWithTitle:title])
3708 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3710 CydiaLogCleaner cleaner;
3711 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3718 fetcher_->Shutdown();
3720 pkgRecords records(cache_);
3722 lock_ = new FileFd();
3723 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3725 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3727 if ([self popErrorWithTitle:title])
3731 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3734 manager_ = (_system->CreatePM(cache_));
3735 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3742 bool substrate(RestartSubstrate_);
3743 RestartSubstrate_ = false;
3745 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3747 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3749 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3751 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3752 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3755 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3757 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3759 [self popErrorWithTitle:title];
3763 bool failed = false;
3764 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3765 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3767 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3773 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3781 RestartSubstrate_ = true;
3784 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3786 if (_error->PendingError()) {
3791 if (result == pkgPackageManager::Failed) {
3796 if (result != pkgPackageManager::Completed) {
3801 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3803 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3805 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3806 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3809 if (![before isEqualToArray:after])
3814 NSString *title(UCLocalize("UPGRADE"));
3815 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3821 [self updateWithStatus:status_];
3824 - (void) updateWithStatus:(Status &)status {
3825 NSString *title(UCLocalize("REFRESHING_DATA"));
3828 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3832 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3833 if ([self popErrorWithTitle:title])
3836 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3838 bool success(ListUpdate(status, list, PulseInterval_));
3839 if (status.WasCancelled())
3842 [self popErrorWithTitle:title forOperation:success];
3843 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3847 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3850 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3851 delegate_ = delegate;
3854 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3855 progress_ = delegate;
3856 status_.setDelegate(delegate);
3859 - (NSObject<ProgressDelegate> *) progressDelegate {
3863 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3864 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3865 return i == sourceMap_.end() ? nil : i->second;
3868 - (NSString *) mappedSectionForPointer:(const char *)section {
3869 _H<NSString> *mapped;
3871 _profile(Database$mappedSectionForPointer$Cache)
3872 mapped = §ions_[section];
3875 if (*mapped == NULL) {
3876 size_t length(strlen(section));
3877 char spaced[length + 1];
3879 _profile(Database$mappedSectionForPointer$Replace)
3880 for (size_t index(0); index != length; ++index)
3881 spaced[index] = section[index] == '_' ? ' ' : section[index];
3882 spaced[length] = '\0';
3887 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3888 string = [NSString stringWithUTF8String:spaced];
3891 _profile(Database$mappedSectionForPointer$Map)
3892 string = [SectionMap_ objectForKey:string] ?: string;
3902 static _H<NSMutableSet> Diversions_;
3904 @interface Diversion : NSObject {
3907 _H<NSString> format_;
3912 @implementation Diversion
3914 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3915 if ((self = [super init]) != nil) {
3916 pattern_ = [from UTF8String];
3922 - (NSString *) divert:(NSString *)url {
3923 return !pattern_(url) ? nil : pattern_->*format_;
3926 + (NSURL *) divertURL:(NSURL *)url {
3928 NSString *href([url absoluteString]);
3930 for (Diversion *diversion in (id) Diversions_)
3931 if (NSString *diverted = [diversion divert:href]) {
3933 NSLog(@"div: %@", diverted);
3935 url = [NSURL URLWithString:diverted];
3942 - (NSString *) key {
3946 - (NSUInteger) hash {
3950 - (BOOL) isEqual:(Diversion *)object {
3951 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3956 @interface CydiaObject : NSObject {
3957 _H<IndirectDelegate> indirect_;
3958 _transient id delegate_;
3961 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3965 @interface CydiaWebViewController : CyteWebViewController {
3966 _H<CydiaObject> cydia_;
3969 + (void) addDiversion:(Diversion *)diversion;
3973 /* Web Scripting {{{ */
3974 @implementation CydiaObject
3976 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3977 if ((self = [super init]) != nil) {
3978 indirect_ = indirect;
3982 - (void) setDelegate:(id)delegate {
3983 delegate_ = delegate;
3986 + (NSArray *) _attributeKeys {
3987 return [NSArray arrayWithObjects:
4004 - (NSArray *) attributeKeys {
4005 return [[self class] _attributeKeys];
4008 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4009 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4012 - (NSString *) version {
4016 - (NSString *) device {
4017 return [[UIDevice currentDevice] uniqueIdentifier];
4020 - (NSString *) firmware {
4021 return [[UIDevice currentDevice] systemVersion];
4024 - (NSString *) hostname {
4025 return [[UIDevice currentDevice] name];
4028 - (NSString *) idiom {
4029 return (id) Idiom_ ?: [NSNull null];
4032 - (NSString *) plmn {
4033 return (id) PLMN_ ?: [NSNull null];
4036 - (NSString *) bbsnum {
4037 return (id) BBSNum_ ?: [NSNull null];
4040 - (NSString *) ecid {
4041 return (id) ChipID_ ?: [NSNull null];
4044 - (NSString *) serial {
4045 return SerialNumber_;
4048 - (NSString *) role {
4049 return (id) Role_ ?: [NSNull null];
4052 - (NSString *) model {
4053 return [NSString stringWithUTF8String:Machine_];
4056 - (NSString *) token {
4057 return (id) Token_ ?: [NSNull null];
4060 + (NSString *) webScriptNameForSelector:(SEL)selector {
4062 else if (selector == @selector(addBridgedHost:))
4063 return @"addBridgedHost";
4064 else if (selector == @selector(addInsecureHost:))
4065 return @"addInsecureHost";
4066 else if (selector == @selector(addInternalRedirect::))
4067 return @"addInternalRedirect";
4068 else if (selector == @selector(addPipelinedHost:scheme:))
4069 return @"addPipelinedHost";
4070 else if (selector == @selector(addSource:::))
4071 return @"addSource";
4072 else if (selector == @selector(addTokenHost:))
4073 return @"addTokenHost";
4074 else if (selector == @selector(addTrivialSource:))
4075 return @"addTrivialSource";
4076 else if (selector == @selector(close))
4078 else if (selector == @selector(du:))
4080 else if (selector == @selector(stringWithFormat:arguments:))
4082 else if (selector == @selector(getAllSources))
4083 return @"getAllSourcs";
4084 else if (selector == @selector(getKernelNumber:))
4085 return @"getKernelNumber";
4086 else if (selector == @selector(getKernelString:))
4087 return @"getKernelString";
4088 else if (selector == @selector(getInstalledPackages))
4089 return @"getInstalledPackages";
4090 else if (selector == @selector(getIORegistryEntry::))
4091 return @"getIORegistryEntry";
4092 else if (selector == @selector(getLocaleIdentifier))
4093 return @"getLocaleIdentifier";
4094 else if (selector == @selector(getPreferredLanguages))
4095 return @"getPreferredLanguages";
4096 else if (selector == @selector(getPackageById:))
4097 return @"getPackageById";
4098 else if (selector == @selector(getMetadataKeys))
4099 return @"getMetadataKeys";
4100 else if (selector == @selector(getMetadataValue:))
4101 return @"getMetadataValue";
4102 else if (selector == @selector(getSessionValue:))
4103 return @"getSessionValue";
4104 else if (selector == @selector(installPackages:))
4105 return @"installPackages";
4106 else if (selector == @selector(localizedStringForKey:value:table:))
4108 else if (selector == @selector(popViewController:))
4109 return @"popViewController";
4110 else if (selector == @selector(refreshSources))
4111 return @"refreshSources";
4112 else if (selector == @selector(removeButton))
4113 return @"removeButton";
4114 else if (selector == @selector(saveConfig))
4115 return @"saveConfig";
4116 else if (selector == @selector(setCydiaSource:))
4117 return @"setCydiaSource";
4118 else if (selector == @selector(setMetadataValue::))
4119 return @"setMetadataValue";
4120 else if (selector == @selector(setSessionValue::))
4121 return @"setSessionValue";
4122 else if (selector == @selector(substitutePackageNames:))
4123 return @"substitutePackageNames";
4124 else if (selector == @selector(scrollToBottom:))
4125 return @"scrollToBottom";
4126 else if (selector == @selector(setAllowsNavigationAction:))
4127 return @"setAllowsNavigationAction";
4128 else if (selector == @selector(setBadgeValue:))
4129 return @"setBadgeValue";
4130 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4131 return @"setButtonImage";
4132 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4133 return @"setButtonTitle";
4134 else if (selector == @selector(setHidesBackButton:))
4135 return @"setHidesBackButton";
4136 else if (selector == @selector(setHidesNavigationBar:))
4137 return @"setHidesNavigationBar";
4138 else if (selector == @selector(setNavigationBarStyle:))
4139 return @"setNavigationBarStyle";
4140 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4141 return @"setNavigationBarTintColor";
4142 else if (selector == @selector(setPasteboardString:))
4143 return @"setPasteboardString";
4144 else if (selector == @selector(setPasteboardURL:))
4145 return @"setPasteboardURL";
4146 else if (selector == @selector(setToken:))
4148 else if (selector == @selector(setViewportWidth:))
4149 return @"setViewportWidth";
4150 else if (selector == @selector(statfs:))
4152 else if (selector == @selector(supports:))
4154 else if (selector == @selector(unload))
4160 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4161 return [self webScriptNameForSelector:selector] == nil;
4164 - (BOOL) supports:(NSString *)feature {
4165 return [feature isEqualToString:@"window.open"];
4169 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4172 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4173 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4176 - (NSNumber *) getKernelNumber:(NSString *)name {
4177 const char *string([name UTF8String]);
4180 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4181 return (id) [NSNull null];
4183 if (size != sizeof(int))
4184 return (id) [NSNull null];
4187 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4188 return (id) [NSNull null];
4190 return [NSNumber numberWithInt:value];
4193 - (NSString *) getKernelString:(NSString *)name {
4194 const char *string([name UTF8String]);
4197 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4198 return (id) [NSNull null];
4200 char value[size + 1];
4201 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4202 return (id) [NSNull null];
4204 // XXX: just in case you request something ludicrous
4207 return [NSString stringWithCString:value];
4210 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4211 NSObject *value(CYIOGetValue([path UTF8String], entry));
4214 if ([value isKindOfClass:[NSData class]])
4215 value = CYHex((NSData *) value);
4220 - (void) _setCydiaSource:(NSString *)source {
4221 @synchronized (HostConfig_) {
4222 CydiaSource_ = source;
4223 [Metadata_ setObject:source forKey:@"CydiaSource"];
4229 - (void) setCydiaSource:(NSString *)source {
4230 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4233 - (NSString *) cydiaSource {
4234 @synchronized (HostConfig_) {
4235 return (id) CydiaSource_ ?: [NSNull null];
4239 - (NSArray *) getMetadataKeys {
4240 @synchronized (Values_) {
4241 return [Values_ allKeys];
4244 - (id) getMetadataValue:(NSString *)key {
4245 @synchronized (Values_) {
4246 return [Values_ objectForKey:key];
4249 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4250 @synchronized (Values_) {
4251 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4252 [Values_ removeObjectForKey:key];
4254 [Values_ setObject:value forKey:key];
4256 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4259 - (id) getSessionValue:(NSString *)key {
4260 @synchronized (SessionData_) {
4261 return [SessionData_ objectForKey:key];
4264 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4265 @synchronized (SessionData_) {
4266 if (value == (id) [WebUndefined undefined])
4267 [SessionData_ removeObjectForKey:key];
4269 [SessionData_ setObject:value forKey:key];
4272 - (void) addBridgedHost:(NSString *)host {
4273 @synchronized (HostConfig_) {
4274 [BridgedHosts_ addObject:host];
4277 - (void) addInsecureHost:(NSString *)host {
4278 @synchronized (HostConfig_) {
4279 [InsecureHosts_ addObject:host];
4282 - (void) addTokenHost:(NSString *)host {
4283 @synchronized (HostConfig_) {
4284 [TokenHosts_ addObject:host];
4287 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4288 @synchronized (HostConfig_) {
4289 if (scheme != (id) [WebUndefined undefined])
4290 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4292 [PipelinedHosts_ addObject:host];
4295 - (void) popViewController:(NSNumber *)value {
4296 if (value == (id) [WebUndefined undefined])
4297 value = [NSNumber numberWithBool:YES];
4298 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4301 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4302 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4304 for (NSString *section in sections)
4305 [array addObject:section];
4307 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4310 distribution, @"Distribution",
4312 nil] waitUntilDone:NO];
4315 - (void) addTrivialSource:(NSString *)href {
4316 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4319 - (void) refreshSources {
4320 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4323 - (void) saveConfig {
4324 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4327 - (NSArray *) getAllSources {
4328 return [[Database sharedInstance] sources];
4331 - (NSArray *) getInstalledPackages {
4332 Database *database([Database sharedInstance]);
4333 @synchronized (database) {
4334 NSArray *packages([database packages]);
4335 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4336 for (Package *package in packages)
4337 if (![package uninstalled])
4338 [installed addObject:package];
4342 - (Package *) getPackageById:(NSString *)id {
4343 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4347 return (Package *) [NSNull null];
4350 - (NSString *) getLocaleIdentifier {
4351 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4354 - (NSArray *) getPreferredLanguages {
4358 - (NSArray *) statfs:(NSString *)path {
4361 if (path == nil || statfs([path UTF8String], &stat) == -1)
4364 return [NSArray arrayWithObjects:
4365 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4366 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4367 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4371 - (NSNumber *) du:(NSString *)path {
4372 NSNumber *value(nil);
4375 _assert(pipe(fds) != -1);
4377 pid_t pid(ExecFork());
4379 _assert(dup2(fds[1], 1) != -1);
4380 _assert(close(fds[0]) != -1);
4381 _assert(close(fds[1]) != -1);
4382 /* XXX: this should probably not use du */
4383 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4388 _assert(close(fds[1]) != -1);
4390 if (FILE *du = fdopen(fds[0], "r")) {
4392 while (fgets(line, sizeof(line), du) != NULL) {
4393 size_t length(strlen(line));
4394 while (length != 0 && line[length - 1] == '\n')
4395 line[--length] = '\0';
4396 if (char *tab = strchr(line, '\t')) {
4398 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4403 } else _assert(close(fds[0]));
4407 if (waitpid(pid, &status, 0) == -1)
4410 else _assert(false);
4416 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4419 - (void) installPackages:(NSArray *)packages {
4420 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4423 - (NSString *) substitutePackageNames:(NSString *)message {
4424 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4425 for (size_t i(0), e([words count]); i != e; ++i) {
4426 NSString *word([words objectAtIndex:i]);
4427 if (Package *package = [[Database sharedInstance] packageWithName:word])
4428 [words replaceObjectAtIndex:i withObject:[package name]];
4431 return [words componentsJoinedByString:@" "];
4434 - (void) removeButton {
4435 [indirect_ removeButton];
4438 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4439 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4442 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4443 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4446 - (void) setBadgeValue:(id)value {
4447 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4450 - (void) setAllowsNavigationAction:(NSString *)value {
4451 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4454 - (void) setHidesBackButton:(NSString *)value {
4455 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4458 - (void) setHidesNavigationBar:(NSString *)value {
4459 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4462 - (void) setNavigationBarStyle:(NSString *)value {
4463 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4466 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4467 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4468 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4469 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4472 - (void) setPasteboardString:(NSString *)value {
4473 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4476 - (void) setPasteboardURL:(NSString *)value {
4477 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4480 - (void) _setToken:(NSString *)token {
4484 [Metadata_ removeObjectForKey:@"Token"];
4486 [Metadata_ setObject:Token_ forKey:@"Token"];
4491 - (void) setToken:(NSString *)token {
4492 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4495 - (void) scrollToBottom:(NSNumber *)animated {
4496 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4499 - (void) setViewportWidth:(float)width {
4500 [indirect_ setViewportWidthOnMainThread:width];
4503 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4504 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4505 unsigned count([arguments count]);
4507 for (unsigned i(0); i != count; ++i)
4508 values[i] = [arguments objectAtIndex:i];
4509 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4512 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4513 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4515 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4517 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4523 @interface NSURL (CydiaSecure)
4526 @implementation NSURL (CydiaSecure)
4528 - (bool) isCydiaSecure {
4529 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4532 @synchronized (HostConfig_) {
4533 if ([InsecureHosts_ containsObject:[self host]])
4542 /* Cydia Browser Controller {{{ */
4543 @implementation CydiaWebViewController
4545 - (NSURL *) navigationURL {
4546 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4549 + (void) _initialize {
4550 [super _initialize];
4552 Diversions_ = [NSMutableSet setWithCapacity:0];
4555 + (void) addDiversion:(Diversion *)diversion {
4556 [Diversions_ addObject:diversion];
4559 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4560 [super webView:view didClearWindowObject:window forFrame:frame];
4562 WebDataSource *source([frame dataSource]);
4563 NSURLResponse *response([source response]);
4564 NSURL *url([response URL]);
4565 NSString *scheme([[url scheme] lowercaseString]);
4567 bool bridged(false);
4569 @synchronized (HostConfig_) {
4570 if ([scheme isEqualToString:@"file"])
4572 else if ([scheme isEqualToString:@"https"])
4573 if ([BridgedHosts_ containsObject:[url host]])
4578 [window setValue:cydia_ forKey:@"cydia"];
4581 - (void) _setupMail:(MFMailComposeViewController *)controller {
4582 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4584 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4585 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4588 - (NSURL *) URLWithURL:(NSURL *)url {
4589 return [Diversion divertURL:url];
4592 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4593 NSURL *url([request URL]);
4594 NSString *host([url host]);
4596 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4598 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4599 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4600 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4601 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4604 @synchronized (HostConfig_) {
4605 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4608 if ([url isCydiaSecure] && token) {
4609 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4610 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4616 - (void) setDelegate:(id)delegate {
4617 [super setDelegate:delegate];
4618 [cydia_ setDelegate:delegate];
4621 - (NSString *) applicationNameForUserAgent {
4622 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4625 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4627 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4628 if (Product_ != nil)
4629 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4635 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4636 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4642 @interface AppCacheController : CydiaWebViewController {
4647 @implementation AppCacheController
4649 - (void) didReceiveMemoryWarning {
4656 @interface NSObject (CydiaScript)
4657 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4660 @implementation NSObject (CydiaScript)
4662 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4668 @implementation NSArray (CydiaScript)
4670 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4671 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4672 for (size_t i(0), e([self count]); i != e; ++i)
4673 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4679 @implementation NSDictionary (CydiaScript)
4681 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4682 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4684 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4691 /* Confirmation Controller {{{ */
4692 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4693 if (!iterator.end())
4694 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4695 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4697 pkgCache::PkgIterator package(dep.TargetPkg());
4700 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4707 @protocol ConfirmationControllerDelegate
4708 - (void) cancelAndClear:(bool)clear;
4709 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4713 @interface ConfirmationController : CydiaWebViewController {
4714 _transient Database *database_;
4716 _H<UIAlertView> essential_;
4718 _H<NSDictionary> changes_;
4719 _H<NSMutableArray> issues_;
4720 _H<NSDictionary> sizes_;
4725 - (id) initWithDatabase:(Database *)database;
4729 @implementation ConfirmationController
4733 RestartSubstrate_ = true;
4734 [delegate_ confirmWithNavigationController:[self navigationController]];
4737 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4738 NSString *context([alert context]);
4740 if ([context isEqualToString:@"remove"]) {
4741 if (button == [alert cancelButtonIndex])
4742 [self dismissModalViewControllerAnimated:YES];
4743 else if (button == [alert firstOtherButtonIndex]) {
4747 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4748 } else if ([context isEqualToString:@"unable"]) {
4749 [self dismissModalViewControllerAnimated:YES];
4750 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4752 [super alertView:alert clickedButtonAtIndex:button];
4756 - (void) _doContinue {
4757 [delegate_ cancelAndClear:NO];
4758 [self dismissModalViewControllerAnimated:YES];
4761 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4762 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4766 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4767 [super webView:view didClearWindowObject:window forFrame:frame];
4769 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4770 (id) changes_, @"changes",
4771 (id) issues_, @"issues",
4772 (id) sizes_, @"sizes",
4774 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4777 - (id) initWithDatabase:(Database *)database {
4778 if ((self = [super init]) != nil) {
4779 database_ = database;
4781 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4782 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4783 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4784 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4785 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4789 pkgCacheFile &cache([database_ cache]);
4790 NSArray *packages([database_ packages]);
4791 pkgDepCache::Policy *policy([database_ policy]);
4793 issues_ = [NSMutableArray arrayWithCapacity:4];
4795 for (Package *package in packages) {
4796 pkgCache::PkgIterator iterator([package iterator]);
4797 NSString *name([package id]);
4799 if ([package broken]) {
4800 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4802 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4804 reasons, @"reasons",
4807 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4811 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4812 pkgCache::DepIterator start;
4813 pkgCache::DepIterator end;
4814 dep.GlobOr(start, end); // ++dep
4816 if (!cache->IsImportantDep(end))
4818 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4821 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4823 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4824 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4825 clauses, @"clauses",
4829 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4831 pkgCache::PkgIterator target(start.TargetPkg());
4832 if (target->ProvidesList != 0)
4833 reason = @"missing";
4835 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4837 reason = @"installed";
4838 installed = [NSString stringWithUTF8String:ver.VerStr()];
4839 } else if (!cache[target].CandidateVerIter(cache).end())
4840 reason = @"uninstalled";
4841 else if (target->ProvidesList == 0)
4842 reason = @"uninstallable";
4844 reason = @"virtual";
4847 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4848 [NSString stringWithUTF8String:start.CompType()], @"operator",
4849 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4852 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4853 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4854 version, @"version",
4856 installed, @"installed",
4859 // yes, seriously. (wtf?)
4867 pkgDepCache::StateCache &state(cache[iterator]);
4869 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4871 if (state.NewInstall())
4872 [installs addObject:name];
4873 // XXX: else if (state.Install())
4874 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4875 [reinstalls addObject:name];
4876 // XXX: move before previous if
4877 else if (state.Upgrade())
4878 [upgrades addObject:name];
4879 else if (state.Downgrade())
4880 [downgrades addObject:name];
4881 else if (!state.Delete())
4882 // XXX: _assert(state.Keep());
4884 else if (special_r(name))
4885 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4886 [NSNull null], @"package",
4887 [NSArray arrayWithObjects:
4888 [NSDictionary dictionaryWithObjectsAndKeys:
4889 @"Conflicts", @"relationship",
4890 [NSArray arrayWithObjects:
4891 [NSDictionary dictionaryWithObjectsAndKeys:
4893 [NSNull null], @"version",
4894 @"installed", @"reason",
4901 if ([package essential])
4903 [removes addObject:name];
4906 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4907 substrate_ |= DepSubstrate(iterator.CurrentVer());
4912 else if (Advanced_) {
4913 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4915 essential_ = [[[UIAlertView alloc]
4916 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4917 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4919 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4921 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4925 [essential_ setContext:@"remove"];
4927 essential_ = [[[UIAlertView alloc]
4928 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4929 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4931 cancelButtonTitle:UCLocalize("OKAY")
4932 otherButtonTitles:nil
4935 [essential_ setContext:@"unable"];
4938 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4939 installs, @"installs",
4940 reinstalls, @"reinstalls",
4941 upgrades, @"upgrades",
4942 downgrades, @"downgrades",
4943 removes, @"removes",
4946 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4947 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4948 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4951 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4955 - (UIBarButtonItem *) leftButton {
4956 return [[[UIBarButtonItem alloc]
4957 initWithTitle:UCLocalize("CANCEL")
4958 style:UIBarButtonItemStylePlain
4960 action:@selector(cancelButtonClicked)
4965 - (void) applyRightButton {
4966 if ([issues_ count] == 0 && ![self isLoading])
4967 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4968 initWithTitle:UCLocalize("CONFIRM")
4969 style:UIBarButtonItemStyleDone
4971 action:@selector(confirmButtonClicked)
4974 [[self navigationItem] setRightBarButtonItem:nil];
4978 - (void) cancelButtonClicked {
4979 [self dismissModalViewControllerAnimated:YES];
4980 [delegate_ cancelAndClear:YES];
4984 - (void) confirmButtonClicked {
4985 if (essential_ != nil)
4995 /* Progress Data {{{ */
4996 @interface CydiaProgressData : NSObject {
4997 _transient id delegate_;
5006 _H<NSMutableArray> events_;
5007 _H<NSString> title_;
5009 _H<NSString> status_;
5010 _H<NSString> finish_;
5015 @implementation CydiaProgressData
5017 + (NSArray *) _attributeKeys {
5018 return [NSArray arrayWithObjects:
5030 - (NSArray *) attributeKeys {
5031 return [[self class] _attributeKeys];
5034 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5035 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5039 if ((self = [super init]) != nil) {
5040 events_ = [NSMutableArray arrayWithCapacity:32];
5044 - (void) setDelegate:(id)delegate {
5045 delegate_ = delegate;
5048 - (void) setPercent:(float)value {
5052 - (NSNumber *) percent {
5053 return [NSNumber numberWithFloat:percent_];
5056 - (void) setCurrent:(float)value {
5060 - (NSNumber *) current {
5061 return [NSNumber numberWithFloat:current_];
5064 - (void) setTotal:(float)value {
5068 - (NSNumber *) total {
5069 return [NSNumber numberWithFloat:total_];
5072 - (void) setSpeed:(float)value {
5076 - (NSNumber *) speed {
5077 return [NSNumber numberWithFloat:speed_];
5080 - (NSArray *) events {
5084 - (void) removeAllEvents {
5085 [events_ removeAllObjects];
5088 - (void) addEvent:(CydiaProgressEvent *)event {
5089 [events_ addObject:event];
5092 - (void) setTitle:(NSString *)text {
5096 - (NSString *) title {
5100 - (void) setFinish:(NSString *)text {
5104 - (NSString *) finish {
5105 return (id) finish_ ?: [NSNull null];
5108 - (void) setRunning:(bool)running {
5112 - (NSNumber *) running {
5113 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5118 /* Progress Controller {{{ */
5119 @interface ProgressController : CydiaWebViewController <
5122 _transient Database *database_;
5123 _H<CydiaProgressData, 1> progress_;
5127 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5129 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5131 - (void) setTitle:(NSString *)title;
5132 - (void) setCancellable:(bool)cancellable;
5136 @implementation ProgressController
5139 [database_ setProgressDelegate:nil];
5143 - (UIBarButtonItem *) leftButton {
5144 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5145 initWithTitle:UCLocalize("CANCEL")
5146 style:UIBarButtonItemStylePlain
5148 action:@selector(cancel)
5149 ] autorelease] : nil;
5152 - (void) updateCancel {
5153 [super applyLeftButton];
5156 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5157 if ((self = [super init]) != nil) {
5158 database_ = database;
5159 delegate_ = delegate;
5161 [database_ setProgressDelegate:self];
5163 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5164 [progress_ setDelegate:self];
5166 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5168 [scroller_ setBackgroundColor:[UIColor blackColor]];
5170 [[self navigationItem] setHidesBackButton:YES];
5172 [self updateCancel];
5176 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5177 [super webView:view didClearWindowObject:window forFrame:frame];
5178 [window setValue:progress_ forKey:@"cydiaProgress"];
5181 - (void) updateProgress {
5182 [self dispatchEvent:@"CydiaProgressUpdate"];
5185 - (void) viewWillAppear:(BOOL)animated {
5186 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5187 [super viewWillAppear:animated];
5191 UpdateExternalStatus(0);
5194 [delegate_ saveState];
5198 [delegate_ returnToCydia];
5202 [delegate_ terminateWithSuccess];
5203 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5204 [delegate_ suspendWithAnimation:YES];
5206 [delegate_ suspend];*/
5218 system("/usr/bin/sbreload");
5224 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5225 SBReboot(SBSSpringBoardServerPort());
5227 reboot2(RB_AUTOBOOT);
5234 - (void) setTitle:(NSString *)title {
5235 [progress_ setTitle:title];
5236 [self updateProgress];
5239 - (UIBarButtonItem *) rightButton {
5240 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5241 initWithTitle:UCLocalize("CLOSE")
5242 style:UIBarButtonItemStylePlain
5244 action:@selector(close)
5248 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5249 UpdateExternalStatus(1);
5251 [progress_ setRunning:true];
5252 [self setTitle:title];
5253 // implicit updateProgress
5255 SHA1SumValue notifyconf; {
5257 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5260 MMap mmap(file, MMap::ReadOnly);
5262 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5263 notifyconf = sha1.Result();
5267 SHA1SumValue springlist; {
5269 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5272 MMap mmap(file, MMap::ReadOnly);
5274 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5275 springlist = sha1.Result();
5279 if (invocation != nil) {
5280 [invocation yieldToSelector:@selector(invoke)];
5281 [self setTitle:@"COMPLETE"];
5286 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5289 MMap mmap(file, MMap::ReadOnly);
5291 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5292 if (!(notifyconf == sha1.Result()))
5299 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5302 MMap mmap(file, MMap::ReadOnly);
5304 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5305 if (!(springlist == sha1.Result()))
5311 if (RestartSubstrate_)
5315 RestartSubstrate_ = false;
5318 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5319 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5320 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5321 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5322 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5326 system("su -c /usr/bin/uicache mobile");
5329 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5331 [progress_ setRunning:false];
5332 [self updateProgress];
5334 [self applyRightButton];
5337 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5338 [progress_ addEvent:event];
5339 [self updateProgress];
5342 - (bool) isProgressCancelled {
5343 return cancel_ == 2;
5348 [self updateCancel];
5351 - (void) setCancellable:(bool)cancellable {
5352 unsigned cancel(cancel_);
5356 else if (cancel_ == 0)
5359 if (cancel != cancel_)
5360 [self updateCancel];
5363 - (void) setProgressCancellable:(NSNumber *)cancellable {
5364 [self setCancellable:[cancellable boolValue]];
5367 - (void) setProgressPercent:(NSNumber *)percent {
5368 [progress_ setPercent:[percent floatValue]];
5369 [self updateProgress];
5372 - (void) setProgressStatus:(NSDictionary *)status {
5373 if (status == nil) {
5374 [progress_ setCurrent:0];
5375 [progress_ setTotal:0];
5376 [progress_ setSpeed:0];
5378 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5380 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5381 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5382 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5385 [self updateProgress];
5391 /* Package Cell {{{ */
5392 @interface PackageCell : CyteTableViewCell <
5393 CyteTableViewCellDelegate
5397 _H<NSString> description_;
5399 _H<NSString> source_;
5401 _H<UIImage> placard_;
5405 - (PackageCell *) init;
5406 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5408 - (void) drawContentRect:(CGRect)rect;
5412 @implementation PackageCell
5414 - (PackageCell *) init {
5415 CGRect frame(CGRectMake(0, 0, 320, 74));
5416 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5417 UIView *content([self contentView]);
5418 CGRect bounds([content bounds]);
5420 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5421 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5422 [content addSubview:content_];
5424 [content_ setDelegate:self];
5425 [content_ setOpaque:YES];
5429 - (NSString *) accessibilityLabel {
5430 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5433 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5434 summarized_ = summary;
5444 [content_ setBackgroundColor:[UIColor whiteColor]];
5448 Source *source = [package source];
5450 icon_ = [package icon];
5452 if (NSString *name = [package name])
5453 name_ = [NSString stringWithString:name];
5455 NSString *description(nil);
5457 if (description == nil && IsWildcat_)
5458 description = [package longDescription];
5459 if (description == nil)
5460 description = [package shortDescription];
5462 if (description != nil)
5463 description_ = [NSString stringWithString:description];
5465 commercial_ = [package isCommercial];
5467 NSString *label = nil;
5468 bool trusted = false;
5470 if (source != nil) {
5471 label = [source label];
5472 trusted = [source trusted];
5473 } else if ([[package id] isEqualToString:@"firmware"])
5474 label = UCLocalize("APPLE");
5476 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5478 NSString *from(label);
5480 NSString *section = [package simpleSection];
5481 if (section != nil && ![section isEqualToString:label]) {
5482 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5483 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5486 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5488 if (NSString *purpose = [package primaryPurpose])
5489 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5494 if (NSString *mode = [package mode]) {
5495 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5496 color = RemovingColor_;
5497 //placard = @"removing";
5499 color = InstallingColor_;
5500 //placard = @"installing";
5503 // XXX: the removing/installing placards are not @2x
5506 color = [UIColor whiteColor];
5508 if ([package installed] != nil)
5509 placard = @"installed";
5514 [content_ setBackgroundColor:color];
5517 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5520 [self setNeedsDisplay];
5521 [content_ setNeedsDisplay];
5524 - (void) drawSummaryContentRect:(CGRect)rect {
5525 bool highlighted(highlighted_);
5526 float width([self bounds].size.width);
5530 rect.size = [(UIImage *) icon_ size];
5532 rect.size.width /= 4;
5533 rect.size.height /= 4;
5535 rect.origin.x = 14 - rect.size.width / 4;
5536 rect.origin.y = 14 - rect.size.height / 4;
5538 [icon_ drawInRect:rect];
5541 if (badge_ != nil) {
5543 rect.size = [(UIImage *) badge_ size];
5545 rect.size.width /= 4;
5546 rect.size.height /= 4;
5548 rect.origin.x = 20 - rect.size.width / 4;
5549 rect.origin.y = 20 - rect.size.height / 4;
5551 [badge_ drawInRect:rect];
5558 UISetColor(commercial_ ? Purple_ : Black_);
5559 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5561 if (placard_ != nil)
5562 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5565 - (void) drawNormalContentRect:(CGRect)rect {
5566 bool highlighted(highlighted_);
5567 float width([self bounds].size.width);
5571 rect.size = [(UIImage *) icon_ size];
5573 rect.size.width /= 2;
5574 rect.size.height /= 2;
5576 rect.origin.x = 25 - rect.size.width / 2;
5577 rect.origin.y = 25 - rect.size.height / 2;
5579 [icon_ drawInRect:rect];
5582 if (badge_ != nil) {
5584 rect.size = [(UIImage *) badge_ size];
5586 rect.size.width /= 2;
5587 rect.size.height /= 2;
5589 rect.origin.x = 36 - rect.size.width / 2;
5590 rect.origin.y = 36 - rect.size.height / 2;
5592 [badge_ drawInRect:rect];
5599 UISetColor(commercial_ ? Purple_ : Black_);
5600 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5601 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5604 UISetColor(commercial_ ? Purplish_ : Gray_);
5605 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5607 if (placard_ != nil)
5608 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5611 - (void) drawContentRect:(CGRect)rect {
5613 [self drawSummaryContentRect:rect];
5615 [self drawNormalContentRect:rect];
5620 /* Section Cell {{{ */
5621 @interface SectionCell : CyteTableViewCell <
5622 CyteTableViewCellDelegate
5624 _H<NSString> basic_;
5625 _H<NSString> section_;
5627 _H<NSString> count_;
5629 _H<UISwitch> switch_;
5633 - (void) setSection:(Section *)section editing:(BOOL)editing;
5637 @implementation SectionCell
5639 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5640 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5641 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5642 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5643 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5645 UIView *content([self contentView]);
5646 CGRect bounds([content bounds]);
5648 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5649 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5650 [content addSubview:content_];
5651 [content_ setBackgroundColor:[UIColor whiteColor]];
5653 [content_ setDelegate:self];
5657 - (void) onSwitch:(id)sender {
5658 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5659 if (metadata == nil) {
5660 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5661 [Sections_ setObject:metadata forKey:basic_];
5664 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5668 - (void) setSection:(Section *)section editing:(BOOL)editing {
5669 if (editing != editing_) {
5671 [switch_ removeFromSuperview];
5673 [self addSubview:switch_];
5682 if (section == nil) {
5683 name_ = UCLocalize("ALL_PACKAGES");
5686 basic_ = [section name];
5687 section_ = [section localized];
5689 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5690 count_ = [NSString stringWithFormat:@"%d", [section count]];
5693 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5696 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5697 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5699 [content_ setNeedsDisplay];
5702 - (void) setFrame:(CGRect)frame {
5703 [super setFrame:frame];
5705 CGRect rect([switch_ frame]);
5706 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5709 - (NSString *) accessibilityLabel {
5713 - (void) drawContentRect:(CGRect)rect {
5714 bool highlighted(highlighted_ && !editing_);
5716 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5721 float width(rect.size.width);
5727 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5729 CGSize size = [count_ sizeWithFont:Font14_];
5733 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5739 /* File Table {{{ */
5740 @interface FileTable : CyteViewController <
5741 UITableViewDataSource,
5744 _transient Database *database_;
5745 _H<Package> package_;
5747 _H<NSMutableArray> files_;
5748 _H<UITableView, 2> list_;
5751 - (id) initWithDatabase:(Database *)database;
5752 - (void) setPackage:(Package *)package;
5756 @implementation FileTable
5758 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5759 return files_ == nil ? 0 : [files_ count];
5762 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5766 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5767 static NSString *reuseIdentifier = @"Cell";
5769 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5771 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5772 [cell setFont:[UIFont systemFontOfSize:16]];
5774 [cell setText:[files_ objectAtIndex:indexPath.row]];
5775 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5780 - (NSURL *) navigationURL {
5781 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5785 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5787 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5788 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5789 [list_ setRowHeight:24.0f];
5790 [(UITableView *) list_ setDataSource:self];
5791 [list_ setDelegate:self];
5792 [[self view] addSubview:list_];
5795 - (void) viewDidLoad {
5796 [super viewDidLoad];
5798 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5801 - (void) releaseSubviews {
5807 [super releaseSubviews];
5810 - (id) initWithDatabase:(Database *)database {
5811 if ((self = [super init]) != nil) {
5812 database_ = database;
5816 - (void) setPackage:(Package *)package {
5820 files_ = [NSMutableArray arrayWithCapacity:32];
5822 if (package != nil) {
5824 name_ = [package id];
5826 if (NSArray *files = [package files])
5827 [files_ addObjectsFromArray:files];
5829 if ([files_ count] != 0) {
5830 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5831 [files_ removeObjectAtIndex:0];
5832 [files_ sortUsingSelector:@selector(compareByPath:)];
5834 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5835 [stack addObject:@"/"];
5837 for (int i(0), e([files_ count]); i != e; ++i) {
5838 NSString *file = [files_ objectAtIndex:i];
5839 while (![file hasPrefix:[stack lastObject]])
5840 [stack removeLastObject];
5841 NSString *directory = [stack lastObject];
5842 [stack addObject:[file stringByAppendingString:@"/"]];
5843 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5844 ([stack count] - 2) * 3, "",
5845 [file substringFromIndex:[directory length]]
5854 - (void) reloadData {
5857 [self setPackage:[database_ packageWithName:name_]];
5862 /* Package Controller {{{ */
5863 @interface CYPackageController : CydiaWebViewController <
5864 UIActionSheetDelegate
5866 _transient Database *database_;
5867 _H<Package> package_;
5870 _H<NSMutableArray> buttons_;
5871 _H<UIBarButtonItem> button_;
5874 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5878 @implementation CYPackageController
5880 - (NSURL *) navigationURL {
5881 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5884 /* XXX: this is not safe at all... localization of /fail/ */
5885 - (void) _clickButtonWithName:(NSString *)name {
5886 if ([name isEqualToString:UCLocalize("CLEAR")])
5887 [delegate_ clearPackage:package_];
5888 else if ([name isEqualToString:UCLocalize("INSTALL")])
5889 [delegate_ installPackage:package_];
5890 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5891 [delegate_ installPackage:package_];
5892 else if ([name isEqualToString:UCLocalize("REMOVE")])
5893 [delegate_ removePackage:package_];
5894 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5895 [delegate_ installPackage:package_];
5896 else _assert(false);
5899 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5900 NSString *context([sheet context]);
5902 if ([context isEqualToString:@"modify"]) {
5903 if (button != [sheet cancelButtonIndex]) {
5904 NSString *buttonName = [buttons_ objectAtIndex:button];
5905 [self _clickButtonWithName:buttonName];
5908 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5912 - (bool) _allowJavaScriptPanel {
5917 - (void) _customButtonClicked {
5918 int count([buttons_ count]);
5923 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5925 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5926 [buttons addObjectsFromArray:buttons_];
5928 UIActionSheet *sheet = [[[UIActionSheet alloc]
5931 cancelButtonTitle:nil
5932 destructiveButtonTitle:nil
5933 otherButtonTitles:nil
5936 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5938 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5939 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5941 [sheet setContext:@"modify"];
5943 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5947 // We don't want to allow non-commercial packages to do custom things to the install button,
5948 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5949 - (void) customButtonClicked {
5951 [super customButtonClicked];
5953 [self _customButtonClicked];
5956 - (void) reloadButtonClicked {
5957 // Don't reload a commerical package by tapping the loading button,
5958 // but if it's not an Install button, we should forward it on.
5959 if (![package_ uninstalled])
5960 [self _customButtonClicked];
5963 - (void) applyLoadingTitle {
5964 // Don't show "Loading" as the title. Ever.
5967 - (UIBarButtonItem *) rightButton {
5972 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5973 if ((self = [super init]) != nil) {
5974 database_ = database;
5975 buttons_ = [NSMutableArray arrayWithCapacity:4];
5976 name_ = name == nil ? @"" : [NSString stringWithString:name];
5977 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5981 - (void) reloadData {
5984 package_ = [database_ packageWithName:name_];
5986 [buttons_ removeAllObjects];
5988 if (package_ != nil) {
5989 [(Package *) package_ parse];
5991 commercial_ = [package_ isCommercial];
5993 if ([package_ mode] != nil)
5994 [buttons_ addObject:UCLocalize("CLEAR")];
5995 if ([package_ source] == nil);
5996 else if ([package_ upgradableAndEssential:NO])
5997 [buttons_ addObject:UCLocalize("UPGRADE")];
5998 else if ([package_ uninstalled])
5999 [buttons_ addObject:UCLocalize("INSTALL")];
6001 [buttons_ addObject:UCLocalize("REINSTALL")];
6002 if (![package_ uninstalled])
6003 [buttons_ addObject:UCLocalize("REMOVE")];
6007 switch ([buttons_ count]) {
6008 case 0: title = nil; break;
6009 case 1: title = [buttons_ objectAtIndex:0]; break;
6010 default: title = UCLocalize("MODIFY"); break;
6013 button_ = [[[UIBarButtonItem alloc]
6015 style:UIBarButtonItemStylePlain
6017 action:@selector(customButtonClicked)
6021 - (bool) isLoading {
6022 return commercial_ ? [super isLoading] : false;
6028 /* Package List Controller {{{ */
6029 @interface PackageListController : CyteViewController <
6030 UITableViewDataSource,
6033 _transient Database *database_;
6035 _H<NSArray> packages_;
6036 _H<NSMutableArray> sections_;
6037 _H<UITableView, 2> list_;
6038 _H<NSMutableArray> index_;
6039 _H<NSMutableDictionary> indices_;
6040 _H<NSString> title_;
6041 unsigned reloading_;
6044 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6045 - (void) setDelegate:(id)delegate;
6046 - (void) resetCursor;
6051 @implementation PackageListController
6053 - (bool) isSummarized {
6057 - (bool) showsSections {
6061 - (void) deselectWithAnimation:(BOOL)animated {
6062 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6065 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6066 CGRect base = [[self view] bounds];
6067 base.size.height -= bounds.size.height;
6068 base.origin = [list_ frame].origin;
6070 [UIView beginAnimations:nil context:NULL];
6071 [UIView setAnimationBeginsFromCurrentState:YES];
6072 [UIView setAnimationCurve:curve];
6073 [UIView setAnimationDuration:duration];
6074 [list_ setFrame:base];
6075 [UIView commitAnimations];
6078 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6079 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6082 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6083 [self resizeForKeyboardBounds:bounds duration:0];
6086 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6087 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6088 *curve = UIViewAnimationCurveEaseInOut;
6090 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6092 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6095 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6098 - (void) keyboardWillShow:(NSNotification *)notification {
6101 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6102 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6104 NSTimeInterval duration;
6105 UIViewAnimationCurve curve;
6106 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6108 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);
6109 UIViewController *base = self;
6110 while ([base parentViewController] != nil)
6111 base = [base parentViewController];
6112 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6113 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6115 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6116 intersection.size.height += CYStatusBarHeight();
6118 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6121 - (void) keyboardWillHide:(NSNotification *)notification {
6122 NSTimeInterval duration;
6123 UIViewAnimationCurve curve;
6124 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6126 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6129 - (void) viewWillAppear:(BOOL)animated {
6130 [super viewWillAppear:animated];
6132 [self resizeForKeyboardBounds:CGRectZero];
6133 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6134 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6137 - (void) viewWillDisappear:(BOOL)animated {
6138 [super viewWillDisappear:animated];
6140 [self resizeForKeyboardBounds:CGRectZero];
6141 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6142 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6145 - (void) viewDidAppear:(BOOL)animated {
6146 [super viewDidAppear:animated];
6147 [self deselectWithAnimation:animated];
6150 - (void) didSelectPackage:(Package *)package {
6151 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6152 [view setDelegate:delegate_];
6153 [[self navigationController] pushViewController:view animated:YES];
6156 #if TryIndexedCollation
6157 + (BOOL) hasIndexedCollation {
6158 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6162 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6163 NSInteger count([sections_ count]);
6164 return count == 0 ? 1 : count;
6167 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6168 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6170 return [[sections_ objectAtIndex:section] name];
6173 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6174 if ([sections_ count] == 0)
6176 return [[sections_ objectAtIndex:section] count];
6179 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6180 @synchronized (database_) {
6181 if ([database_ era] != era_)
6184 Section *section([sections_ objectAtIndex:[path section]]);
6185 NSInteger row([path row]);
6186 Package *package([packages_ objectAtIndex:([section row] + row)]);
6187 return [[package retain] autorelease];
6190 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6191 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6193 cell = [[[PackageCell alloc] init] autorelease];
6195 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6196 [cell setPackage:package asSummary:[self isSummarized]];
6200 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6201 Package *package([self packageAtIndexPath:path]);
6202 package = [database_ packageWithName:[package id]];
6203 [self didSelectPackage:package];
6206 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6207 if (![self showsSections])
6213 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6214 #if TryIndexedCollation
6215 if ([[self class] hasIndexedCollation]) {
6216 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6223 - (void) updateHeight {
6224 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6227 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6228 if ((self = [super init]) != nil) {
6229 database_ = database;
6230 title_ = [title copy];
6231 [[self navigationItem] setTitle:title_];
6236 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6238 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6239 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6240 [[self view] addSubview:list_];
6242 // XXX: is 20 the most optimal number here?
6243 [list_ setSectionIndexMinimumDisplayRowCount:20];
6245 [(UITableView *) list_ setDataSource:self];
6246 [list_ setDelegate:self];
6248 [self updateHeight];
6251 - (void) releaseSubviews {
6259 [super releaseSubviews];
6262 - (void) setDelegate:(id)delegate {
6263 delegate_ = delegate;
6266 - (bool) shouldYield {
6270 - (bool) shouldBlock {
6274 - (NSMutableArray *) _reloadPackages {
6275 @synchronized (database_) {
6276 era_ = [database_ era];
6277 NSArray *packages([database_ packages]);
6279 return [NSMutableArray arrayWithArray:packages];
6282 - (void) _reloadData {
6283 if (reloading_ != 0) {
6290 if ([self shouldYield]) {
6294 if (![self shouldBlock])
6297 hud = [delegate_ addProgressHUD];
6298 [hud setText:UCLocalize("LOADING")];
6302 packages = [self yieldToSelector:@selector(_reloadPackages)];
6305 [delegate_ removeProgressHUD:hud];
6306 } while (reloading_ == 2);
6310 packages = [self _reloadPackages];
6313 packages_ = packages;
6315 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6316 sections_ = [NSMutableArray arrayWithCapacity:16];
6318 Section *section = nil;
6320 #if TryIndexedCollation
6321 if ([[self class] hasIndexedCollation]) {
6322 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6324 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6325 NSArray *titles = [collation sectionIndexTitles];
6328 _profile(PackageTable$reloadData$Section)
6329 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6333 _profile(PackageTable$reloadData$Section$Package)
6334 package = [packages_ objectAtIndex:offset];
6335 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6338 while (secidx < index) {
6341 _profile(PackageTable$reloadData$Section$Allocate)
6342 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6345 _profile(PackageTable$reloadData$Section$Add)
6346 [sections_ addObject:section];
6350 [section addToCount];
6356 index_ = [NSMutableArray arrayWithCapacity:32];
6358 bool sectioned([self showsSections]);
6360 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6361 [sections_ addObject:section];
6364 _profile(PackageTable$reloadData$Section)
6365 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6369 _profile(PackageTable$reloadData$Section$Package)
6370 package = [packages_ objectAtIndex:offset];
6371 index = [package index];
6374 if (sectioned && (section == nil || [section index] != index)) {
6375 _profile(PackageTable$reloadData$Section$Allocate)
6376 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6379 [index_ addObject:[section name]];
6380 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6382 _profile(PackageTable$reloadData$Section$Add)
6383 [sections_ addObject:section];
6387 [section addToCount];
6392 [self updateHeight];
6394 _profile(PackageTable$reloadData$List)
6395 [(UITableView *) list_ setDataSource:self];
6400 - (void) reloadData {
6403 if ([self shouldYield])
6404 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6409 - (void) resetCursor {
6410 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6413 - (void) clearData {
6414 [self updateHeight];
6416 [list_ setDataSource:nil];
6424 /* Filtered Package List Controller {{{ */
6425 @interface FilteredPackageListController : PackageListController {
6428 _H<NSObject> object_;
6431 - (void) setObject:(id)object;
6432 - (void) setObject:(id)object forFilter:(SEL)filter;
6435 - (void) setFilter:(SEL)filter;
6437 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6441 @implementation FilteredPackageListController
6447 - (void) setFilter:(SEL)filter {
6448 @synchronized (self) {
6451 /* XXX: this is an unsafe optimization of doomy hell */
6452 Method method(class_getInstanceMethod([Package class], filter));
6453 _assert(method != NULL);
6454 imp_ = method_getImplementation(method);
6455 _assert(imp_ != NULL);
6458 - (void) setObject:(id)object {
6459 @synchronized (self) {
6463 - (void) setObject:(id)object forFilter:(SEL)filter {
6464 @synchronized (self) {
6465 [self setFilter:filter];
6466 [self setObject:object];
6469 - (NSMutableArray *) _reloadPackages {
6470 @synchronized (database_) {
6471 era_ = [database_ era];
6472 NSArray *packages([database_ packages]);
6474 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6478 _H<NSObject> object;
6480 @synchronized (self) {
6486 _profile(PackageTable$reloadData$Filter)
6487 for (Package *package in packages)
6488 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6489 [filtered addObject:package];
6495 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6496 if ((self = [super initWithDatabase:database title:title]) != nil) {
6497 [self setFilter:filter];
6498 [self setObject:object];
6505 /* Home Controller {{{ */
6506 @interface HomeController : CydiaWebViewController {
6511 @implementation HomeController
6514 if ((self = [super init]) != nil) {
6515 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6520 - (NSURL *) navigationURL {
6521 return [NSURL URLWithString:@"cydia://home"];
6524 - (void) didReceiveMemoryWarning {
6527 - (void) aboutButtonClicked {
6528 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6530 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6531 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6532 [alert setCancelButtonIndex:0];
6535 @"Copyright \u00a9 2008-2011\n"
6538 "Jay Freeman (saurik)\n"
6539 "saurik@saurik.com\n"
6540 "http://www.saurik.com/"
6546 - (UIBarButtonItem *) leftButton {
6547 return [[[UIBarButtonItem alloc]
6548 initWithTitle:UCLocalize("ABOUT")
6549 style:UIBarButtonItemStylePlain
6551 action:@selector(aboutButtonClicked)
6557 /* Manage Controller {{{ */
6558 @interface ManageController : CydiaWebViewController {
6561 - (void) queueStatusDidChange;
6565 @implementation ManageController
6568 if ((self = [super init]) != nil) {
6569 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6573 - (NSURL *) navigationURL {
6574 return [NSURL URLWithString:@"cydia://manage"];
6577 - (UIBarButtonItem *) leftButton {
6578 return [[[UIBarButtonItem alloc]
6579 initWithTitle:UCLocalize("SETTINGS")
6580 style:UIBarButtonItemStylePlain
6582 action:@selector(settingsButtonClicked)
6586 - (void) settingsButtonClicked {
6587 [delegate_ showSettings];
6590 - (void) queueButtonClicked {
6594 - (UIBarButtonItem *) customButton {
6595 return Queuing_ ? [[[UIBarButtonItem alloc]
6596 initWithTitle:UCLocalize("QUEUE")
6597 style:UIBarButtonItemStyleDone
6599 action:@selector(queueButtonClicked)
6600 ] autorelease] : [super customButton];
6603 - (void) queueStatusDidChange {
6604 [self applyRightButton];
6607 - (bool) isLoading {
6608 return !Queuing_ && [super isLoading];
6614 /* Refresh Bar {{{ */
6615 @interface RefreshBar : UINavigationBar {
6616 _H<UIProgressIndicator> indicator_;
6617 _H<UITextLabel> prompt_;
6618 _H<UIProgressBar> progress_;
6619 _H<UINavigationButton> cancel_;
6624 @implementation RefreshBar
6626 - (void) positionViews {
6627 CGRect frame = [cancel_ frame];
6628 frame.size = [cancel_ sizeThatFits:frame.size];
6629 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6630 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6631 [cancel_ setFrame:frame];
6633 CGSize prgsize = {75, 100};
6635 [self frame].size.width - prgsize.width - 10,
6636 ([self frame].size.height - prgsize.height) / 2
6638 [progress_ setFrame:prgrect];
6640 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6641 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6642 CGRect indrect = {{indoffset, indoffset}, indsize};
6643 [indicator_ setFrame:indrect];
6645 CGSize prmsize = {215, indsize.height + 4};
6647 indoffset * 2 + indsize.width,
6648 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6650 [prompt_ setFrame:prmrect];
6653 - (void) setFrame:(CGRect)frame {
6654 [super setFrame:frame];
6655 [self positionViews];
6658 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6659 if ((self = [super initWithFrame:frame]) != nil) {
6660 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6662 [self setBarStyle:UIBarStyleBlack];
6664 UIBarStyle barstyle([self _barStyle:NO]);
6665 bool ugly(barstyle == UIBarStyleDefault);
6667 UIProgressIndicatorStyle style = ugly ?
6668 UIProgressIndicatorStyleMediumBrown :
6669 UIProgressIndicatorStyleMediumWhite;
6671 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6672 [(UIProgressIndicator *) indicator_ setStyle:style];
6673 [indicator_ startAnimation];
6674 [self addSubview:indicator_];
6676 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6677 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6678 [prompt_ setBackgroundColor:[UIColor clearColor]];
6679 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6680 [self addSubview:prompt_];
6682 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6683 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6684 [(UIProgressBar *) progress_ setStyle:0];
6685 [self addSubview:progress_];
6687 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6688 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6689 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6690 [cancel_ setBarStyle:barstyle];
6692 [self positionViews];
6696 - (void) setCancellable:(bool)cancellable {
6698 [self addSubview:cancel_];
6700 [cancel_ removeFromSuperview];
6704 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6705 [progress_ setProgress:0];
6709 [self setCancellable:NO];
6712 - (void) setPrompt:(NSString *)prompt {
6713 [prompt_ setText:prompt];
6716 - (void) setProgress:(float)progress {
6717 [progress_ setProgress:progress];
6723 /* Cydia Navigation Controller Interface {{{ */
6724 @interface UINavigationController (Cydia)
6726 - (NSArray *) navigationURLCollection;
6727 - (void) unloadData;
6732 /* Cydia Tab Bar Controller {{{ */
6733 @interface CYTabBarController : UITabBarController <
6734 UITabBarControllerDelegate,
6737 _transient Database *database_;
6738 _H<RefreshBar, 1> refreshbar_;
6742 // XXX: ok, "updatedelegate_"?...
6743 _transient NSObject<CydiaDelegate> *updatedelegate_;
6745 _H<UIViewController> remembered_;
6746 _transient UIViewController *transient_;
6749 - (NSArray *) navigationURLCollection;
6750 - (void) dropBar:(BOOL)animated;
6751 - (void) beginUpdate;
6752 - (void) raiseBar:(BOOL)animated;
6754 - (void) unloadData;
6758 @implementation CYTabBarController
6760 - (void) setUnselectedViewController:(UIViewController *)transient {
6761 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6762 if (transient != nil) {
6763 if (transient_ == nil)
6764 remembered_ = [controllers objectAtIndex:0];
6765 transient_ = transient;
6766 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6767 [controllers replaceObjectAtIndex:0 withObject:transient_];
6768 [self setSelectedIndex:0];
6769 [self setViewControllers:controllers];
6770 [self concealTabBarSelection];
6771 } else if (remembered_ != nil) {
6772 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6773 transient_ = transient;
6774 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6776 [self setViewControllers:controllers];
6777 [self revealTabBarSelection];
6781 - (UIViewController *) unselectedViewController {
6785 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6786 if ([self unselectedViewController])
6787 [self setUnselectedViewController:nil];
6790 - (NSArray *) navigationURLCollection {
6791 NSMutableArray *items([NSMutableArray array]);
6793 // XXX: Should this deal with transient view controllers?
6794 for (id navigation in [self viewControllers]) {
6795 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6797 [items addObject:stack];
6803 - (void) unloadData {
6806 for (UINavigationController *controller in [self viewControllers])
6807 [controller unloadData];
6809 if (UIViewController *selected = [self selectedViewController])
6810 [selected reloadData];
6812 if (UIViewController *unselected = [self unselectedViewController]) {
6813 [unselected unloadData];
6814 [unselected reloadData];
6819 [[NSNotificationCenter defaultCenter] removeObserver:self];
6824 - (id) initWithDatabase:(Database *)database {
6825 if ((self = [super init]) != nil) {
6826 database_ = database;
6827 [self setDelegate:self];
6829 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6830 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6832 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6836 - (void) setUpdate:(NSDate *)date {
6840 - (void) beginUpdate {
6841 [(RefreshBar *) refreshbar_ start];
6844 [updatedelegate_ retainNetworkActivityIndicator];
6848 detachNewThreadSelector:@selector(performUpdate)
6854 - (void) performUpdate {
6855 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6858 status.setDelegate(self);
6859 [database_ updateWithStatus:status];
6862 performSelectorOnMainThread:@selector(completeUpdate)
6870 - (void) stopUpdateWithSelector:(SEL)selector {
6872 [updatedelegate_ releaseNetworkActivityIndicator];
6874 [self raiseBar:YES];
6877 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6880 - (void) completeUpdate {
6883 [self stopUpdateWithSelector:@selector(reloadData)];
6886 - (void) cancelUpdate {
6887 [self stopUpdateWithSelector:@selector(updateData)];
6890 - (void) cancelPressed {
6891 [self cancelUpdate];
6898 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6899 [refreshbar_ setPrompt:[event compoundMessage]];
6902 - (bool) isProgressCancelled {
6906 - (void) setProgressCancellable:(NSNumber *)cancellable {
6907 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6910 - (void) setProgressPercent:(NSNumber *)percent {
6911 [refreshbar_ setProgress:[percent floatValue]];
6914 - (void) setProgressStatus:(NSDictionary *)status {
6916 [self setProgressPercent:[status objectForKey:@"Percent"]];
6919 - (void) setUpdateDelegate:(id)delegate {
6920 updatedelegate_ = delegate;
6923 - (UIView *) transitionView {
6924 if ([self respondsToSelector:@selector(_transitionView)])
6925 return [self _transitionView];
6927 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6930 - (void) dropBar:(BOOL)animated {
6935 UIView *transition([self transitionView]);
6936 [[self view] addSubview:refreshbar_];
6938 CGRect barframe([refreshbar_ frame]);
6940 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6941 barframe.origin.y = CYStatusBarHeight();
6943 barframe.origin.y = 0;
6945 [refreshbar_ setFrame:barframe];
6948 [UIView beginAnimations:nil context:NULL];
6950 CGRect viewframe = [transition frame];
6951 viewframe.origin.y += barframe.size.height;
6952 viewframe.size.height -= barframe.size.height;
6953 [transition setFrame:viewframe];
6956 [UIView commitAnimations];
6958 // Ensure bar has the proper width for our view, it might have changed
6959 barframe.size.width = viewframe.size.width;
6960 [refreshbar_ setFrame:barframe];
6963 - (void) raiseBar:(BOOL)animated {
6968 UIView *transition([self transitionView]);
6969 [refreshbar_ removeFromSuperview];
6971 CGRect barframe([refreshbar_ frame]);
6974 [UIView beginAnimations:nil context:NULL];
6976 CGRect viewframe = [transition frame];
6977 viewframe.origin.y -= barframe.size.height;
6978 viewframe.size.height += barframe.size.height;
6979 [transition setFrame:viewframe];
6982 [UIView commitAnimations];
6985 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6986 bool dropped(dropped_);
6991 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6997 - (void) statusBarFrameChanged:(NSNotification *)notification {
7007 /* Cydia Navigation Controller Implementation {{{ */
7008 @implementation UINavigationController (Cydia)
7010 - (NSArray *) navigationURLCollection {
7011 NSMutableArray *stack([NSMutableArray array]);
7013 for (CyteViewController *controller in [self viewControllers]) {
7014 NSString *url = [[controller navigationURL] absoluteString];
7016 [stack addObject:url];
7022 - (void) reloadData {
7025 UIViewController *visible([self visibleViewController]);
7027 [visible reloadData];
7029 // on the iPad, this view controller is ALSO visible. :(
7031 if (UIViewController *top = [self topViewController])
7036 - (void) unloadData {
7037 for (CyteViewController *page in [self viewControllers])
7046 /* Cydia:// Protocol {{{ */
7047 @interface CydiaURLProtocol : NSURLProtocol {
7052 @implementation CydiaURLProtocol
7054 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7055 NSURL *url([request URL]);
7059 NSString *scheme([[url scheme] lowercaseString]);
7060 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7062 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7068 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7072 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7073 id<NSURLProtocolClient> client([self client]);
7075 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7077 NSData *data(UIImagePNGRepresentation(icon));
7079 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7080 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7081 [client URLProtocol:self didLoadData:data];
7082 [client URLProtocolDidFinishLoading:self];
7086 - (void) startLoading {
7087 id<NSURLProtocolClient> client([self client]);
7088 NSURLRequest *request([self request]);
7090 NSURL *url([request URL]);
7091 NSString *href([url absoluteString]);
7092 NSString *scheme([[url scheme] lowercaseString]);
7096 if ([scheme isEqualToString:@"cydia"])
7097 path = [href substringFromIndex:8];
7098 else if ([scheme isEqualToString:@"about"])
7099 path = [href substringFromIndex:12];
7100 else _assert(false);
7102 NSRange slash([path rangeOfString:@"/"]);
7105 if (slash.location == NSNotFound) {
7109 command = [path substringToIndex:slash.location];
7110 path = [path substringFromIndex:(slash.location + 1)];
7113 Database *database([Database sharedInstance]);
7115 if ([command isEqualToString:@"package-icon"]) {
7118 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7119 Package *package([database packageWithName:path]);
7123 UIImage *icon([package icon]);
7124 [self _returnPNGWithImage:icon forRequest:request];
7125 } else if ([command isEqualToString:@"source-icon"]) {
7128 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7129 NSString *source(Simplify(path));
7130 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7132 icon = [UIImage applicationImageNamed:@"unknown.png"];
7133 [self _returnPNGWithImage:icon forRequest:request];
7134 } else if ([command isEqualToString:@"uikit-image"]) {
7137 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7138 UIImage *icon(_UIImageWithName(path));
7139 [self _returnPNGWithImage:icon forRequest:request];
7140 } else if ([command isEqualToString:@"section-icon"]) {
7143 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7144 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7146 icon = [UIImage applicationImageNamed:@"unknown.png"];
7147 [self _returnPNGWithImage:icon forRequest:request];
7149 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7153 - (void) stopLoading {
7159 /* Section Controller {{{ */
7160 @interface SectionController : FilteredPackageListController {
7161 _H<NSString> section_;
7164 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7168 @implementation SectionController
7170 - (NSURL *) navigationURL {
7171 NSString *name = section_;
7175 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7178 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7181 title = UCLocalize("ALL_PACKAGES");
7182 else if (![name isEqual:@""])
7183 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7185 title = UCLocalize("NO_SECTION");
7187 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7194 /* Sections Controller {{{ */
7195 @interface SectionsController : CyteViewController <
7196 UITableViewDataSource,
7199 _transient Database *database_;
7200 _H<NSMutableArray> sections_;
7201 _H<NSMutableArray> filtered_;
7202 _H<UITableView, 2> list_;
7205 - (id) initWithDatabase:(Database *)database;
7206 - (void) editButtonClicked;
7210 @implementation SectionsController
7212 - (NSURL *) navigationURL {
7213 return [NSURL URLWithString:@"cydia://sections"];
7216 - (void) updateNavigationItem {
7217 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7218 if ([sections_ count] == 0) {
7219 [[self navigationItem] setRightBarButtonItem:nil];
7221 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7222 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7224 action:@selector(editButtonClicked)
7225 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7229 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7230 [super setEditing:editing animated:animated];
7235 [delegate_ updateData];
7237 [self updateNavigationItem];
7240 - (void) viewDidAppear:(BOOL)animated {
7241 [super viewDidAppear:animated];
7242 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7245 - (void) viewWillDisappear:(BOOL)animated {
7246 [super viewWillDisappear:animated];
7247 if ([self isEditing]) [self setEditing:NO];
7250 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7251 Section *section = nil;
7252 int index = [indexPath row];
7253 if (![self isEditing]) {
7256 section = [filtered_ objectAtIndex:index];
7258 section = [sections_ objectAtIndex:index];
7263 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7264 if ([self isEditing])
7265 return [sections_ count];
7267 return [filtered_ count] + 1;
7270 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7274 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7275 static NSString *reuseIdentifier = @"SectionCell";
7277 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7279 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7281 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7286 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7287 if ([self isEditing])
7290 Section *section = [self sectionAtIndexPath:indexPath];
7292 SectionController *controller = [[[SectionController alloc]
7293 initWithDatabase:database_
7294 section:[section name]
7296 [controller setDelegate:delegate_];
7298 [[self navigationController] pushViewController:controller animated:YES];
7302 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7304 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7305 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7306 [list_ setRowHeight:45.0f];
7307 [(UITableView *) list_ setDataSource:self];
7308 [list_ setDelegate:self];
7309 [[self view] addSubview:list_];
7312 - (void) viewDidLoad {
7313 [super viewDidLoad];
7315 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7318 - (void) releaseSubviews {
7324 [super releaseSubviews];
7327 - (id) initWithDatabase:(Database *)database {
7328 if ((self = [super init]) != nil) {
7329 database_ = database;
7333 - (void) reloadData {
7336 NSArray *packages = [database_ packages];
7338 sections_ = [NSMutableArray arrayWithCapacity:16];
7339 filtered_ = [NSMutableArray arrayWithCapacity:16];
7341 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7344 for (Package *package in packages) {
7345 NSString *name([package section]);
7346 NSString *key(name == nil ? @"" : name);
7350 _profile(SectionsView$reloadData$Section)
7351 section = [sections objectForKey:key];
7352 if (section == nil) {
7353 _profile(SectionsView$reloadData$Section$Allocate)
7354 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7355 [sections setObject:section forKey:key];
7360 [section addToCount];
7362 _profile(SectionsView$reloadData$Filter)
7363 if (![package valid] || ![package visible])
7371 [sections_ addObjectsFromArray:[sections allValues]];
7373 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7375 for (Section *section in (id) sections_) {
7376 size_t count([section row]);
7380 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7381 [section setCount:count];
7382 [filtered_ addObject:section];
7385 [self updateNavigationItem];
7390 - (void) editButtonClicked {
7391 [self setEditing:![self isEditing] animated:YES];
7397 /* Changes Controller {{{ */
7398 @interface ChangesController : CyteViewController <
7399 UITableViewDataSource,
7402 _transient Database *database_;
7404 _H<NSArray> packages_;
7405 _H<NSMutableArray> sections_;
7406 _H<UITableView, 2> list_;
7410 - (id) initWithDatabase:(Database *)database;
7414 @implementation ChangesController
7416 - (NSURL *) navigationURL {
7417 return [NSURL URLWithString:@"cydia://changes"];
7420 - (void) viewDidAppear:(BOOL)animated {
7421 [super viewDidAppear:animated];
7422 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7425 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7426 NSInteger count([sections_ count]);
7427 return count == 0 ? 1 : count;
7430 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7431 if ([sections_ count] == 0)
7433 return [[sections_ objectAtIndex:section] name];
7436 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7437 if ([sections_ count] == 0)
7439 return [[sections_ objectAtIndex:section] count];
7442 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7443 @synchronized (database_) {
7444 if ([database_ era] != era_)
7447 NSUInteger sectionIndex([path section]);
7448 if (sectionIndex >= [sections_ count])
7450 Section *section([sections_ objectAtIndex:sectionIndex]);
7451 NSInteger row([path row]);
7452 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7455 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7456 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7458 cell = [[[PackageCell alloc] init] autorelease];
7460 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7461 [cell setPackage:package asSummary:false];
7465 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7466 Package *package([self packageAtIndexPath:path]);
7467 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7468 [view setDelegate:delegate_];
7469 [[self navigationController] pushViewController:view animated:YES];
7473 - (void) refreshButtonClicked {
7474 [delegate_ beginUpdate];
7475 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7478 - (void) upgradeButtonClicked {
7479 [delegate_ distUpgrade];
7480 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7484 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7486 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7487 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7488 [list_ setRowHeight:73];
7489 [(UITableView *) list_ setDataSource:self];
7490 [list_ setDelegate:self];
7491 [[self view] addSubview:list_];
7494 - (void) viewDidLoad {
7495 [super viewDidLoad];
7497 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7500 - (void) releaseSubviews {
7506 [super releaseSubviews];
7509 - (id) initWithDatabase:(Database *)database {
7510 if ((self = [super init]) != nil) {
7511 database_ = database;
7515 - (NSMutableArray *) _reloadPackages {
7516 @synchronized (database_) {
7517 era_ = [database_ era];
7518 NSArray *packages([database_ packages]);
7520 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7523 _profile(ChangesController$_reloadPackages$Filter)
7524 for (Package *package in packages)
7525 if ([package upgradableAndEssential:YES] || [package visible])
7526 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7529 _profile(ChangesController$_reloadPackages$radixSort)
7530 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7537 - (void) _reloadData {
7542 UIProgressHUD *hud([delegate_ addProgressHUD]);
7543 [hud setText:UCLocalize("LOADING")];
7544 //NSLog(@"HUD:%@::%@", delegate_, hud);
7545 packages = [self yieldToSelector:@selector(_reloadPackages)];
7546 [delegate_ removeProgressHUD:hud];
7548 packages = [self _reloadPackages];
7551 @synchronized (database_) {
7552 if (era_ != [database_ era])
7555 packages_ = packages;
7556 sections_ = [NSMutableArray arrayWithCapacity:16];
7558 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7559 Section *ignored = nil;
7560 Section *section = nil;
7564 bool unseens = false;
7566 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7568 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7569 Package *package = [packages_ objectAtIndex:offset];
7571 BOOL uae = [package upgradableAndEssential:YES];
7575 time_t seen([package seen]);
7577 if (section == nil || last != seen) {
7581 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7584 _profile(ChangesController$reloadData$Allocate)
7585 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7586 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7587 [sections_ addObject:section];
7591 [section addToCount];
7592 } else if ([package ignored]) {
7593 if (ignored == nil) {
7594 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7596 [ignored addToCount];
7599 [upgradable addToCount];
7604 CFRelease(formatter);
7607 Section *last = [sections_ lastObject];
7608 size_t count = [last count];
7609 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7610 [sections_ removeLastObject];
7613 if ([ignored count] != 0)
7614 [sections_ insertObject:ignored atIndex:0];
7616 [sections_ insertObject:upgradable atIndex:0];
7620 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7621 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7622 style:UIBarButtonItemStylePlain
7624 action:@selector(upgradeButtonClicked)
7625 ] autorelease]) animated:YES];
7627 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7628 initWithTitle:UCLocalize("REFRESH")
7629 style:UIBarButtonItemStylePlain
7631 action:@selector(refreshButtonClicked)
7632 ] autorelease]) animated:YES];
7637 - (void) reloadData {
7639 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7644 /* Search Controller {{{ */
7645 @interface SearchController : FilteredPackageListController <
7648 _H<UISearchBar, 1> search_;
7652 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7653 - (void) reloadData;
7657 @implementation SearchController
7659 - (NSURL *) navigationURL {
7660 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7661 return [NSURL URLWithString:@"cydia://search"];
7663 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7666 - (void) useSearch {
7667 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7672 - (void) viewWillAppear:(BOOL)animated {
7673 [super viewWillAppear:animated];
7675 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7679 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7680 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7685 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7686 [search_ resignFirstResponder];
7690 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7691 [search_ setText:@""];
7692 [self searchBarButtonClicked:searchBar];
7695 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7696 [self searchBarButtonClicked:searchBar];
7699 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7700 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7704 - (bool) shouldYield {
7708 - (bool) shouldBlock {
7709 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7712 - (bool) isSummarized {
7713 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7716 - (bool) showsSections {
7720 - (NSMutableArray *) _reloadPackages {
7721 NSMutableArray *packages([super _reloadPackages]);
7722 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7723 [packages radixSortUsingSelector:@selector(rank)];
7727 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7728 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7729 search_ = [[[UISearchBar alloc] init] autorelease];
7730 [search_ setDelegate:self];
7733 [search_ setText:query];
7737 - (void) viewDidAppear:(BOOL)animated {
7738 [super viewDidAppear:animated];
7740 if (!searchloaded_) {
7741 searchloaded_ = YES;
7742 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7743 [search_ layoutSubviews];
7744 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7746 UITextField *textField;
7747 if ([search_ respondsToSelector:@selector(searchField)])
7748 textField = [search_ searchField];
7750 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7752 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7753 [textField setEnablesReturnKeyAutomatically:NO];
7754 [[self navigationItem] setTitleView:textField];
7758 - (void) reloadData {
7759 id object([search_ text]);
7760 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7761 object = [object componentsSeparatedByString:@" "];
7763 [self setObject:object];
7769 - (void) didSelectPackage:(Package *)package {
7770 [search_ resignFirstResponder];
7771 [super didSelectPackage:package];
7776 /* Package Settings Controller {{{ */
7777 @interface PackageSettingsController : CyteViewController <
7778 UITableViewDataSource,
7781 _transient Database *database_;
7783 _H<Package> package_;
7784 _H<UITableView, 2> table_;
7785 _H<UISwitch> subscribedSwitch_;
7786 _H<UISwitch> ignoredSwitch_;
7787 _H<UITableViewCell> subscribedCell_;
7788 _H<UITableViewCell> ignoredCell_;
7791 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7795 @implementation PackageSettingsController
7797 - (NSURL *) navigationURL {
7798 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7801 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7802 if (package_ == nil)
7805 if ([package_ installed] == nil)
7811 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7812 if (package_ == nil)
7815 // both sections contain just one item right now.
7819 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7823 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7825 return UCLocalize("SHOW_ALL_CHANGES_EX");
7827 return UCLocalize("IGNORE_UPGRADES_EX");
7830 - (void) onSubscribed:(id)control {
7831 bool value([control isOn]);
7832 if (package_ == nil)
7834 if ([package_ setSubscribed:value])
7835 [delegate_ updateData];
7838 - (void) _updateIgnored {
7839 const char *package([name_ UTF8String]);
7840 bool on([ignoredSwitch_ isOn]);
7842 pid_t pid(ExecFork());
7844 FILE *dpkg(popen("dpkg --set-selections", "w"));
7845 fwrite(package, strlen(package), 1, dpkg);
7848 fwrite(" hold\n", 6, 1, dpkg);
7850 fwrite(" install\n", 9, 1, dpkg);
7860 int result(waitpid(pid, &status, 0));
7863 _assert(result == pid);
7869 - (void) onIgnored:(id)control {
7870 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7871 [invocation setTarget:self];
7872 [invocation setSelector:@selector(_updateIgnored)];
7874 [delegate_ reloadDataWithInvocation:invocation];
7877 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7878 if (package_ == nil)
7881 switch ([indexPath section]) {
7882 case 0: return subscribedCell_;
7883 case 1: return ignoredCell_;
7892 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7894 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7895 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7896 [(UITableView *) table_ setDataSource:self];
7897 [table_ setDelegate:self];
7898 [[self view] addSubview:table_];
7900 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7901 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7902 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7904 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7905 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7906 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7908 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7909 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7910 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7911 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7913 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7914 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7915 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7916 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7919 - (void) viewDidLoad {
7920 [super viewDidLoad];
7922 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7925 - (void) releaseSubviews {
7927 subscribedCell_ = nil;
7929 ignoredSwitch_ = nil;
7930 subscribedSwitch_ = nil;
7932 [super releaseSubviews];
7935 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7936 if ((self = [super init]) != nil) {
7937 database_ = database;
7942 - (void) reloadData {
7945 package_ = [database_ packageWithName:name_];
7947 if (package_ != nil) {
7948 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7949 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7950 } // XXX: what now, G?
7952 [table_ reloadData];
7958 /* Installed Controller {{{ */
7959 @interface InstalledController : FilteredPackageListController {
7963 - (id) initWithDatabase:(Database *)database;
7965 - (void) updateRoleButton;
7966 - (void) queueStatusDidChange;
7970 @implementation InstalledController
7972 - (NSURL *) navigationURL {
7973 return [NSURL URLWithString:@"cydia://installed"];
7976 - (id) initWithDatabase:(Database *)database {
7977 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7978 [self updateRoleButton];
7979 [self queueStatusDidChange];
7984 - (void) queueButtonClicked {
7989 - (void) queueStatusDidChange {
7993 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7994 initWithTitle:UCLocalize("QUEUE")
7995 style:UIBarButtonItemStyleDone
7997 action:@selector(queueButtonClicked)
8000 [[self navigationItem] setLeftBarButtonItem:nil];
8006 - (void) updateRoleButton {
8007 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8008 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8009 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8010 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8012 action:@selector(roleButtonClicked)
8016 - (void) roleButtonClicked {
8017 [self setObject:[NSNumber numberWithBool:expert_]];
8021 [self updateRoleButton];
8027 /* Source Cell {{{ */
8028 @interface SourceCell : CyteTableViewCell <
8029 CyteTableViewCellDelegate
8032 _H<NSString> origin_;
8033 _H<NSString> label_;
8036 - (void) setSource:(Source *)source;
8040 @implementation SourceCell
8042 - (void) _setImage:(UIImage *)image {
8044 [content_ setNeedsDisplay];
8047 - (void) _setSource:(NSURL *) url {
8048 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8050 if (NSData *data = [NSURLConnection
8051 sendSynchronousRequest:[NSURLRequest
8053 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8057 returningResponse:NULL
8060 if (UIImage *image = [UIImage imageWithData:data])
8061 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
8066 - (void) setSource:(Source *)source {
8067 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8069 origin_ = [source name];
8070 label_ = [source rooturi];
8072 [content_ setNeedsDisplay];
8074 if (NSURL *url = [source iconURL])
8075 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url];
8078 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8079 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8080 UIView *content([self contentView]);
8081 CGRect bounds([content bounds]);
8083 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8084 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8085 [content_ setBackgroundColor:[UIColor whiteColor]];
8086 [content addSubview:content_];
8088 [content_ setDelegate:self];
8089 [content_ setOpaque:YES];
8091 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8095 - (NSString *) accessibilityLabel {
8099 - (void) drawContentRect:(CGRect)rect {
8100 bool highlighted(highlighted_);
8101 float width(rect.size.width);
8104 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8111 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 60) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8115 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 75) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8120 /* Source Controller {{{ */
8121 @interface SourceController : FilteredPackageListController {
8122 _transient Source *source_;
8126 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8130 @implementation SourceController
8132 - (NSURL *) navigationURL {
8133 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8136 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8137 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8139 key_ = [source key];
8143 - (void) reloadData {
8144 source_ = [database_ sourceWithKey:key_];
8145 key_ = [source_ key];
8146 [self setObject:source_];
8148 [[self navigationItem] setTitle:[source_ label]];
8155 /* Sources Controller {{{ */
8156 @interface SourcesController : CyteViewController <
8157 UITableViewDataSource,
8160 _transient Database *database_;
8161 _H<UITableView, 2> list_;
8162 _H<NSMutableArray> sources_;
8166 _H<UIProgressHUD> hud_;
8169 //NSURLConnection *installer_;
8170 NSURLConnection *trivial_;
8171 NSURLConnection *trivial_bz2_;
8172 NSURLConnection *trivial_gz_;
8173 //NSURLConnection *automatic_;
8178 - (id) initWithDatabase:(Database *)database;
8179 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8183 @implementation SourcesController
8185 - (void) _releaseConnection:(NSURLConnection *)connection {
8186 if (connection != nil) {
8187 [connection cancel];
8188 //[connection setDelegate:nil];
8189 [connection release];
8194 //[self _releaseConnection:installer_];
8195 [self _releaseConnection:trivial_];
8196 [self _releaseConnection:trivial_gz_];
8197 [self _releaseConnection:trivial_bz2_];
8198 //[self _releaseConnection:automatic_];
8203 - (NSURL *) navigationURL {
8204 return [NSURL URLWithString:@"cydia://sources"];
8207 - (void) viewDidAppear:(BOOL)animated {
8208 [super viewDidAppear:animated];
8209 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8212 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8216 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8220 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8221 return [sources_ count];
8224 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8225 return [sources_ objectAtIndex:[indexPath row]];
8228 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8229 static NSString *cellIdentifier = @"SourceCell";
8231 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8232 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8233 [cell setSource:[self sourceAtIndexPath:indexPath]];
8234 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8239 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8240 Source *source = [self sourceAtIndexPath:indexPath];
8242 SourceController *controller = [[[SourceController alloc]
8243 initWithDatabase:database_
8247 [controller setDelegate:delegate_];
8249 [[self navigationController] pushViewController:controller animated:YES];
8252 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8253 Source *source = [self sourceAtIndexPath:indexPath];
8254 return [source record] != nil;
8257 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8258 if (editingStyle == UITableViewCellEditingStyleDelete) {
8259 Source *source = [self sourceAtIndexPath:indexPath];
8260 [Sources_ removeObjectForKey:[source key]];
8261 [delegate_ syncData];
8266 [delegate_ addTrivialSource:href_];
8267 [delegate_ syncData];
8270 - (NSString *) getWarning {
8271 NSString *href(href_);
8272 NSRange colon([href rangeOfString:@"://"]);
8273 if (colon.location != NSNotFound)
8274 href = [href substringFromIndex:(colon.location + 3)];
8275 href = [href stringByAddingPercentEscapes];
8276 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8277 href = [href stringByCachingURLWithCurrentCDN];
8279 NSURL *url([NSURL URLWithString:href]);
8281 NSStringEncoding encoding;
8282 NSError *error(nil);
8284 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8285 return [warning length] == 0 ? nil : warning;
8289 - (void) _endConnection:(NSURLConnection *)connection {
8290 // XXX: the memory management in this method is horribly awkward
8292 NSURLConnection **field = NULL;
8293 if (connection == trivial_)
8295 else if (connection == trivial_bz2_)
8296 field = &trivial_bz2_;
8297 else if (connection == trivial_gz_)
8298 field = &trivial_gz_;
8299 _assert(field != NULL);
8300 [connection release];
8305 trivial_bz2_ == nil &&
8308 [delegate_ releaseNetworkActivityIndicator];
8310 [delegate_ removeProgressHUD:hud_];
8316 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8319 UIAlertView *alert = [[[UIAlertView alloc]
8320 initWithTitle:UCLocalize("SOURCE_WARNING")
8323 cancelButtonTitle:UCLocalize("CANCEL")
8325 UCLocalize("ADD_ANYWAY"),
8329 [alert setContext:@"warning"];
8330 [alert setNumberOfRows:1];
8334 } else if (error_ != nil) {
8335 UIAlertView *alert = [[[UIAlertView alloc]
8336 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8337 message:[error_ localizedDescription]
8339 cancelButtonTitle:UCLocalize("OK")
8340 otherButtonTitles:nil
8343 [alert setContext:@"urlerror"];
8346 UIAlertView *alert = [[[UIAlertView alloc]
8347 initWithTitle:UCLocalize("NOT_REPOSITORY")
8348 message:UCLocalize("NOT_REPOSITORY_EX")
8350 cancelButtonTitle:UCLocalize("OK")
8351 otherButtonTitles:nil
8354 [alert setContext:@"trivial"];
8363 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8364 switch ([response statusCode]) {
8370 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8371 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8373 [self _endConnection:connection];
8376 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8377 [self _endConnection:connection];
8380 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8381 NSURL *url([NSURL URLWithString:href]);
8383 NSMutableURLRequest *request = [NSMutableURLRequest
8385 cachePolicy:NSURLRequestUseProtocolCachePolicy
8386 timeoutInterval:120.0
8389 [request setHTTPMethod:method];
8391 if (Machine_ != NULL)
8392 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8394 if ([url isCydiaSecure]) {
8395 if (UniqueID_ != nil)
8396 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8399 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8402 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8403 NSString *context([alert context]);
8405 if ([context isEqualToString:@"source"]) {
8408 NSString *href = [[alert textField] text];
8410 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8412 if (![href hasSuffix:@"/"])
8413 href_ = [href stringByAppendingString:@"/"];
8417 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8418 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8419 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8420 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8424 // XXX: this is stupid
8425 hud_ = [delegate_ addProgressHUD];
8426 [hud_ setText:UCLocalize("VERIFYING_URL")];
8427 [delegate_ retainNetworkActivityIndicator];
8436 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8437 } else if ([context isEqualToString:@"trivial"])
8438 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8439 else if ([context isEqualToString:@"urlerror"])
8440 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8441 else if ([context isEqualToString:@"warning"]) {
8455 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8460 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8462 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8463 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8464 [list_ setRowHeight:53];
8465 [(UITableView *) list_ setDataSource:self];
8466 [list_ setDelegate:self];
8467 [[self view] addSubview:list_];
8470 - (void) viewDidLoad {
8471 [super viewDidLoad];
8473 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8474 [self updateButtonsForEditingStatus:NO animated:NO];
8477 - (void) releaseSubviews {
8482 [super releaseSubviews];
8485 - (id) initWithDatabase:(Database *)database {
8486 if ((self = [super init]) != nil) {
8487 database_ = database;
8491 - (void) reloadData {
8495 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8498 sources_ = [NSMutableArray arrayWithCapacity:16];
8499 [sources_ addObjectsFromArray:[database_ sources]];
8501 [sources_ sortUsingSelector:@selector(compareByName:)];
8504 int count([sources_ count]);
8506 for (int i = 0; i != count; i++) {
8507 if ([[sources_ objectAtIndex:i] record] == nil)
8512 [list_ setEditing:NO];
8513 [self updateButtonsForEditingStatus:NO animated:NO];
8517 - (void) showAddSourcePrompt {
8518 UIAlertView *alert = [[[UIAlertView alloc]
8519 initWithTitle:UCLocalize("ENTER_APT_URL")
8522 cancelButtonTitle:UCLocalize("CANCEL")
8524 UCLocalize("ADD_SOURCE"),
8528 [alert setContext:@"source"];
8530 [alert setNumberOfRows:1];
8531 [alert addTextFieldWithValue:@"http://" label:@""];
8533 UITextInputTraits *traits = [[alert textField] textInputTraits];
8534 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8535 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8536 [traits setKeyboardType:UIKeyboardTypeURL];
8537 // XXX: UIReturnKeyDone
8538 [traits setReturnKeyType:UIReturnKeyNext];
8543 - (void) addButtonClicked {
8544 [self showAddSourcePrompt];
8547 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8548 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8549 initWithTitle:UCLocalize("ADD")
8550 style:UIBarButtonItemStylePlain
8552 action:@selector(addButtonClicked)
8553 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8555 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8556 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8557 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8559 action:@selector(editButtonClicked)
8560 ] autorelease] animated:animated];
8562 if (IsWildcat_ && !editing)
8563 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8564 initWithTitle:UCLocalize("SETTINGS")
8565 style:UIBarButtonItemStylePlain
8567 action:@selector(settingsButtonClicked)
8571 - (void) settingsButtonClicked {
8572 [delegate_ showSettings];
8575 - (void) editButtonClicked {
8576 [list_ setEditing:![list_ isEditing] animated:YES];
8578 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8584 /* Settings Controller {{{ */
8585 @interface SettingsController : CyteViewController <
8586 UITableViewDataSource,
8589 _transient Database *database_;
8590 // XXX: ok, "roledelegate_"?...
8591 _transient id roledelegate_;
8592 _H<UITableView, 2> table_;
8593 _H<UISegmentedControl> segment_;
8594 _H<UIView> container_;
8597 - (void) showDoneButton;
8598 - (void) resizeSegmentedControl;
8602 @implementation SettingsController
8605 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8607 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8608 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8609 [table_ setDelegate:self];
8610 [(UITableView *) table_ setDataSource:self];
8611 [[self view] addSubview:table_];
8613 NSArray *items = [NSArray arrayWithObjects:
8615 UCLocalize("HACKER"),
8616 UCLocalize("DEVELOPER"),
8618 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8619 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8620 [container_ addSubview:segment_];
8623 - (void) viewDidLoad {
8624 [super viewDidLoad];
8626 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8629 if ([Role_ isEqualToString:@"User"]) index = 0;
8630 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8631 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8633 [segment_ setSelectedSegmentIndex:index];
8634 [self showDoneButton];
8637 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8638 [self resizeSegmentedControl];
8641 - (void) releaseSubviews {
8646 [super releaseSubviews];
8649 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8650 if ((self = [super init]) != nil) {
8651 database_ = database;
8652 roledelegate_ = delegate;
8656 - (void) resizeSegmentedControl {
8657 CGFloat width = [[self view] frame].size.width;
8658 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8661 - (void) viewWillAppear:(BOOL)animated {
8662 [super viewWillAppear:animated];
8664 [self resizeSegmentedControl];
8667 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8668 [self resizeSegmentedControl];
8671 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8672 [self resizeSegmentedControl];
8676 NSString *role(nil);
8678 switch ([segment_ selectedSegmentIndex]) {
8679 case 0: role = @"User"; break;
8680 case 1: role = @"Hacker"; break;
8681 case 2: role = @"Developer"; break;
8686 if (![role isEqualToString:Role_]) {
8687 bool rolling(Role_ == nil);
8690 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8694 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8698 [roledelegate_ loadData];
8700 [roledelegate_ updateData];
8704 - (void) segmentChanged:(UISegmentedControl *)control {
8705 [self showDoneButton];
8708 - (void) saveAndClose {
8711 [[self navigationItem] setRightBarButtonItem:nil];
8712 [[self navigationController] dismissModalViewControllerAnimated:YES];
8715 - (void) doneButtonClicked {
8716 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8717 [spinner startAnimating];
8718 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8719 [[self navigationItem] setRightBarButtonItem:spinItem];
8721 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8724 - (void) showDoneButton {
8725 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8726 initWithTitle:UCLocalize("DONE")
8727 style:UIBarButtonItemStyleDone
8729 action:@selector(doneButtonClicked)
8730 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8733 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8734 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8738 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8742 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8743 return nil; // This method is required by the protocol.
8746 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8748 return UCLocalize("ROLE_EX");
8750 return [NSString stringWithFormat:
8751 @"%@: %@\n%@: %@\n%@: %@",
8752 UCLocalize("USER"), UCLocalize("USER_EX"),
8753 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8754 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8759 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8760 return section == 3 ? 44.0f : 0;
8763 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8764 return section == 3 ? container_ : nil;
8767 - (void) reloadData {
8770 [table_ reloadData];
8775 /* Stash Controller {{{ */
8776 @interface StashController : CyteViewController {
8777 _H<UIActivityIndicatorView> spinner_;
8778 _H<UILabel> status_;
8779 _H<UILabel> caption_;
8784 @implementation StashController
8787 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8788 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8790 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8791 CGRect spinrect = [spinner_ frame];
8792 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8793 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8794 [spinner_ setFrame:spinrect];
8795 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8796 [[self view] addSubview:spinner_];
8797 [spinner_ startAnimating];
8800 captrect.size.width = [[self view] frame].size.width;
8801 captrect.size.height = 40.0f;
8802 captrect.origin.x = 0;
8803 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8804 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8805 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8806 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8807 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8808 [caption_ setTextColor:[UIColor whiteColor]];
8809 [caption_ setBackgroundColor:[UIColor clearColor]];
8810 [caption_ setShadowColor:[UIColor blackColor]];
8811 [caption_ setTextAlignment:UITextAlignmentCenter];
8812 [[self view] addSubview:caption_];
8815 statusrect.size.width = [[self view] frame].size.width;
8816 statusrect.size.height = 30.0f;
8817 statusrect.origin.x = 0;
8818 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8819 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8820 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8821 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8822 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8823 [status_ setTextColor:[UIColor whiteColor]];
8824 [status_ setBackgroundColor:[UIColor clearColor]];
8825 [status_ setShadowColor:[UIColor blackColor]];
8826 [status_ setTextAlignment:UITextAlignmentCenter];
8827 [[self view] addSubview:status_];
8830 - (void) releaseSubviews {
8835 [super releaseSubviews];
8841 @interface CYURLCache : SDURLCache {
8846 @implementation CYURLCache
8848 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8851 else if ([event isEqualToString:@"no-cache"])
8853 else if ([event isEqualToString:@"store"])
8855 else if ([event isEqualToString:@"invalid"])
8857 else if ([event isEqualToString:@"memory"])
8859 else if ([event isEqualToString:@"disk"])
8861 else if ([event isEqualToString:@"miss"])
8864 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8868 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8869 if (NSURLResponse *response = [cached response])
8870 if (NSString *mime = [response MIMEType])
8871 if ([mime isEqualToString:@"text/cache-manifest"]) {
8872 NSURL *url([response URL]);
8875 NSLog(@"###: %@", [url absoluteString]);
8878 @synchronized (HostConfig_) {
8879 [CachedURLs_ addObject:url];
8883 [super storeCachedResponse:cached forRequest:request];
8888 @interface Cydia : UIApplication <
8889 ConfirmationControllerDelegate,
8892 UINavigationControllerDelegate,
8893 UITabBarControllerDelegate
8895 _H<UIWindow> window_;
8896 _H<CYTabBarController> tabbar_;
8897 _H<CydiaLoadingViewController> emulated_;
8899 _H<NSMutableArray> essential_;
8900 _H<NSMutableArray> broken_;
8902 Database *database_;
8904 _H<NSURL> starturl_;
8909 _H<StashController> stash_;
8918 @implementation Cydia
8920 - (void) beginUpdate {
8921 [tabbar_ beginUpdate];
8925 return [tabbar_ updating];
8929 if ([broken_ count] != 0) {
8930 int count = [broken_ count];
8932 UIAlertView *alert = [[[UIAlertView alloc]
8933 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8934 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8936 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8938 UCLocalize("TEMPORARY_IGNORE"),
8942 [alert setContext:@"fixhalf"];
8943 [alert setNumberOfRows:2];
8945 } else if (!Ignored_ && [essential_ count] != 0) {
8946 int count = [essential_ count];
8948 UIAlertView *alert = [[[UIAlertView alloc]
8949 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8950 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8952 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8954 UCLocalize("UPGRADE_ESSENTIAL"),
8955 UCLocalize("COMPLETE_UPGRADE"),
8959 [alert setContext:@"upgrade"];
8964 - (void) returnToCydia {
8968 - (void) _saveConfig {
8974 NSString *error(nil);
8976 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8978 NSError *error(nil);
8979 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8980 NSLog(@"failure to save metadata data: %@", error);
8985 NSLog(@"failure to serialize metadata: %@", error);
8992 // Navigation controller for the queuing badge.
8993 - (UINavigationController *) queueNavigationController {
8994 NSArray *controllers = [tabbar_ viewControllers];
8995 return [controllers objectAtIndex:3];
8998 - (void) unloadData {
8999 [tabbar_ unloadData];
9002 - (void) _updateData {
9006 UINavigationController *navigation = [self queueNavigationController];
9008 id queuedelegate = nil;
9009 if ([[navigation viewControllers] count] > 0)
9010 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9012 [queuedelegate queueStatusDidChange];
9013 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9016 - (void) _refreshIfPossible:(NSDate *)update {
9017 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9019 bool recently = false;
9020 if (update != nil) {
9021 NSTimeInterval interval([update timeIntervalSinceNow]);
9022 if (interval <= 0 && interval > -(15*60))
9026 // Don't automatic refresh if:
9027 // - We already refreshed recently.
9028 // - We already auto-refreshed this launch.
9029 // - Auto-refresh is disabled.
9030 if (recently || loaded_ || ManualRefresh) {
9031 // If we are cancelling, we need to make sure it knows it's already loaded.
9034 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9036 // We are going to load, so remember that.
9039 SCNetworkReachabilityFlags flags; {
9040 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9041 SCNetworkReachabilityGetFlags(reachability, &flags);
9042 CFRelease(reachability);
9045 // XXX: this elaborate mess is what Apple is using to determine this? :(
9046 // XXX: do we care if the user has to intervene? maybe that's ok?
9048 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9049 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9050 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9051 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9052 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9053 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9057 // If we can reach the server, auto-refresh!
9059 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9065 - (void) refreshIfPossible {
9066 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9069 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9070 @synchronized (self) {
9071 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9072 [hud setText:UCLocalize("RELOADING_DATA")];
9074 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9077 [self removeProgressHUD:hud];
9081 [essential_ removeAllObjects];
9082 [broken_ removeAllObjects];
9084 NSArray *packages([database_ packages]);
9085 for (Package *package in packages) {
9087 [broken_ addObject:package];
9088 if ([package upgradableAndEssential:NO]) {
9089 if ([package essential])
9090 [essential_ addObject:package];
9095 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9098 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9099 [changesItem setBadgeValue:badge];
9100 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9101 [self setApplicationIconBadgeNumber:changes];
9104 [changesItem setBadgeValue:nil];
9105 [changesItem setAnimatedBadge:NO];
9106 [self setApplicationIconBadgeNumber:0];
9112 - (void) updateData {
9118 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9121 - (void) disemulate {
9122 if (emulated_ == nil)
9125 [window_ addSubview:[tabbar_ view]];
9126 [[emulated_ view] removeFromSuperview];
9128 [window_ setUserInteractionEnabled:YES];
9131 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9132 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9134 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9136 UIViewController *parent;
9137 if (emulated_ == nil)
9146 [parent presentModalViewController:navigation animated:YES];
9149 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9150 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9152 if (navigation != nil)
9153 [navigation pushViewController:progress animated:YES];
9155 [self presentModalViewController:progress force:YES];
9157 [progress invoke:invocation withTitle:title];
9161 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9162 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9165 - (void) repairWithInvocation:(NSInvocation *)invocation {
9167 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9171 - (void) repairWithSelector:(SEL)selector {
9172 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9175 - (void) reloadData {
9176 [self reloadDataWithInvocation:nil];
9177 if ([database_ progressDelegate] == nil)
9183 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9186 - (void) addSource:(NSDictionary *) source {
9190 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9191 AddSource(href, distribution, sections);
9194 - (void) addTrivialSource:(NSString *)href {
9195 AddSource(href, @"./");
9198 - (void) updateValues {
9203 pkgProblemResolver *resolver = [database_ resolver];
9205 resolver->InstallProtect();
9206 if (!resolver->Resolve(true))
9211 // XXX: this is a really crappy way of doing this.
9212 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9213 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9214 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9215 if ([tabbar_ updating])
9216 [tabbar_ cancelUpdate];
9218 if (![database_ prepare])
9221 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9222 [page setDelegate:self];
9223 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9226 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9227 [tabbar_ presentModalViewController:confirm_ animated:YES];
9233 @synchronized (self) {
9238 - (void) clearPackage:(Package *)package {
9239 @synchronized (self) {
9246 - (void) installPackages:(NSArray *)packages {
9247 @synchronized (self) {
9248 for (Package *package in packages)
9255 - (void) installPackage:(Package *)package {
9256 @synchronized (self) {
9263 - (void) removePackage:(Package *)package {
9264 @synchronized (self) {
9271 - (void) distUpgrade {
9272 @synchronized (self) {
9273 if (![database_ upgrade])
9280 [database_ perform];
9281 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9284 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9287 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9289 [self refreshIfPossible];
9292 - (void) showSettings {
9293 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9296 - (void) retainNetworkActivityIndicator {
9297 if (activity_++ == 0)
9298 [self setNetworkActivityIndicatorVisible:YES];
9301 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9305 - (void) releaseNetworkActivityIndicator {
9306 if (--activity_ == 0)
9307 [self setNetworkActivityIndicatorVisible:NO];
9310 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9315 - (void) cancelAndClear:(bool)clear {
9316 @synchronized (self) {
9328 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9329 NSString *context([alert context]);
9331 if ([context isEqualToString:@"conffile"]) {
9332 FILE *input = [database_ input];
9333 if (button == [alert cancelButtonIndex])
9334 fprintf(input, "N\n");
9335 else if (button == [alert firstOtherButtonIndex])
9336 fprintf(input, "Y\n");
9339 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9340 } else if ([context isEqualToString:@"fixhalf"]) {
9341 if (button == [alert cancelButtonIndex]) {
9342 @synchronized (self) {
9343 for (Package *broken in (id) broken_) {
9346 NSString *id = [broken id];
9347 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9348 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9349 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9350 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9356 } else if (button == [alert firstOtherButtonIndex]) {
9357 [broken_ removeAllObjects];
9361 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9362 } else if ([context isEqualToString:@"upgrade"]) {
9363 if (button == [alert firstOtherButtonIndex]) {
9364 @synchronized (self) {
9365 for (Package *essential in (id) essential_)
9366 [essential install];
9371 } else if (button == [alert firstOtherButtonIndex] + 1) {
9373 } else if (button == [alert cancelButtonIndex]) {
9377 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9381 - (void) system:(NSString *)command {
9382 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9385 system([command UTF8String]);
9391 - (void) applicationWillSuspend {
9393 [super applicationWillSuspend];
9396 - (BOOL) isSafeToSuspend {
9399 NSLog(@"isSafeToSuspend: locked_ != 0");
9404 // Use external process status API internally.
9405 // This is probably a really bad idea.
9406 // XXX: what is the point of this? does this solve anything at all?
9407 uint64_t status = 0;
9409 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9410 notify_get_state(notify_token, &status);
9411 notify_cancel(notify_token);
9416 NSLog(@"isSafeToSuspend: status != 0");
9422 NSLog(@"isSafeToSuspend: -> true");
9427 - (void) applicationSuspend:(__GSEvent *)event {
9428 if ([self isSafeToSuspend])
9429 [super applicationSuspend:event];
9432 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9433 if ([self isSafeToSuspend])
9434 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9437 - (void) _setSuspended:(BOOL)value {
9438 if ([self isSafeToSuspend])
9439 [super _setSuspended:value];
9442 - (UIProgressHUD *) addProgressHUD {
9443 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9444 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9446 [window_ setUserInteractionEnabled:NO];
9448 UIViewController *target(tabbar_);
9449 if (UIViewController *modal = [target modalViewController])
9452 UIView *view([target view]);
9453 [view addSubview:hud];
9455 [hud showInView:[tabbar_ view]];
9461 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9464 [hud removeFromSuperview];
9465 [window_ setUserInteractionEnabled:YES];
9468 - (CyteViewController *) pageForPackage:(NSString *)name {
9469 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9472 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9473 NSString *scheme([[url scheme] lowercaseString]);
9474 if ([[url absoluteString] length] <= [scheme length] + 3)
9476 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9477 NSArray *components([path pathComponents]);
9479 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9480 return [self pageForPackage:[components objectAtIndex:1]];
9482 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9485 NSString *base([components objectAtIndex:0]);
9487 CyteViewController *controller = nil;
9489 if ([base isEqualToString:@"url"]) {
9490 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9491 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9492 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9493 } else if (!external && [components count] == 1) {
9494 if ([base isEqualToString:@"manage"]) {
9495 controller = [[[ManageController alloc] init] autorelease];
9498 if ([base isEqualToString:@"sources"]) {
9499 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9502 if ([base isEqualToString:@"home"]) {
9503 controller = [[[HomeController alloc] init] autorelease];
9506 if ([base isEqualToString:@"sections"]) {
9507 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9510 if ([base isEqualToString:@"search"]) {
9511 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9514 if ([base isEqualToString:@"changes"]) {
9515 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9518 if ([base isEqualToString:@"installed"]) {
9519 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9521 } else if ([components count] == 2) {
9522 NSString *argument = [components objectAtIndex:1];
9524 if ([base isEqualToString:@"package"]) {
9525 controller = [self pageForPackage:argument];
9528 if (!external && [base isEqualToString:@"search"]) {
9529 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9532 if (!external && [base isEqualToString:@"sections"]) {
9533 if ([argument isEqualToString:@"all"])
9535 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9538 if (!external && [base isEqualToString:@"sources"]) {
9539 if ([argument isEqualToString:@"add"]) {
9540 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9541 [(SourcesController *)controller showAddSourcePrompt];
9543 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9544 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9548 if (!external && [base isEqualToString:@"launch"]) {
9549 [self launchApplicationWithIdentifier:argument suspended:NO];
9552 } else if (!external && [components count] == 3) {
9553 NSString *arg1 = [components objectAtIndex:1];
9554 NSString *arg2 = [components objectAtIndex:2];
9556 if ([base isEqualToString:@"package"]) {
9557 if ([arg2 isEqualToString:@"settings"]) {
9558 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9559 } else if ([arg2 isEqualToString:@"files"]) {
9560 if (Package *package = [database_ packageWithName:arg1]) {
9561 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9562 [(FileTable *)controller setPackage:package];
9568 [controller setDelegate:self];
9572 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9573 CyteViewController *page([self pageForURL:url forExternal:external]);
9576 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9577 [nav setViewControllers:[NSArray arrayWithObject:page]];
9578 [tabbar_ setUnselectedViewController:nav];
9584 - (void) applicationOpenURL:(NSURL *)url {
9585 [super applicationOpenURL:url];
9590 [self openCydiaURL:url forExternal:YES];
9593 - (void) applicationWillResignActive:(UIApplication *)application {
9594 // Stop refreshing if you get a phone call or lock the device.
9595 if ([tabbar_ updating])
9596 [tabbar_ cancelUpdate];
9598 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9599 [super applicationWillResignActive:application];
9602 - (void) saveState {
9603 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9604 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9605 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9611 - (void) applicationWillTerminate:(UIApplication *)application {
9615 - (void) setConfigurationData:(NSString *)data {
9616 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9618 if (!conffile_r(data)) {
9619 lprintf("E:invalid conffile\n");
9623 NSString *ofile = conffile_r[1];
9624 //NSString *nfile = conffile_r[2];
9626 UIAlertView *alert = [[[UIAlertView alloc]
9627 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9628 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9630 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9632 UCLocalize("ACCEPT_NEW_COPY"),
9633 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9637 [alert setContext:@"conffile"];
9638 [alert setNumberOfRows:2];
9642 - (void) addStashController {
9644 stash_ = [[[StashController alloc] init] autorelease];
9645 [window_ addSubview:[stash_ view]];
9648 - (void) removeStashController {
9649 [[stash_ view] removeFromSuperview];
9655 [self setIdleTimerDisabled:YES];
9657 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9658 UpdateExternalStatus(1);
9659 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9660 UpdateExternalStatus(0);
9662 [self removeStashController];
9664 if (ExecFork() == 0) {
9665 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9666 perror("launchctl stop");
9670 - (void) setupViewControllers {
9671 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9673 NSMutableArray *items([NSMutableArray arrayWithObjects:
9674 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9675 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9676 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9677 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9681 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9682 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9684 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9687 NSMutableArray *controllers([NSMutableArray array]);
9688 for (UITabBarItem *item in items) {
9689 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9690 [controller setTabBarItem:item];
9691 [controllers addObject:controller];
9693 [tabbar_ setViewControllers:controllers];
9695 [tabbar_ setUpdateDelegate:self];
9698 - (void) _sendMemoryWarningNotification {
9699 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9702 - (void) _sendMemoryWarningNotifications {
9704 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9709 - (void) applicationDidFinishLaunching:(id)unused {
9710 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9713 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9714 [self setApplicationSupportsShakeToEdit:NO];
9716 @synchronized (HostConfig_) {
9717 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9720 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9721 initWithMemoryCapacity:524288
9722 diskCapacity:10485760
9723 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9726 [CydiaWebViewController _initialize];
9728 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9730 // this would disallow http{,s} URLs from accessing this data
9731 //[WebView registerURLSchemeAsLocal:@"cydia"];
9733 Font12_ = [UIFont systemFontOfSize:12];
9734 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9735 Font14_ = [UIFont systemFontOfSize:14];
9736 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9737 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9739 essential_ = [NSMutableArray arrayWithCapacity:4];
9740 broken_ = [NSMutableArray arrayWithCapacity:4];
9742 // XXX: I really need this thing... like, seriously... I'm sorry
9743 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9745 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9746 [window_ orderFront:self];
9747 [window_ makeKey:self];
9748 [window_ setHidden:NO];
9751 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9752 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9753 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9754 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9755 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9756 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9757 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9758 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9759 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9762 [self addStashController];
9763 // XXX: this would be much cleaner as a yieldToSelector:
9764 // that way the removeStashController could happen right here inline
9765 // we also could no longer require the useless stash_ field anymore
9766 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9770 database_ = [Database sharedInstance];
9771 [database_ setDelegate:self];
9773 [window_ setUserInteractionEnabled:NO];
9774 [self setupViewControllers];
9776 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9777 [window_ addSubview:[emulated_ view]];
9779 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9783 - (NSArray *) defaultStartPages {
9784 NSMutableArray *standard = [NSMutableArray array];
9785 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9786 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9787 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9789 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9791 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9792 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9794 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9801 [window_ setUserInteractionEnabled:YES];
9802 [self showSettings];
9805 if ([emulated_ modalViewController] != nil)
9806 [emulated_ dismissModalViewControllerAnimated:YES];
9807 [window_ setUserInteractionEnabled:NO];
9810 [self reloadDataWithInvocation:nil];
9811 [self refreshIfPossible];
9816 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9817 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9818 int standardIndex = 0;
9819 NSArray *standard = [self defaultStartPages];
9826 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9827 if (valid && closed != nil) {
9828 NSTimeInterval interval([closed timeIntervalSinceNow]);
9829 // XXX: Is 15 minutes the optimal time here?
9830 if (interval > 0 && interval <= -(15*60))
9834 if (valid && [saved count] != [standard count])
9838 for (unsigned int i = 0; i < [standard count]; i++) {
9839 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9840 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9841 // but it's good enough for now.
9842 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9849 NSArray *items = nil;
9851 [tabbar_ setSelectedIndex:savedIndex];
9854 [tabbar_ setSelectedIndex:standardIndex];
9858 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9859 NSArray *stack = [items objectAtIndex:tab];
9860 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9861 NSMutableArray *current = [NSMutableArray array];
9863 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9864 NSString *addr = [stack objectAtIndex:nav];
9865 NSURL *url = [NSURL URLWithString:addr];
9866 CyteViewController *page = [self pageForURL:url forExternal:NO];
9868 [current addObject:page];
9871 [navigation setViewControllers:current];
9874 // (Try to) show the startup URL.
9875 if (starturl_ != nil) {
9876 [self openCydiaURL:starturl_ forExternal:NO];
9881 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9882 if (item != nil && IsWildcat_) {
9883 [sheet showFromBarButtonItem:item animated:YES];
9885 [sheet showInView:window_];
9889 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9890 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9891 [progress setTitle:task];
9892 [progress addProgressEvent:event];
9895 - (void) addProgressEventForTask:(NSArray *)data {
9896 CydiaProgressEvent *event([data objectAtIndex:0]);
9897 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9898 [self addProgressEvent:event forTask:task];
9901 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9902 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9908 id Alloc_(id self, SEL selector) {
9909 id object = alloc_(self, selector);
9910 lprintf("[%s]A-%p\n", self->isa->name, object);
9915 id Dealloc_(id self, SEL selector) {
9916 id object = dealloc_(self, selector);
9917 lprintf("[%s]D-%p\n", self->isa->name, object);
9921 Class $WebDefaultUIKitDelegate;
9923 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9924 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9925 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9926 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9929 static NSSet *MobilizedFiles_;
9931 static NSURL *MobilizeURL(NSURL *url) {
9932 NSString *path([url path]);
9933 if ([path hasPrefix:@"/var/root/"]) {
9934 NSString *file([path substringFromIndex:10]);
9935 if ([MobilizedFiles_ containsObject:file])
9936 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9942 Class $CFXPreferencesPropertyListSource;
9943 @class CFXPreferencesPropertyListSource;
9945 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9946 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9947 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9948 url = MobilizeURL(url);
9949 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9950 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9956 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9957 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9958 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9959 url = MobilizeURL(url);
9960 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9961 //NSLog(@"%@ %@", [url absoluteString], value);
9967 Class $NSURLConnection;
9969 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9970 NSMutableURLRequest *copy([request mutableCopy]);
9972 NSURL *url([copy URL]);
9974 NSString *href([url absoluteString]);
9975 NSString *host([url host]);
9976 NSString *scheme([[url scheme] lowercaseString]);
9978 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9980 @synchronized (HostConfig_) {
9981 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9982 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9983 [copy setHTTPShouldUsePipelining:YES];
9985 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9986 if ([control isEqualToString:@"max-age=0"])
9987 if ([CachedURLs_ containsObject:href]) {
9989 NSLog(@"~~~: %@", href);
9992 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9994 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9995 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9996 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10000 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10004 int main(int argc, char *argv[]) {
10005 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10009 UpdateExternalStatus(0);
10011 if (Class $UIDevice = objc_getClass("UIDevice")) {
10012 UIDevice *device([$UIDevice currentDevice]);
10013 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10015 IsWildcat_ = false;
10017 UIScreen *screen([UIScreen mainScreen]);
10018 if ([screen respondsToSelector:@selector(scale)])
10019 ScreenScale_ = [screen scale];
10023 UIDevice *device([UIDevice currentDevice]);
10024 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10025 Idiom_ = @"iphone";
10027 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10028 if (idiom == UIUserInterfaceIdiomPhone)
10029 Idiom_ = @"iphone";
10030 else if (idiom == UIUserInterfaceIdiomPad)
10033 NSLog(@"unknown UIUserInterfaceIdiom!");
10036 Pcre pattern("^([0-9]+\\.[0-9]+)");
10038 if (pattern([device systemVersion]))
10039 Firmware_ = pattern[1];
10040 if (pattern(Cydia_))
10041 Major_ = pattern[1];
10043 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10045 HostConfig_ = [[[NSObject alloc] init] autorelease];
10046 @synchronized (HostConfig_) {
10047 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10048 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10049 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10050 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10051 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10054 NSString *ui(@"ui/ios");
10056 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10057 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10058 UI_ = CydiaURL(ui);
10060 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10062 MobilizedFiles_ = [NSMutableSet setWithObjects:
10063 @"Library/Preferences/com.apple.Accessibility.plist",
10064 @"Library/Preferences/com.apple.preferences.sounds.plist",
10067 /* Library Hacks {{{ */
10068 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10070 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10072 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10073 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10074 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10075 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10078 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10079 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10080 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10081 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10084 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10085 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10086 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10087 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10088 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10091 $NSURLConnection = objc_getClass("NSURLConnection");
10092 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10093 if (NSURLConnection$init$ != NULL) {
10094 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10095 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10098 /* Set Locale {{{ */
10099 Locale_ = CFLocaleCopyCurrent();
10100 Languages_ = [NSLocale preferredLanguages];
10102 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10103 //NSLog(@"%@", [Languages_ description]);
10106 if (Locale_ != NULL)
10107 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10108 else if (Languages_ != nil && [Languages_ count] != 0)
10109 lang = [[Languages_ objectAtIndex:0] UTF8String];
10111 // XXX: consider just setting to C and then falling through?
10114 if (lang != NULL) {
10115 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10116 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10119 NSLog(@"Setting Language: %s", lang);
10121 if (lang != NULL) {
10122 setenv("LANG", lang, true);
10123 std::setlocale(LC_ALL, lang);
10127 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10129 /* Parse Arguments {{{ */
10130 bool substrate(false);
10136 for (int argi(1); argi != argc; ++argi)
10137 if (strcmp(argv[argi], "--") == 0) {
10139 argv[argi] = argv[0];
10145 for (int argi(1); argi != arge; ++argi)
10146 if (strcmp(args[argi], "--substrate") == 0)
10149 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10153 App_ = [[NSBundle mainBundle] bundlePath];
10159 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10160 alloc_ = alloc->method_imp;
10161 alloc->method_imp = (IMP) &Alloc_;*/
10163 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10164 dealloc_ = dealloc->method_imp;
10165 dealloc->method_imp = (IMP) &Dealloc_;*/
10167 /* System Information {{{ */
10171 size = sizeof(maxproc);
10172 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10173 perror("sysctlbyname(\"kern.maxproc\", ?)");
10174 else if (maxproc < 64) {
10176 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10177 perror("sysctlbyname(\"kern.maxproc\", #)");
10180 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10181 char *osversion = new char[size];
10182 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10183 perror("sysctlbyname(\"kern.osversion\", ?)");
10185 System_ = [NSString stringWithUTF8String:osversion];
10187 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10188 char *machine = new char[size];
10189 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10190 perror("sysctlbyname(\"hw.machine\", ?)");
10192 Machine_ = machine;
10194 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10195 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10196 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10198 UniqueID_ = [device uniqueIdentifier];
10200 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10201 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10202 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10204 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10205 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10206 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10208 if (mcc != NULL && mnc != NULL)
10209 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10216 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10217 Build_ = [system objectForKey:@"ProductBuildVersion"];
10218 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10219 Product_ = [info objectForKey:@"SafariProductVersion"];
10220 Safari_ = [info objectForKey:@"CFBundleVersion"];
10223 /* Load Database {{{ */
10225 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10227 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10229 if (Metadata_ == NULL)
10230 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10232 Settings_ = [Metadata_ objectForKey:@"Settings"];
10234 Packages_ = [Metadata_ objectForKey:@"Packages"];
10236 Values_ = [Metadata_ objectForKey:@"Values"];
10237 Sections_ = [Metadata_ objectForKey:@"Sections"];
10238 Sources_ = [Metadata_ objectForKey:@"Sources"];
10240 Token_ = [Metadata_ objectForKey:@"Token"];
10242 Version_ = [Metadata_ objectForKey:@"Version"];
10244 @synchronized (HostConfig_) {
10245 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10249 if (Settings_ != nil)
10250 Role_ = [Settings_ objectForKey:@"Role"];
10252 if (Values_ == nil) {
10253 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10254 [Metadata_ setObject:Values_ forKey:@"Values"];
10257 if (Sections_ == nil) {
10258 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10259 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10262 if (Sources_ == nil) {
10263 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10264 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10267 if (Version_ == nil) {
10268 Version_ = [NSNumber numberWithUnsignedInt:0];
10269 [Metadata_ setObject:Version_ forKey:@"Version"];
10272 @synchronized (HostConfig_) {
10273 if (CydiaSource_ == nil) {
10274 CydiaSource_ = @"apt.saurik.com";
10275 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10279 if ([Version_ unsignedIntValue] == 0) {
10280 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10281 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10282 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10283 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10285 Version_ = [NSNumber numberWithUnsignedInt:1];
10286 [Metadata_ setObject:Version_ forKey:@"Version"];
10288 [Metadata_ removeObjectForKey:@"LastUpdate"];
10297 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10300 if (Packages_ != nil) {
10302 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10306 [Metadata_ removeObjectForKey:@"Packages"];
10312 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10314 #define MobileSubstrate_(name) \
10315 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10316 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10317 if (handle == NULL) \
10318 NSLog(@"%s", dlerror()); \
10321 MobileSubstrate_(Activator)
10322 MobileSubstrate_(libstatusbar)
10323 MobileSubstrate_(SimulatedKeyEvents)
10324 MobileSubstrate_(WinterBoard)
10326 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10327 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10329 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10331 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10332 unlink("/tmp/.cydia.fw");
10334 } else if (access("/User", F_OK) != 0 || version < 4) {
10337 system("/usr/libexec/cydia/firmware.sh");
10341 _assert([[NSFileManager defaultManager]
10342 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10343 withIntermediateDirectories:YES
10348 if (access("/tmp/cydia.chk", F_OK) == 0) {
10349 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10350 _assert(errno == ENOENT);
10351 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10352 _assert(errno == ENOENT);
10355 /* APT Initialization {{{ */
10356 _assert(pkgInitConfig(*_config));
10357 _assert(pkgInitSystem(*_config, _system));
10360 _config->Set("APT::Acquire::Translation", lang);
10362 // XXX: this timeout might be important :(
10363 //_config->Set("Acquire::http::Timeout", 15);
10365 _config->Set("Acquire::http::MaxParallel", 3);
10367 /* Color Choices {{{ */
10368 space_ = CGColorSpaceCreateDeviceRGB();
10370 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10371 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10372 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10373 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10374 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10375 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10376 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10377 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10378 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10380 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10381 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10383 /* UIKit Configuration {{{ */
10384 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10385 if ($GSFontSetUseLegacyFontMetrics != NULL)
10386 $GSFontSetUseLegacyFontMetrics(YES);
10388 // XXX: I have a feeling this was important
10389 //UIKeyboardDisableAutomaticAppearance();
10392 Colon_ = UCLocalize("COLON_DELIMITED");
10393 Elision_ = UCLocalize("ELISION");
10394 Error_ = UCLocalize("ERROR");
10395 Warning_ = UCLocalize("WARNING");
10398 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10400 CGColorSpaceRelease(space_);
10401 CFRelease(Locale_);