1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
210 #define Cydia_ CYDIA_VERSION
212 #define lprintf(args...) fprintf(stderr, args)
215 #define TraceLogging (1 && !ForRelease)
216 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
217 #define ProfileTimes (0 && !ForRelease)
218 #define ForSaurik (0 && !ForRelease)
219 #define LogBrowser (0 && !ForRelease)
220 #define TrackResize (0 && !ForRelease)
221 #define ManualRefresh (1 && !ForRelease)
222 #define ShowInternals (0 && !ForRelease)
223 #define AlwaysReload (0 && !ForRelease)
224 #define TryIndexedCollation (0 && !ForRelease)
228 #define _trace(args...)
233 #define _profile(name) {
236 #define PrintTimes() do {} while (false)
239 // Hash Functions/Structures {{{
240 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
250 static _finline NSString *CydiaURL(NSString *path) {
252 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
253 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
254 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
255 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
256 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
258 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
261 static _finline void UpdateExternalStatus(uint64_t newStatus) {
263 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
264 notify_set_state(notify_token, newStatus);
265 notify_cancel(notify_token);
267 notify_post("com.saurik.Cydia.status");
270 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
271 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
272 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
275 /* NSForcedOrderingSearch doesn't work on the iPhone */
276 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
277 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
278 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
280 /* Insertion Sort {{{ */
282 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
283 const char *ptr = (const char *)list;
285 CFIndex half = count / 2;
286 const char *probe = ptr + elementSize * half;
287 CFComparisonResult cr = comparator(element, probe, context);
288 if (0 == cr) return (probe - (const char *)list) / elementSize;
289 ptr = (cr < 0) ? ptr : probe + elementSize;
290 count = (cr < 0) ? half : (half + (count & 1) - 1);
292 return (ptr - (const char *)list) / elementSize;
295 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
296 const char *ptr = (const char *)list;
298 CFIndex half = count / 2;
299 const char *probe = ptr + elementSize * half;
300 CFComparisonResult cr = comparator(element, probe, context);
301 if (0 == cr) return (probe - (const char *)list) / elementSize;
302 ptr = (cr < 0) ? ptr : probe + elementSize;
303 count = (cr < 0) ? half : (half + (count & 1) - 1);
305 return (ptr - (const char *)list) / elementSize;
308 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
309 if (range.length == 0)
311 const void **values(new const void *[range.length]);
312 CFArrayGetValues(array, range, values);
314 #if HistogramInsertionSort > 0
315 uint32_t total(0), *offsets(new uint32_t[range.length]);
318 for (CFIndex index(1); index != range.length; ++index) {
319 const void *value(values[index]);
320 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
321 CFIndex correct(index);
322 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
323 #if HistogramInsertionSort > 1
324 NSLog(@"%@ < %@", value, values[correct - 1]);
329 if (correct != index) {
330 size_t offset(index - correct);
331 #if HistogramInsertionSort
335 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
337 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
338 values[correct] = value;
342 CFArrayReplaceValues(array, range, values, range.length);
345 #if HistogramInsertionSort > 0
346 for (CFIndex index(0); index != range.length; ++index)
347 if (offsets[index] != 0)
348 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
349 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
356 /* Apple Bug Fixes {{{ */
357 @implementation UIWebDocumentView (Cydia)
359 - (void) _setScrollerOffset:(CGPoint)offset {
360 UIScroller *scroller([self _scroller]);
362 CGSize size([scroller contentSize]);
363 CGSize bounds([scroller bounds].size);
366 max.x = size.width - bounds.width;
367 max.y = size.height - bounds.height;
375 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
376 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
378 [scroller setOffset:offset];
384 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
385 size_t length([self length] - state->state);
388 else if (length > count)
390 for (size_t i(0); i != length; ++i)
391 objects[i] = [self item:state->state++];
392 state->itemsPtr = objects;
393 state->mutationsPtr = (unsigned long *) self;
397 /* Cydia NSString Additions {{{ */
398 @interface NSString (Cydia)
399 - (NSComparisonResult) compareByPath:(NSString *)other;
400 - (NSString *) stringByCachingURLWithCurrentCDN;
401 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
404 @implementation NSString (Cydia)
406 - (NSComparisonResult) compareByPath:(NSString *)other {
407 NSString *prefix = [self commonPrefixWithString:other options:0];
408 size_t length = [prefix length];
410 NSRange lrange = NSMakeRange(length, [self length] - length);
411 NSRange rrange = NSMakeRange(length, [other length] - length);
413 lrange = [self rangeOfString:@"/" options:0 range:lrange];
414 rrange = [other rangeOfString:@"/" options:0 range:rrange];
416 NSComparisonResult value;
418 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
419 value = NSOrderedSame;
420 else if (lrange.location == NSNotFound)
421 value = NSOrderedAscending;
422 else if (rrange.location == NSNotFound)
423 value = NSOrderedDescending;
425 value = NSOrderedSame;
427 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
428 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
429 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
430 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
432 NSComparisonResult result = [lpath compare:rpath];
433 return result == NSOrderedSame ? value : result;
436 - (NSString *) stringByCachingURLWithCurrentCDN {
438 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
439 withString:@"://cache.cydia.saurik.com/"
443 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
444 return [(id)CFURLCreateStringByAddingPercentEscapes(
449 kCFStringEncodingUTF8
456 /* C++ NSString Wrapper Cache {{{ */
457 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
458 return size == 0 ? NULL :
459 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
460 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
463 static _finline CFStringRef CYStringCreate(const char *data) {
464 return CYStringCreate(data, strlen(data));
473 _finline void clear_() {
474 if (cache_ != NULL) {
481 _finline bool empty() const {
485 _finline size_t size() const {
489 _finline char *data() const {
493 _finline void clear() {
498 _finline CYString() :
505 _finline ~CYString() {
509 void operator =(const CYString &rhs) {
513 if (rhs.cache_ == nil)
516 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
519 void copy(apr_pool_t *pool) {
520 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
521 memcpy(temp, data_, size_);
526 void set(apr_pool_t *pool, const char *data, size_t size) {
532 data_ = const_cast<char *>(data);
540 _finline void set(apr_pool_t *pool, const char *data) {
541 set(pool, data, data == NULL ? 0 : strlen(data));
544 _finline void set(apr_pool_t *pool, const std::string &rhs) {
545 set(pool, rhs.data(), rhs.size());
548 bool operator ==(const CYString &rhs) const {
549 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
552 _finline operator CFStringRef() {
554 cache_ = CYStringCreate(data_, size_);
558 _finline operator id() {
559 return (NSString *) static_cast<CFStringRef>(*this);
562 _finline operator const char *() {
563 return reinterpret_cast<const char *>(data_);
567 /* C++ NSString Algorithm Adapters {{{ */
569 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
572 struct NSStringMapHash :
573 std::unary_function<NSString *, size_t>
575 _finline size_t operator ()(NSString *value) const {
576 return CFStringHashNSString((CFStringRef) value);
580 struct NSStringMapLess :
581 std::binary_function<NSString *, NSString *, bool>
583 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
584 return [lhs compare:rhs] == NSOrderedAscending;
588 struct NSStringMapEqual :
589 std::binary_function<NSString *, NSString *, bool>
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
593 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
594 //[lhs isEqualToString:rhs];
599 /* CoreGraphics Primitives {{{ */
604 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
605 CGFloat color[] = {red, green, blue, alpha};
606 return CGColorCreate(space, color);
615 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
616 color_(Create_(space, red, green, blue, alpha))
618 Set(space, red, green, blue, alpha);
623 CGColorRelease(color_);
630 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
632 color_ = Create_(space, red, green, blue, alpha);
635 operator CGColorRef() {
641 /* Random Global Variables {{{ */
642 static const int PulseInterval_ = 50000;
644 static const NSString *UI_;
647 static bool RestartSubstrate_;
648 static NSArray *Finishes_;
650 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
651 #define NotifyConfig_ "/etc/notify.conf"
653 static bool Queuing_;
655 static CYColor Blue_;
656 static CYColor Blueish_;
657 static CYColor Black_;
659 static CYColor White_;
660 static CYColor Gray_;
661 static CYColor Green_;
662 static CYColor Purple_;
663 static CYColor Purplish_;
665 static UIColor *InstallingColor_;
666 static UIColor *RemovingColor_;
668 static NSString *App_;
670 static BOOL Advanced_;
671 static BOOL Ignored_;
673 static _H<UIFont> Font12_;
674 static _H<UIFont> Font12Bold_;
675 static _H<UIFont> Font14_;
676 static _H<UIFont> Font18Bold_;
677 static _H<UIFont> Font22Bold_;
679 static const char *Machine_ = NULL;
680 static NSString *System_ = nil;
681 static NSString *SerialNumber_ = nil;
682 static NSString *ChipID_ = nil;
683 static NSString *BBSNum_ = nil;
684 static _H<NSString> Token_;
685 static NSString *UniqueID_ = nil;
686 static NSString *PLMN_ = nil;
687 static NSString *Build_ = nil;
688 static NSString *Product_ = nil;
689 static NSString *Safari_ = nil;
691 static CFLocaleRef Locale_;
692 static NSArray *Languages_;
693 static CGColorSpaceRef space_;
695 static NSDictionary *SectionMap_;
696 static NSMutableDictionary *Metadata_;
697 static _transient NSMutableDictionary *Settings_;
698 static _transient NSString *Role_;
699 static _transient NSMutableDictionary *Packages_;
700 static _transient NSMutableDictionary *Values_;
701 static _transient NSMutableDictionary *Sections_;
702 static _transient NSMutableDictionary *Sources_;
703 static _transient NSNumber *Version_;
704 static _transient _H<NSString> CydiaSource_;
705 static bool Changed_;
709 static CGFloat ScreenScale_;
710 static NSString *Idiom_;
712 static _H<NSMutableDictionary> SessionData_;
713 static _H<NSObject> HostConfig_;
714 static _H<NSMutableSet> BridgedHosts_;
715 static _H<NSMutableSet> TokenHosts_;
716 static _H<NSMutableSet> InsecureHosts_;
717 static _H<NSMutableSet> PipelinedHosts_;
718 static _H<NSMutableSet> CachedURLs_;
720 static NSString *kCydiaProgressEventTypeError = @"Error";
721 static NSString *kCydiaProgressEventTypeInformation = @"Information";
722 static NSString *kCydiaProgressEventTypeStatus = @"Status";
723 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
726 static void AddSource(NSDictionary *source) {
727 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
731 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
732 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
735 distribution, @"Distribution",
736 sections ?: [NSMutableArray array], @"Sections",
740 static void WriteSources() {
741 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
742 _assert(file != NULL);
744 fprintf(file, "deb http://%s/ tangelo main\n",
745 [CydiaSource_ UTF8String]
748 for (NSString *key in [Sources_ allKeys]) {
749 NSDictionary *source([Sources_ objectForKey:key]);
751 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
753 fprintf(file, "%s %s %s%s%s\n",
754 [[source objectForKey:@"Type"] UTF8String],
755 [[source objectForKey:@"URI"] UTF8String],
756 [[source objectForKey:@"Distribution"] UTF8String],
757 [sections count] == 0 ? "" : " ",
758 [[sections componentsJoinedByString:@" "] UTF8String]
765 /* Display Helpers {{{ */
766 inline float Interpolate(float begin, float end, float fraction) {
767 return (end - begin) * fraction + begin;
770 static _finline const char *StripVersion_(const char *version) {
771 const char *colon(strchr(version, ':'));
772 return colon == NULL ? version : colon + 1;
775 NSString *LocalizeSection(NSString *section) {
776 static Pcre title_r("^(.*?) \\((.*)\\)$");
777 if (title_r(section)) {
778 NSString *parent(title_r[1]);
779 NSString *child(title_r[2]);
781 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
782 LocalizeSection(parent),
783 LocalizeSection(child)
787 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
790 NSString *Simplify(NSString *title) {
791 const char *data = [title UTF8String];
792 size_t size = [title length];
794 static Pcre square_r("^\\[(.*)\\]$");
795 if (square_r(data, size))
796 return Simplify(square_r[1]);
798 static Pcre paren_r("^\\((.*)\\)$");
799 if (paren_r(data, size))
800 return Simplify(paren_r[1]);
802 static Pcre title_r("^(.*?) \\((.*)\\)$");
803 if (title_r(data, size))
804 return Simplify(title_r[1]);
810 NSString *GetLastUpdate() {
811 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
814 return UCLocalize("NEVER_OR_UNKNOWN");
816 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
817 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
819 CFRelease(formatter);
821 return [(NSString *) formatted autorelease];
824 bool isSectionVisible(NSString *section) {
825 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
826 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
827 return hidden == nil || ![hidden boolValue];
830 static NSObject *CYIOGetValue(const char *path, NSString *property) {
831 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
832 if (entry == MACH_PORT_NULL)
835 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
836 IOObjectRelease(entry);
840 return [(id) value autorelease];
843 static NSString *CYHex(NSData *data, bool reverse = false) {
847 size_t length([data length]);
848 uint8_t bytes[length];
849 [data getBytes:bytes];
851 char string[length * 2 + 1];
852 for (size_t i(0); i != length; ++i)
853 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
855 return [NSString stringWithUTF8String:string];
860 /* Delegate Prototypes {{{ */
863 @class CydiaProgressEvent;
865 @protocol DatabaseDelegate
866 - (void) repairWithSelector:(SEL)selector;
867 - (void) setConfigurationData:(NSString *)data;
868 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
871 @class CYPackageController;
873 @protocol CydiaDelegate
875 - (void) retainNetworkActivityIndicator;
876 - (void) releaseNetworkActivityIndicator;
877 - (void) clearPackage:(Package *)package;
878 - (void) installPackage:(Package *)package;
879 - (void) installPackages:(NSArray *)packages;
880 - (void) removePackage:(Package *)package;
881 - (void) beginUpdate;
883 - (void) distUpgrade;
887 - (void) addSource:(NSDictionary *)source;
888 - (void) addTrivialSource:(NSString *)href;
889 - (void) showSettings;
890 - (UIProgressHUD *) addProgressHUD;
891 - (void) removeProgressHUD:(UIProgressHUD *)hud;
892 - (CyteViewController *) pageForPackage:(NSString *)name;
893 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
894 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
898 /* Status Delegation {{{ */
900 public pkgAcquireStatus
903 _transient NSObject<ProgressDelegate> *delegate_;
913 void setDelegate(NSObject<ProgressDelegate> *delegate) {
914 delegate_ = delegate;
917 NSObject<ProgressDelegate> *getDelegate() const {
921 virtual bool MediaChange(std::string media, std::string drive) {
925 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
928 virtual void Fetch(pkgAcquire::ItemDesc &item) {
929 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
930 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
931 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
934 virtual void Done(pkgAcquire::ItemDesc &item) {
937 virtual void Fail(pkgAcquire::ItemDesc &item) {
939 item.Owner->Status == pkgAcquire::Item::StatIdle ||
940 item.Owner->Status == pkgAcquire::Item::StatDone
944 std::string &error(item.Owner->ErrorText);
948 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
949 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
952 virtual bool Pulse(pkgAcquire *Owner) {
953 bool value = pkgAcquireStatus::Pulse(Owner);
956 double(CurrentBytes + CurrentItems) /
957 double(TotalBytes + TotalItems)
960 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
961 [NSNumber numberWithDouble:percent], @"Percent",
963 [NSNumber numberWithDouble:CurrentBytes], @"Current",
964 [NSNumber numberWithDouble:TotalBytes], @"Total",
965 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
966 nil] waitUntilDone:YES];
968 if (value && ![delegate_ isProgressCancelled])
976 _finline bool WasCancelled() const {
980 virtual void Start() {
981 pkgAcquireStatus::Start();
982 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
985 virtual void Stop() {
986 pkgAcquireStatus::Stop();
987 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
988 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
992 /* Database Interface {{{ */
993 typedef std::map< unsigned long, _H<Source> > SourceMap;
995 @interface Database : NSObject {
1001 pkgCacheFile cache_;
1002 pkgDepCache::Policy *policy_;
1003 pkgRecords *records_;
1004 pkgProblemResolver *resolver_;
1005 pkgAcquire *fetcher_;
1007 SPtr<pkgPackageManager> manager_;
1008 pkgSourceList *list_;
1010 SourceMap sourceMap_;
1011 _H<NSMutableArray> sourceList_;
1013 CFMutableArrayRef packages_;
1015 _transient NSObject<DatabaseDelegate> *delegate_;
1016 _transient NSObject<ProgressDelegate> *progress_;
1024 std::map<const char *, _H<NSString> > sections_;
1027 + (Database *) sharedInstance;
1030 - (void) _readCydia:(NSNumber *)fd;
1031 - (void) _readStatus:(NSNumber *)fd;
1032 - (void) _readOutput:(NSNumber *)fd;
1036 - (Package *) packageWithName:(NSString *)name;
1038 - (pkgCacheFile &) cache;
1039 - (pkgDepCache::Policy *) policy;
1040 - (pkgRecords *) records;
1041 - (pkgProblemResolver *) resolver;
1042 - (pkgAcquire &) fetcher;
1043 - (pkgSourceList &) list;
1044 - (NSArray *) packages;
1045 - (NSArray *) sources;
1046 - (Source *) sourceWithKey:(NSString *)key;
1047 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1055 - (void) updateWithStatus:(Status &)status;
1057 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1059 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1060 - (NSObject<ProgressDelegate> *) progressDelegate;
1062 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1064 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1068 /* ProgressEvent Implementation {{{ */
1069 @implementation CydiaProgressEvent
1071 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1072 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1075 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1076 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1077 [event setPackage:package];
1081 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1082 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1084 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1085 NSArray *fields([description componentsSeparatedByString:@" "]);
1086 [event setItem:fields];
1088 if ([fields count] > 3) {
1089 [event setPackage:[fields objectAtIndex:2]];
1090 [event setVersion:[fields objectAtIndex:3]];
1093 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1098 + (NSArray *) _attributeKeys {
1099 return [NSArray arrayWithObjects:
1109 - (NSArray *) attributeKeys {
1110 return [[self class] _attributeKeys];
1113 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1114 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1117 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1118 if ((self = [super init]) != nil) {
1124 - (NSString *) message {
1128 - (NSString *) type {
1132 - (NSArray *) item {
1133 return (id) item_ ?: [NSNull null];
1136 - (void) setItem:(NSArray *)item {
1140 - (NSString *) package {
1141 return (id) package_ ?: [NSNull null];
1144 - (void) setPackage:(NSString *)package {
1148 - (NSString *) url {
1149 return (id) url_ ?: [NSNull null];
1152 - (void) setURL:(NSString *)url {
1156 - (void) setVersion:(NSString *)version {
1160 - (NSString *) version {
1161 return (id) version_ ?: [NSNull null];
1164 - (NSString *) compound:(NSString *)value {
1166 NSString *mode(nil); {
1167 NSString *type([self type]);
1168 if ([type isEqualToString:kCydiaProgressEventTypeError])
1169 mode = UCLocalize("ERROR");
1170 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1171 mode = UCLocalize("WARNING");
1175 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1181 - (NSString *) compoundMessage {
1182 return [self compound:[self message]];
1185 - (NSString *) compoundTitle {
1188 if (package_ == nil)
1190 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1191 title = [package name];
1195 return [self compound:title];
1201 // Cytore Definitions {{{
1202 struct PackageValue :
1205 Cytore::Offset<PackageValue> next_;
1207 uint32_t index_ : 23;
1208 uint32_t subscribed_ : 1;
1225 Cytore::Offset<PackageValue> packages_[1 << 16];
1228 static Cytore::File<MetaValue> MetaFile_;
1230 // Cytore Helper Functions {{{
1231 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1232 SplitHash nhash = { hashlittle(name, length) };
1234 PackageValue *metadata;
1236 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1237 offset: if (offset->IsNull()) {
1238 *offset = MetaFile_.New<PackageValue>(length + 1);
1239 metadata = &MetaFile_.Get(*offset);
1241 if (metadata == NULL) {
1245 metadata = new PackageValue();
1246 memset(metadata, 0, sizeof(*metadata));
1249 memcpy(metadata->name_, name, length + 1);
1250 metadata->nhash_ = nhash.u16[1];
1252 metadata = &MetaFile_.Get(*offset);
1254 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1255 offset = &metadata->next_;
1263 static void PackageImport(const void *key, const void *value, void *context) {
1264 bool &fail(*reinterpret_cast<bool *>(context));
1267 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1268 NSLog(@"failed to import package %@", key);
1272 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1273 NSDictionary *package((NSDictionary *) value);
1275 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1276 if ([subscribed boolValue] && !metadata->subscribed_)
1277 metadata->subscribed_ = true;
1279 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1280 time_t time([date timeIntervalSince1970]);
1281 if (metadata->first_ > time || metadata->first_ == 0)
1282 metadata->first_ = time;
1285 NSDate *date([package objectForKey:@"LastSeen"]);
1286 NSString *version([package objectForKey:@"LastVersion"]);
1288 if (date != nil && version != nil) {
1289 time_t time([date timeIntervalSince1970]);
1290 if (metadata->last_ < time || metadata->last_ == 0)
1291 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1292 size_t length(strlen(buffer));
1293 uint16_t vhash(hashlittle(buffer, length));
1295 size_t capped(std::min<size_t>(8, length));
1296 char *latest(buffer + length - capped);
1298 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1299 metadata->vhash_ = vhash;
1301 metadata->last_ = time;
1307 /* Source Class {{{ */
1308 @interface Source : NSObject {
1309 CYString depiction_;
1310 CYString description_;
1316 CYString distribution_;
1322 _H<NSString> authority_;
1324 CYString defaultIcon_;
1326 _H<NSDictionary> record_;
1330 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1332 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1334 - (NSString *) depictionForPackage:(NSString *)package;
1335 - (NSString *) supportForPackage:(NSString *)package;
1337 - (NSDictionary *) record;
1341 - (NSString *) distribution;
1342 - (NSString *) type;
1344 - (NSString *) base;
1347 - (NSString *) host;
1349 - (NSString *) name;
1350 - (NSString *) shortDescription;
1351 - (NSString *) label;
1352 - (NSString *) origin;
1353 - (NSString *) version;
1355 - (NSString *) defaultIcon;
1359 @implementation Source
1363 distribution_.clear();
1368 description_.clear();
1374 defaultIcon_.clear();
1381 + (NSString *) webScriptNameForSelector:(SEL)selector {
1383 else if (selector == @selector(addSection:))
1384 return @"addSection";
1385 else if (selector == @selector(removeSection:))
1386 return @"removeSection";
1387 else if (selector == @selector(remove))
1393 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1394 return [self webScriptNameForSelector:selector] == nil;
1397 + (NSArray *) _attributeKeys {
1398 return [NSArray arrayWithObjects:
1406 @"shortDescription",
1414 - (NSArray *) attributeKeys {
1415 return [[self class] _attributeKeys];
1418 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1419 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1422 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1425 trusted_ = index->IsTrusted();
1427 uri_.set(pool, index->GetURI());
1428 distribution_.set(pool, index->GetDist());
1429 type_.set(pool, index->GetType());
1431 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1432 if (dindex != NULL) {
1433 base_.set(pool, dindex->MetaIndexURI(""));
1436 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1439 pkgTagFile tags(&fd);
1441 pkgTagSection section;
1448 {"default-icon", &defaultIcon_},
1449 {"depiction", &depiction_},
1450 {"description", &description_},
1452 {"origin", &origin_},
1453 {"support", &support_},
1454 {"version", &version_},
1457 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1458 const char *start, *end;
1460 if (section.Find(names[i].name_, start, end)) {
1461 CYString &value(*names[i].value_);
1462 value.set(pool, start, end - start);
1468 record_ = [Sources_ objectForKey:[self key]];
1470 NSURL *url([NSURL URLWithString:uri_]);
1474 host_ = [host_ lowercaseString];
1479 authority_ = [url path];
1482 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1483 if ((self = [super init]) != nil) {
1484 [self setMetaIndex:index inPool:pool];
1488 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1489 NSDictionary *lhr = [self record];
1490 NSDictionary *rhr = [source record];
1493 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1495 NSString *lhs = [self name];
1496 NSString *rhs = [source name];
1498 if ([lhs length] != 0 && [rhs length] != 0) {
1499 unichar lhc = [lhs characterAtIndex:0];
1500 unichar rhc = [rhs characterAtIndex:0];
1502 if (isalpha(lhc) && !isalpha(rhc))
1503 return NSOrderedAscending;
1504 else if (!isalpha(lhc) && isalpha(rhc))
1505 return NSOrderedDescending;
1508 return [lhs compare:rhs options:LaxCompareOptions_];
1511 - (NSString *) depictionForPackage:(NSString *)package {
1512 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1515 - (NSString *) supportForPackage:(NSString *)package {
1516 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1519 - (NSArray *) sections {
1520 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1523 - (void) _addSection:(NSString *)section {
1526 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1527 if (![sections containsObject:section]) {
1528 [sections addObject:section];
1532 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1537 - (bool) addSection:(NSString *)section {
1541 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1545 - (void) _removeSection:(NSString *)section {
1549 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1550 if ([sections containsObject:section]) {
1551 [sections removeObject:section];
1556 - (bool) removeSection:(NSString *)section {
1560 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1565 [Sources_ removeObjectForKey:[self key]];
1570 bool value(record_ != nil);
1571 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1575 - (NSDictionary *) record {
1583 - (NSString *) uri {
1587 - (NSString *) distribution {
1588 return distribution_;
1591 - (NSString *) type {
1595 - (NSString *) base {
1599 - (NSString *) key {
1600 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1603 - (NSString *) host {
1607 - (NSString *) name {
1608 return origin_.empty() ? (id) authority_ : origin_;
1611 - (NSString *) shortDescription {
1612 return description_;
1615 - (NSString *) label {
1616 return label_.empty() ? (id) authority_ : label_;
1619 - (NSString *) origin {
1623 - (NSString *) version {
1627 - (NSString *) defaultIcon {
1628 return defaultIcon_;
1633 /* CydiaOperation Class {{{ */
1634 @interface CydiaOperation : NSObject {
1635 _H<NSString> operator_;
1636 _H<NSString> value_;
1639 - (NSString *) operator;
1640 - (NSString *) value;
1644 @implementation CydiaOperation
1646 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1647 if ((self = [super init]) != nil) {
1648 operator_ = [NSString stringWithUTF8String:_operator];
1649 value_ = [NSString stringWithUTF8String:value];
1653 + (NSArray *) _attributeKeys {
1654 return [NSArray arrayWithObjects:
1660 - (NSArray *) attributeKeys {
1661 return [[self class] _attributeKeys];
1664 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1665 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1668 - (NSString *) operator {
1672 - (NSString *) value {
1678 /* CydiaClause Class {{{ */
1679 @interface CydiaClause : NSObject {
1680 _H<NSString> package_;
1681 _H<CydiaOperation> version_;
1684 - (NSString *) package;
1685 - (CydiaOperation *) version;
1689 @implementation CydiaClause
1691 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1692 if ((self = [super init]) != nil) {
1693 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1695 if (const char *version = dep.TargetVer())
1696 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1698 version_ = (id) [NSNull null];
1702 + (NSArray *) _attributeKeys {
1703 return [NSArray arrayWithObjects:
1709 - (NSArray *) attributeKeys {
1710 return [[self class] _attributeKeys];
1713 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1714 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1717 - (NSString *) package {
1721 - (CydiaOperation *) version {
1727 /* CydiaRelation Class {{{ */
1728 @interface CydiaRelation : NSObject {
1729 _H<NSString> relationship_;
1730 _H<NSMutableArray> clauses_;
1733 - (NSString *) relationship;
1734 - (NSArray *) clauses;
1738 @implementation CydiaRelation
1740 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1741 if ((self = [super init]) != nil) {
1742 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1743 clauses_ = [NSMutableArray arrayWithCapacity:8];
1745 pkgCache::DepIterator start;
1746 pkgCache::DepIterator end;
1747 dep.GlobOr(start, end); // ++dep
1750 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1752 // yes, seriously. (wtf?)
1760 + (NSArray *) _attributeKeys {
1761 return [NSArray arrayWithObjects:
1767 - (NSArray *) attributeKeys {
1768 return [[self class] _attributeKeys];
1771 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1772 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1775 - (NSString *) relationship {
1776 return relationship_;
1779 - (NSArray *) clauses {
1783 - (void) addClause:(CydiaClause *)clause {
1784 [clauses_ addObject:clause];
1789 /* Package Class {{{ */
1790 struct ParsedPackage {
1793 CYString architecture_;
1796 CYString depiction_;
1806 @interface Package : NSObject {
1809 uint32_t essential_ : 1;
1810 uint32_t obsolete_ : 1;
1811 uint32_t ignored_ : 1;
1817 _transient Database *database_;
1819 pkgCache::VerIterator version_;
1820 pkgCache::PkgIterator iterator_;
1821 pkgCache::VerFileIterator file_;
1827 CYString installed_;
1829 const char *section_;
1830 _transient NSString *section$_;
1834 PackageValue *metadata_;
1835 ParsedPackage *parsed_;
1837 _H<NSMutableArray> tags_;
1840 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1841 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1843 - (pkgCache::PkgIterator) iterator;
1846 - (NSString *) section;
1847 - (NSString *) simpleSection;
1849 - (NSString *) longSection;
1850 - (NSString *) shortSection;
1854 - (MIMEAddress *) maintainer;
1856 - (NSString *) longDescription;
1857 - (NSString *) shortDescription;
1860 - (PackageValue *) metadata;
1863 - (bool) subscribed;
1864 - (bool) setSubscribed:(bool)subscribed;
1868 - (NSString *) latest;
1869 - (NSString *) installed;
1870 - (BOOL) uninstalled;
1873 - (BOOL) upgradableAndEssential:(BOOL)essential;
1876 - (BOOL) unfiltered;
1880 - (BOOL) halfConfigured;
1881 - (BOOL) halfInstalled;
1883 - (NSString *) mode;
1886 - (NSString *) name;
1888 - (NSString *) homepage;
1889 - (NSString *) depiction;
1890 - (MIMEAddress *) author;
1892 - (NSString *) support;
1894 - (NSArray *) files;
1895 - (NSArray *) warnings;
1896 - (NSArray *) applications;
1898 - (Source *) source;
1901 - (BOOL) matches:(NSArray *)query;
1903 - (bool) hasSupportingRole;
1904 - (BOOL) hasTag:(NSString *)tag;
1905 - (NSString *) primaryPurpose;
1906 - (NSArray *) purposes;
1907 - (bool) isCommercial;
1909 - (void) setIndex:(size_t)index;
1911 - (CYString &) cyname;
1913 - (uint32_t) compareBySection:(NSArray *)sections;
1918 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1919 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1920 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1921 - (bool) isVisibleInSection:(NSString *)section;
1922 - (bool) isVisibleInSource:(Source *)source;
1926 uint32_t PackageChangesRadix(Package *self, void *) {
1931 uint32_t timestamp : 30;
1932 uint32_t ignored : 1;
1933 uint32_t upgradable : 1;
1937 bool upgradable([self upgradableAndEssential:YES]);
1938 value.bits.upgradable = upgradable ? 1 : 0;
1941 value.bits.timestamp = 0;
1942 value.bits.ignored = [self ignored] ? 0 : 1;
1943 value.bits.upgradable = 1;
1945 value.bits.timestamp = [self seen] >> 2;
1946 value.bits.ignored = 0;
1947 value.bits.upgradable = 0;
1950 return _not(uint32_t) - value.key;
1953 uint32_t PackagePrefixRadix(Package *self, void *context) {
1954 size_t offset(reinterpret_cast<size_t>(context));
1955 CYString &name([self cyname]);
1957 size_t size(name.size());
1960 char *text(name.data());
1963 if (!isdigit(text[0]))
1967 while (size != digits && isdigit(text[digits]))
1975 if (offset == 0 && zeros != 0) {
1976 memset(data, '0', zeros);
1977 memcpy(data + zeros, text, 4 - zeros);
1979 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1980 if (size <= offset - zeros)
1983 text += offset - zeros;
1984 size -= offset - zeros;
1987 memcpy(data, text, 4);
1989 memcpy(data, text, size);
1990 memset(data + size, 0, 4 - size);
1993 for (size_t i(0); i != 4; ++i)
1994 if (isalpha(data[i]))
2002 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2004 /* XXX: ntohl may be more honest */
2005 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2008 CYString &(*PackageName)(Package *self, SEL sel);
2010 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2011 _profile(PackageNameCompare)
2012 CYString &lhi(PackageName(lhs, @selector(cyname)));
2013 CYString &rhi(PackageName(rhs, @selector(cyname)));
2014 CFStringRef lhn(lhi), rhn(rhi);
2017 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2018 else if (rhn == NULL)
2019 return NSOrderedDescending;
2021 _profile(PackageNameCompare$NumbersLast)
2022 if (!lhi.empty() && !rhi.empty()) {
2023 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2024 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2025 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2026 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2027 return lha ? NSOrderedAscending : NSOrderedDescending;
2031 CFIndex length = CFStringGetLength(lhn);
2033 _profile(PackageNameCompare$Compare)
2034 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2039 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2040 return PackageNameCompare(*lhs, *rhs, context);
2043 struct PackageNameOrdering :
2044 std::binary_function<Package *, Package *, bool>
2046 _finline bool operator ()(Package *lhs, Package *rhs) const {
2047 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2051 @implementation Package
2053 - (NSString *) description {
2054 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2058 if (parsed_ != NULL)
2063 + (NSString *) webScriptNameForSelector:(SEL)selector {
2065 else if (selector == @selector(clear))
2067 else if (selector == @selector(getField:))
2069 else if (selector == @selector(hasTag:))
2071 else if (selector == @selector(install))
2073 else if (selector == @selector(remove))
2079 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2080 return [self webScriptNameForSelector:selector] == nil;
2083 + (NSArray *) _attributeKeys {
2084 return [NSArray arrayWithObjects:
2104 @"shortDescription",
2117 - (NSArray *) attributeKeys {
2118 return [[self class] _attributeKeys];
2121 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2122 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2125 - (NSArray *) relations {
2126 @synchronized (database_) {
2127 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2128 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2129 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2133 - (NSString *) architecture {
2135 @synchronized (database_) {
2136 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2139 - (NSString *) getField:(NSString *)name {
2140 @synchronized (database_) {
2141 if ([database_ era] != era_ || file_.end())
2144 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2146 const char *start, *end;
2147 if (!parser.Find([name UTF8String], start, end))
2148 return (NSString *) [NSNull null];
2150 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2154 if (parsed_ != NULL)
2156 @synchronized (database_) {
2157 if ([database_ era] != era_ || file_.end())
2160 ParsedPackage *parsed(new ParsedPackage);
2163 _profile(Package$parse)
2164 pkgRecords::Parser *parser;
2166 _profile(Package$parse$Lookup)
2167 parser = &[database_ records]->Lookup(file_);
2172 _profile(Package$parse$Find)
2177 {"architecture", &parsed->architecture_},
2178 {"icon", &parsed->icon_},
2179 {"depiction", &parsed->depiction_},
2180 {"homepage", &parsed->homepage_},
2181 {"website", &website},
2182 {"bugs", &parsed->bugs_},
2183 {"support", &parsed->support_},
2184 {"sponsor", &parsed->sponsor_},
2185 {"author", &parsed->author_},
2188 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2189 const char *start, *end;
2191 if (parser->Find(names[i].name_, start, end)) {
2192 CYString &value(*names[i].value_);
2193 _profile(Package$parse$Value)
2194 value.set(pool_, start, end - start);
2200 _profile(Package$parse$Tagline)
2201 const char *start, *end;
2202 if (parser->ShortDesc(start, end)) {
2203 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2206 while (stop != start && stop[-1] == '\r')
2208 parsed->tagline_.set(pool_, start, stop - start);
2212 _profile(Package$parse$Retain)
2213 if (parsed->homepage_.empty())
2214 parsed->homepage_ = website;
2215 if (parsed->homepage_ == parsed->depiction_)
2216 parsed->homepage_.clear();
2221 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2222 if ((self = [super init]) != nil) {
2223 _profile(Package$initWithVersion)
2226 database_ = database;
2227 era_ = [database era];
2231 pkgCache::PkgIterator iterator(version.ParentPkg());
2232 iterator_ = iterator;
2234 _profile(Package$initWithVersion$Version)
2235 if (!version_.end())
2236 file_ = version_.FileList();
2238 pkgCache &cache([database_ cache]);
2239 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2243 _profile(Package$initWithVersion$Cache)
2244 name_.set(NULL, iterator.Display());
2246 latest_.set(NULL, StripVersion_(version_.VerStr()));
2248 pkgCache::VerIterator current(iterator.CurrentVer());
2250 installed_.set(NULL, StripVersion_(current.VerStr()));
2253 _profile(Package$initWithVersion$Tags)
2254 pkgCache::TagIterator tag(iterator.TagList());
2256 tags_ = [NSMutableArray arrayWithCapacity:8];
2258 const char *name(tag.Name());
2259 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2261 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2262 if (strcmp(name + 6, "enduser") == 0)
2264 else if (strcmp(name + 6, "hacker") == 0)
2266 else if (strcmp(name + 6, "developer") == 0)
2268 else if (strcmp(name + 6, "cydia") == 0)
2274 if (strncmp(name, "cydia::", 7) == 0) {
2275 if (strcmp(name + 7, "essential") == 0)
2277 else if (strcmp(name + 7, "obsolete") == 0)
2282 } while (!tag.end());
2286 _profile(Package$initWithVersion$Metadata)
2287 const char *mixed(iterator.Name());
2288 size_t size(strlen(mixed));
2289 char lower[size + 1];
2291 for (size_t i(0); i != size; ++i)
2292 lower[i] = mixed[i] | 0x20;
2295 PackageValue *metadata(PackageFind(lower, size));
2296 metadata_ = metadata;
2298 id_.set(NULL, metadata->name_, size);
2300 const char *latest(version_.VerStr());
2301 size_t length(strlen(latest));
2303 uint16_t vhash(hashlittle(latest, length));
2305 size_t capped(std::min<size_t>(8, length));
2306 latest = latest + length - capped;
2308 if (metadata->first_ == 0)
2309 metadata->first_ = now_;
2311 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2312 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2313 metadata->vhash_ = vhash;
2314 metadata->last_ = now_;
2315 } else if (metadata->last_ == 0)
2316 metadata->last_ = metadata->first_;
2319 _profile(Package$initWithVersion$Section)
2320 section_ = iterator.Section();
2323 _profile(Package$initWithVersion$Flags)
2324 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2325 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2330 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2331 pkgCache::VerIterator version;
2333 _profile(Package$packageWithIterator$GetCandidateVer)
2334 version = [database policy]->GetCandidateVer(iterator);
2342 _profile(Package$packageWithIterator$Allocate)
2343 package = [Package allocWithZone:zone];
2346 _profile(Package$packageWithIterator$Initialize)
2348 initWithVersion:version
2355 _profile(Package$packageWithIterator$Autorelease)
2356 package = [package autorelease];
2362 - (pkgCache::PkgIterator) iterator {
2366 - (NSString *) section {
2367 if (section$_ == nil) {
2368 if (section_ == NULL)
2371 _profile(Package$section$mappedSectionForPointer)
2372 section$_ = [database_ mappedSectionForPointer:section_];
2377 - (NSString *) simpleSection {
2378 if (NSString *section = [self section])
2379 return Simplify(section);
2384 - (NSString *) longSection {
2385 return LocalizeSection([self section]);
2388 - (NSString *) shortSection {
2389 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2392 - (NSString *) uri {
2395 pkgIndexFile *index;
2396 pkgCache::PkgFileIterator file(file_.File());
2397 if (![database_ list].FindIndex(file, index))
2399 return [NSString stringWithUTF8String:iterator_->Path];
2400 //return [NSString stringWithUTF8String:file.Site()];
2401 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2405 - (MIMEAddress *) maintainer {
2406 @synchronized (database_) {
2407 if ([database_ era] != era_ || file_.end())
2410 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2411 const std::string &maintainer(parser->Maintainer());
2412 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2416 @synchronized (database_) {
2417 if ([database_ era] != era_ || version_.end())
2420 return version_->InstalledSize;
2423 - (NSString *) longDescription {
2424 @synchronized (database_) {
2425 if ([database_ era] != era_ || file_.end())
2428 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2429 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2431 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2432 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2433 if ([lines count] < 2)
2436 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2437 for (size_t i(1), e([lines count]); i != e; ++i) {
2438 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2439 [trimmed addObject:trim];
2442 return [trimmed componentsJoinedByString:@"\n"];
2445 - (NSString *) shortDescription {
2446 if (parsed_ != NULL)
2447 return static_cast<NSString *>(parsed_->tagline_);
2449 @synchronized (database_) {
2450 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2452 const char *start, *end;
2453 if (!parser.ShortDesc(start, end))
2456 if (end - start > 100)
2460 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2463 while (end != start && end[-1] == '\r')
2467 return [(id) CYStringCreate(start, end - start) autorelease];
2471 _profile(Package$index)
2472 CFStringRef name((CFStringRef) [self name]);
2473 if (CFStringGetLength(name) == 0)
2475 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2476 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2478 return toupper(character);
2482 - (PackageValue *) metadata {
2487 PackageValue *metadata([self metadata]);
2488 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2491 - (bool) subscribed {
2492 return [self metadata]->subscribed_;
2495 - (bool) setSubscribed:(bool)subscribed {
2496 PackageValue *metadata([self metadata]);
2497 if (metadata->subscribed_ == subscribed)
2499 metadata->subscribed_ = subscribed;
2507 - (NSString *) latest {
2511 - (NSString *) installed {
2515 - (BOOL) uninstalled {
2516 return installed_.empty();
2520 return !version_.end();
2523 - (BOOL) upgradableAndEssential:(BOOL)essential {
2524 _profile(Package$upgradableAndEssential)
2525 pkgCache::VerIterator current(iterator_.CurrentVer());
2527 return essential && essential_;
2529 return !version_.end() && version_ != current;
2533 - (BOOL) essential {
2538 return [database_ cache][iterator_].InstBroken();
2541 - (BOOL) unfiltered {
2542 _profile(Package$unfiltered$obsolete)
2543 if (_unlikely(obsolete_))
2547 _profile(Package$unfiltered$hasSupportingRole)
2548 if (_unlikely(![self hasSupportingRole]))
2556 if (![self unfiltered])
2561 _profile(Package$visible$section)
2562 section = [self section];
2565 _profile(Package$visible$isSectionVisible)
2566 if (!isSectionVisible(section))
2574 unsigned char current(iterator_->CurrentState);
2575 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2578 - (BOOL) halfConfigured {
2579 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2582 - (BOOL) halfInstalled {
2583 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2587 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2588 return state.Mode != pkgDepCache::ModeKeep;
2591 - (NSString *) mode {
2592 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2594 switch (state.Mode) {
2595 case pkgDepCache::ModeDelete:
2596 if ((state.iFlags & pkgDepCache::Purge) != 0)
2600 case pkgDepCache::ModeKeep:
2601 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2602 return @"REINSTALL";
2603 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2607 case pkgDepCache::ModeInstall:
2608 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2609 return @"REINSTALL";
2610 else*/ switch (state.Status) {
2612 return @"DOWNGRADE";
2618 return @"NEW_INSTALL";
2629 - (NSString *) name {
2630 return name_.empty() ? id_ : name_;
2633 - (UIImage *) icon {
2634 NSString *section = [self simpleSection];
2637 if (parsed_ != NULL)
2638 if (NSString *href = parsed_->icon_)
2639 if ([href hasPrefix:@"file:///"])
2640 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2641 if (icon == nil) if (section != nil)
2642 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2643 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2644 if ([dicon hasPrefix:@"file:///"])
2645 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2647 icon = [UIImage applicationImageNamed:@"unknown.png"];
2651 - (NSString *) homepage {
2652 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2655 - (NSString *) depiction {
2656 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2659 - (MIMEAddress *) sponsor {
2660 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2663 - (MIMEAddress *) author {
2664 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2667 - (NSString *) support {
2668 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2671 - (NSArray *) files {
2672 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2673 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2676 fin.open([path UTF8String]);
2681 while (std::getline(fin, line))
2682 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2687 - (NSString *) state {
2688 @synchronized (database_) {
2689 if ([database_ era] != era_ || file_.end())
2692 switch (iterator_->CurrentState) {
2693 case pkgCache::State::NotInstalled:
2694 return @"NotInstalled";
2695 case pkgCache::State::UnPacked:
2697 case pkgCache::State::HalfConfigured:
2698 return @"HalfConfigured";
2699 case pkgCache::State::HalfInstalled:
2700 return @"HalfInstalled";
2701 case pkgCache::State::ConfigFiles:
2702 return @"ConfigFiles";
2703 case pkgCache::State::Installed:
2704 return @"Installed";
2705 case pkgCache::State::TriggersAwaited:
2706 return @"TriggersAwaited";
2707 case pkgCache::State::TriggersPending:
2708 return @"TriggersPending";
2711 return (NSString *) [NSNull null];
2714 - (NSString *) selection {
2715 @synchronized (database_) {
2716 if ([database_ era] != era_ || file_.end())
2719 switch (iterator_->SelectedState) {
2720 case pkgCache::State::Unknown:
2722 case pkgCache::State::Install:
2724 case pkgCache::State::Hold:
2726 case pkgCache::State::DeInstall:
2727 return @"DeInstall";
2728 case pkgCache::State::Purge:
2732 return (NSString *) [NSNull null];
2735 - (NSArray *) warnings {
2736 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2737 const char *name(iterator_.Name());
2739 size_t length(strlen(name));
2740 if (length < 2) invalid:
2741 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2742 else for (size_t i(0); i != length; ++i)
2744 /* XXX: technically this is not allowed */
2745 (name[i] < 'A' || name[i] > 'Z') &&
2746 (name[i] < 'a' || name[i] > 'z') &&
2747 (name[i] < '0' || name[i] > '9') &&
2748 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2751 if (strcmp(name, "cydia") != 0) {
2754 bool _private = false;
2757 bool repository = [[self section] isEqualToString:@"Repositories"];
2759 if (NSArray *files = [self files])
2760 for (NSString *file in files)
2761 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2763 else if (!user && [file isEqualToString:@"/User"])
2765 else if (!_private && [file isEqualToString:@"/private"])
2767 else if (!stash && [file isEqualToString:@"/var/stash"])
2770 /* XXX: this is not sensitive enough. only some folders are valid. */
2771 if (cydia && !repository)
2772 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2774 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2776 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2778 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2781 return [warnings count] == 0 ? nil : warnings;
2784 - (NSArray *) applications {
2785 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2787 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2789 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2790 if (NSArray *files = [self files])
2791 for (NSString *file in files)
2792 if (application_r(file)) {
2793 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2794 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2795 if ([id isEqualToString:me])
2798 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2800 display = application_r[1];
2802 NSString *bundle([file stringByDeletingLastPathComponent]);
2803 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2804 if (icon == nil || [icon length] == 0)
2806 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2808 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2809 [applications addObject:application];
2811 [application addObject:id];
2812 [application addObject:display];
2813 [application addObject:url];
2816 return [applications count] == 0 ? nil : applications;
2819 - (Source *) source {
2820 if (source_ == nil) {
2821 @synchronized (database_) {
2822 if ([database_ era] != era_ || file_.end())
2823 source_ = (Source *) [NSNull null];
2825 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2829 return source_ == (Source *) [NSNull null] ? nil : source_;
2836 - (BOOL) matches:(NSArray *)query {
2837 if (query == nil || [query count] == 0)
2846 string = [self name];
2847 length = [string length];
2849 for (NSString *term in query) {
2850 range = [string rangeOfString:term options:MatchCompareOptions_];
2851 if (range.location != NSNotFound)
2852 rank_ -= 6 * 1000000 / length;
2857 length = [string length];
2859 for (NSString *term in query) {
2860 range = [string rangeOfString:term options:MatchCompareOptions_];
2861 if (range.location != NSNotFound)
2862 rank_ -= 6 * 1000000 / length;
2866 string = [self shortDescription];
2867 length = [string length];
2868 NSUInteger stop(std::min<NSUInteger>(length, 100));
2870 for (NSString *term in query) {
2871 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2872 if (range.location != NSNotFound)
2873 rank_ -= 2 * 100000;
2879 - (bool) hasSupportingRole {
2884 if ([Role_ isEqualToString:@"User"])
2888 if ([Role_ isEqualToString:@"Hacker"])
2892 if ([Role_ isEqualToString:@"Developer"])
2897 - (NSArray *) tags {
2901 - (BOOL) hasTag:(NSString *)tag {
2902 return tags_ == nil ? NO : [tags_ containsObject:tag];
2905 - (NSString *) primaryPurpose {
2906 for (NSString *tag in (NSArray *) tags_)
2907 if ([tag hasPrefix:@"purpose::"])
2908 return [tag substringFromIndex:9];
2912 - (NSArray *) purposes {
2913 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2914 for (NSString *tag in (NSArray *) tags_)
2915 if ([tag hasPrefix:@"purpose::"])
2916 [purposes addObject:[tag substringFromIndex:9]];
2917 return [purposes count] == 0 ? nil : purposes;
2920 - (bool) isCommercial {
2921 return [self hasTag:@"cydia::commercial"];
2924 - (void) setIndex:(size_t)index {
2925 if (metadata_->index_ != index)
2926 metadata_->index_ = index;
2929 - (CYString &) cyname {
2930 return name_.empty() ? id_ : name_;
2933 - (uint32_t) compareBySection:(NSArray *)sections {
2934 NSString *section([self section]);
2935 for (size_t i(0), e([sections count]); i != e; ++i) {
2936 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2940 return _not(uint32_t);
2944 @synchronized (database_) {
2945 pkgProblemResolver *resolver = [database_ resolver];
2946 resolver->Clear(iterator_);
2948 pkgCacheFile &cache([database_ cache]);
2949 cache->SetReInstall(iterator_, false);
2950 cache->MarkKeep(iterator_, false);
2954 @synchronized (database_) {
2955 pkgProblemResolver *resolver = [database_ resolver];
2956 resolver->Clear(iterator_);
2957 resolver->Protect(iterator_);
2959 pkgCacheFile &cache([database_ cache]);
2960 cache->SetReInstall(iterator_, false);
2961 cache->MarkInstall(iterator_, false);
2963 pkgDepCache::StateCache &state((*cache)[iterator_]);
2964 if (!state.Install())
2965 cache->SetReInstall(iterator_, true);
2969 @synchronized (database_) {
2970 pkgProblemResolver *resolver = [database_ resolver];
2971 resolver->Clear(iterator_);
2972 resolver->Remove(iterator_);
2973 resolver->Protect(iterator_);
2975 pkgCacheFile &cache([database_ cache]);
2976 cache->SetReInstall(iterator_, false);
2977 cache->MarkDelete(iterator_, true);
2980 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2981 _profile(Package$isUnfilteredAndSearchedForBy)
2984 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2985 value &= [self unfiltered];
2988 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2989 value &= [self matches:query];
2996 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2997 if ([search length] == 0)
3000 _profile(Package$isUnfilteredAndSelectedForBy)
3003 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3004 value &= [self unfiltered];
3007 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3008 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3015 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3016 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3019 - (bool) isVisibleInSection:(NSString *)name {
3020 NSString *section([self section]);
3024 section == nil && [name length] == 0 ||
3025 [name isEqualToString:section]
3026 ) && [self visible];
3029 - (bool) isVisibleInSource:(Source *)source {
3030 return [self source] == source && [self visible];
3035 /* Section Class {{{ */
3036 @interface Section : NSObject {
3041 _H<NSString> localized_;
3044 - (NSComparisonResult) compareByLocalized:(Section *)section;
3045 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3046 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3047 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3048 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3049 - (NSString *) name;
3056 - (void) addToCount;
3058 - (void) setCount:(size_t)count;
3059 - (NSString *) localized;
3063 @implementation Section
3065 - (NSComparisonResult) compareByLocalized:(Section *)section {
3066 NSString *lhs(localized_);
3067 NSString *rhs([section localized]);
3069 /*if ([lhs length] != 0 && [rhs length] != 0) {
3070 unichar lhc = [lhs characterAtIndex:0];
3071 unichar rhc = [rhs characterAtIndex:0];
3073 if (isalpha(lhc) && !isalpha(rhc))
3074 return NSOrderedAscending;
3075 else if (!isalpha(lhc) && isalpha(rhc))
3076 return NSOrderedDescending;
3079 return [lhs compare:rhs options:LaxCompareOptions_];
3082 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3083 if ((self = [self initWithName:name localize:NO]) != nil) {
3084 if (localized != nil)
3085 localized_ = localized;
3089 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3090 return [self initWithName:name row:0 localize:localize];
3093 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3094 if ((self = [super init]) != nil) {
3099 localized_ = LocalizeSection(name_);
3103 /* XXX: localize the index thingees */
3104 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3105 if ((self = [super init]) != nil) {
3106 name_ = [NSString stringWithCharacters:&index length:1];
3112 - (NSString *) name {
3132 - (void) addToCount {
3136 - (void) setCount:(size_t)count {
3140 - (NSString *) localized {
3147 static NSString *Colon_;
3149 static NSString *Error_;
3150 static NSString *Warning_;
3152 class CydiaLogCleaner :
3153 public pkgArchiveCleaner
3156 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3161 /* Database Implementation {{{ */
3162 @implementation Database
3164 + (Database *) sharedInstance {
3165 static _H<Database> instance;
3166 if (instance == nil)
3167 instance = [[[Database alloc] init] autorelease];
3175 - (void) releasePackages {
3176 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3177 CFArrayRemoveAllValues(packages_);
3181 // XXX: actually implement this thing
3183 [self releasePackages];
3184 apr_pool_destroy(pool_);
3185 NSRecycleZone(zone_);
3189 - (void) _readCydia:(NSNumber *)fd {
3190 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3191 std::istream is(&ib);
3194 static Pcre finish_r("^finish:([^:]*)$");
3196 while (std::getline(is, line)) {
3197 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3199 const char *data(line.c_str());
3200 size_t size = line.size();
3201 lprintf("C:%s\n", data);
3203 if (finish_r(data, size)) {
3204 NSString *finish = finish_r[1];
3205 int index = [Finishes_ indexOfObject:finish];
3206 if (index != INT_MAX && index > Finish_)
3216 - (void) _readStatus:(NSNumber *)fd {
3217 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3218 std::istream is(&ib);
3221 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3222 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3224 while (std::getline(is, line)) {
3225 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3227 const char *data(line.c_str());
3228 size_t size(line.size());
3229 lprintf("S:%s\n", data);
3231 if (conffile_r(data, size)) {
3232 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3233 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3234 } else if (strncmp(data, "status: ", 8) == 0) {
3235 // status: <package>: {unpacked,half-configured,installed}
3236 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3237 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3238 } else if (strncmp(data, "processing: ", 12) == 0) {
3239 // processing: configure: config-test
3240 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3241 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3242 } else if (pmstatus_r(data, size)) {
3243 std::string type([pmstatus_r[1] UTF8String]);
3245 NSString *package = pmstatus_r[2];
3246 if ([package isEqualToString:@"dpkg-exec"])
3249 float percent([pmstatus_r[3] floatValue]);
3250 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3252 NSString *string = pmstatus_r[4];
3254 if (type == "pmerror") {
3255 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3256 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3257 } else if (type == "pmstatus") {
3258 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3259 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3260 } else if (type == "pmconffile")
3261 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3263 lprintf("E:unknown pmstatus\n");
3265 lprintf("E:unknown status\n");
3273 - (void) _readOutput:(NSNumber *)fd {
3274 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3275 std::istream is(&ib);
3278 while (std::getline(is, line)) {
3279 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3281 lprintf("O:%s\n", line.c_str());
3283 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3284 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3296 - (Package *) packageWithName:(NSString *)name {
3297 @synchronized (self) {
3298 if (static_cast<pkgDepCache *>(cache_) == NULL)
3300 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3301 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3305 if ((self = [super init]) != nil) {
3312 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3313 apr_pool_create(&pool_, NULL);
3315 size_t capacity(MetaFile_->active_);
3321 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3322 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3326 _assert(pipe(fds) != -1);
3329 _config->Set("APT::Keep-Fds::", cydiafd_);
3330 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3333 detachNewThreadSelector:@selector(_readCydia:)
3335 withObject:[NSNumber numberWithInt:fds[0]]
3338 _assert(pipe(fds) != -1);
3342 detachNewThreadSelector:@selector(_readStatus:)
3344 withObject:[NSNumber numberWithInt:fds[0]]
3347 _assert(pipe(fds) != -1);
3348 _assert(dup2(fds[0], 0) != -1);
3349 _assert(close(fds[0]) != -1);
3351 input_ = fdopen(fds[1], "a");
3353 _assert(pipe(fds) != -1);
3354 _assert(dup2(fds[1], 1) != -1);
3355 _assert(close(fds[1]) != -1);
3358 detachNewThreadSelector:@selector(_readOutput:)
3360 withObject:[NSNumber numberWithInt:fds[0]]
3365 - (pkgCacheFile &) cache {
3369 - (pkgDepCache::Policy *) policy {
3373 - (pkgRecords *) records {
3377 - (pkgProblemResolver *) resolver {
3381 - (pkgAcquire &) fetcher {
3385 - (pkgSourceList &) list {
3389 - (NSArray *) packages {
3390 return (NSArray *) packages_;
3393 - (NSArray *) sources {
3397 - (Source *) sourceWithKey:(NSString *)key {
3398 for (Source *source in [self sources]) {
3399 if ([[source key] isEqualToString:key])
3404 - (bool) popErrorWithTitle:(NSString *)title {
3407 while (!_error->empty()) {
3409 bool warning(!_error->PopMessage(error));
3414 size_t size(error.size());
3415 if (size == 0 || error[size - 1] != '\n')
3417 error.resize(size - 1);
3420 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3422 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3428 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3429 return [self popErrorWithTitle:title] || !success;
3432 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3433 @synchronized (self) {
3436 [self releasePackages];
3439 [sourceList_ removeAllObjects];
3459 apr_pool_clear(pool_);
3461 NSRecycleZone(zone_);
3462 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3464 int chk(creat("/tmp/cydia.chk", 0644));
3468 if (invocation != nil)
3469 [invocation invoke];
3471 NSString *title(UCLocalize("DATABASE"));
3474 OpProgress progress;
3475 while (!cache_.Open(progress, true)) { pop:
3477 bool warning(!_error->PopMessage(error));
3478 lprintf("cache_.Open():[%s]\n", error.c_str());
3480 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3481 [delegate_ repairWithSelector:@selector(configure)];
3482 else if (error == "The package lists or status file could not be parsed or opened.")
3483 [delegate_ repairWithSelector:@selector(update)];
3484 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3485 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3486 // else if (error == "Malformed Status line")
3487 // else if (error == "The list of sources could not be read.")
3489 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3499 unlink("/tmp/cydia.chk");
3501 now_ = [[NSDate date] timeIntervalSince1970];
3503 policy_ = new pkgDepCache::Policy();
3504 records_ = new pkgRecords(cache_);
3505 resolver_ = new pkgProblemResolver(cache_);
3506 fetcher_ = new pkgAcquire(&status_);
3509 list_ = new pkgSourceList();
3510 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3513 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3514 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3518 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3521 if (cache_->BrokenCount() != 0) {
3522 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3525 if (cache_->BrokenCount() != 0) {
3526 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3530 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3534 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3535 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3536 [sourceList_ addObject:object];
3538 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3539 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3540 // XXX: this could be more intelligent
3541 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3542 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3544 sourceMap_[cached->ID] = object;
3549 /*std::vector<Package *> packages;
3550 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3555 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3556 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3557 //packages.push_back(package);
3558 CFArrayAppendValue(packages_, CFRetain(package));
3562 /*if (packages.empty())
3563 packages_ = [[NSArray alloc] init];
3565 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3568 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3569 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3570 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3578 /*if (!packages.empty())
3579 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3580 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3582 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3584 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3586 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3590 size_t count(CFArrayGetCount(packages_));
3591 MetaFile_->active_ = count;
3593 for (size_t index(0); index != count; ++index)
3594 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3601 @synchronized (self) {
3603 resolver_ = new pkgProblemResolver(cache_);
3605 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3606 if (!cache_[iterator].Keep())
3607 cache_->MarkKeep(iterator, false);
3608 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3609 cache_->SetReInstall(iterator, false);
3612 - (void) configure {
3613 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3615 system([dpkg UTF8String]);
3620 // XXX: I don't remember this condition
3625 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3627 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3629 if ([self popErrorWithTitle:title])
3633 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3635 CydiaLogCleaner cleaner;
3636 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3643 fetcher_->Shutdown();
3645 pkgRecords records(cache_);
3647 lock_ = new FileFd();
3648 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3650 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3652 if ([self popErrorWithTitle:title])
3656 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3659 manager_ = (_system->CreatePM(cache_));
3660 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3667 bool substrate(RestartSubstrate_);
3668 RestartSubstrate_ = false;
3670 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3672 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3674 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3676 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3677 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3680 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3682 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3684 [self popErrorWithTitle:title];
3688 bool failed = false;
3689 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3690 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3692 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3698 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3706 RestartSubstrate_ = true;
3709 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3711 if (_error->PendingError()) {
3716 if (result == pkgPackageManager::Failed) {
3721 if (result != pkgPackageManager::Completed) {
3726 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3728 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3730 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3731 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3734 if (![before isEqualToArray:after])
3739 NSString *title(UCLocalize("UPGRADE"));
3740 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3746 [self updateWithStatus:status_];
3749 - (void) updateWithStatus:(Status &)status {
3750 NSString *title(UCLocalize("REFRESHING_DATA"));
3753 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3757 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3758 if ([self popErrorWithTitle:title])
3761 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3763 bool success(ListUpdate(status, list, PulseInterval_));
3764 if (status.WasCancelled())
3767 [self popErrorWithTitle:title forOperation:success];
3768 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3772 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3775 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3776 delegate_ = delegate;
3779 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3780 progress_ = delegate;
3781 status_.setDelegate(delegate);
3784 - (NSObject<ProgressDelegate> *) progressDelegate {
3788 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3789 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3790 return i == sourceMap_.end() ? nil : i->second;
3793 - (NSString *) mappedSectionForPointer:(const char *)section {
3794 _H<NSString> *mapped;
3796 _profile(Database$mappedSectionForPointer$Cache)
3797 mapped = §ions_[section];
3800 if (*mapped == NULL) {
3801 size_t length(strlen(section));
3802 char spaced[length + 1];
3804 _profile(Database$mappedSectionForPointer$Replace)
3805 for (size_t index(0); index != length; ++index)
3806 spaced[index] = section[index] == '_' ? ' ' : section[index];
3807 spaced[length] = '\0';
3812 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3813 string = [NSString stringWithUTF8String:spaced];
3816 _profile(Database$mappedSectionForPointer$Map)
3817 string = [SectionMap_ objectForKey:string] ?: string;
3827 static _H<NSMutableSet> Diversions_;
3829 @interface Diversion : NSObject {
3832 _H<NSString> format_;
3837 @implementation Diversion
3839 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3840 if ((self = [super init]) != nil) {
3841 pattern_ = [from UTF8String];
3847 - (NSString *) divert:(NSString *)url {
3848 return !pattern_(url) ? nil : pattern_->*format_;
3851 + (NSURL *) divertURL:(NSURL *)url {
3853 NSString *href([url absoluteString]);
3855 for (Diversion *diversion in (id) Diversions_)
3856 if (NSString *diverted = [diversion divert:href]) {
3858 NSLog(@"div: %@", diverted);
3860 url = [NSURL URLWithString:diverted];
3867 - (NSString *) key {
3871 - (NSUInteger) hash {
3875 - (BOOL) isEqual:(Diversion *)object {
3876 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3881 @interface CydiaObject : NSObject {
3882 _H<IndirectDelegate> indirect_;
3883 _transient id delegate_;
3886 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3890 @interface CydiaWebViewController : CyteWebViewController {
3891 _H<CydiaObject> cydia_;
3894 + (void) addDiversion:(Diversion *)diversion;
3898 /* Web Scripting {{{ */
3899 @implementation CydiaObject
3901 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3902 if ((self = [super init]) != nil) {
3903 indirect_ = indirect;
3907 - (void) setDelegate:(id)delegate {
3908 delegate_ = delegate;
3911 + (NSArray *) _attributeKeys {
3912 return [NSArray arrayWithObjects:
3929 - (NSArray *) attributeKeys {
3930 return [[self class] _attributeKeys];
3933 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3934 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3937 - (NSString *) version {
3941 - (NSString *) device {
3942 return [[UIDevice currentDevice] uniqueIdentifier];
3945 - (NSString *) firmware {
3946 return [[UIDevice currentDevice] systemVersion];
3949 - (NSString *) hostname {
3950 return [[UIDevice currentDevice] name];
3953 - (NSString *) idiom {
3954 return (id) Idiom_ ?: [NSNull null];
3957 - (NSString *) plmn {
3958 return (id) PLMN_ ?: [NSNull null];
3961 - (NSString *) bbsnum {
3962 return (id) BBSNum_ ?: [NSNull null];
3965 - (NSString *) ecid {
3966 return (id) ChipID_ ?: [NSNull null];
3969 - (NSString *) serial {
3970 return SerialNumber_;
3973 - (NSString *) role {
3974 return (id) Role_ ?: [NSNull null];
3977 - (NSString *) model {
3978 return [NSString stringWithUTF8String:Machine_];
3981 - (NSString *) token {
3982 return (id) Token_ ?: [NSNull null];
3985 + (NSString *) webScriptNameForSelector:(SEL)selector {
3987 else if (selector == @selector(addBridgedHost:))
3988 return @"addBridgedHost";
3989 else if (selector == @selector(addInsecureHost:))
3990 return @"addInsecureHost";
3991 else if (selector == @selector(addInternalRedirect::))
3992 return @"addInternalRedirect";
3993 else if (selector == @selector(addPipelinedHost:scheme:))
3994 return @"addPipelinedHost";
3995 else if (selector == @selector(addSource:::))
3996 return @"addSource";
3997 else if (selector == @selector(addTokenHost:))
3998 return @"addTokenHost";
3999 else if (selector == @selector(addTrivialSource:))
4000 return @"addTrivialSource";
4001 else if (selector == @selector(close))
4003 else if (selector == @selector(du:))
4005 else if (selector == @selector(stringWithFormat:arguments:))
4007 else if (selector == @selector(getAllSources))
4008 return @"getAllSourcs";
4009 else if (selector == @selector(getKernelNumber:))
4010 return @"getKernelNumber";
4011 else if (selector == @selector(getKernelString:))
4012 return @"getKernelString";
4013 else if (selector == @selector(getInstalledPackages))
4014 return @"getInstalledPackages";
4015 else if (selector == @selector(getIORegistryEntry::))
4016 return @"getIORegistryEntry";
4017 else if (selector == @selector(getLocaleIdentifier))
4018 return @"getLocaleIdentifier";
4019 else if (selector == @selector(getPreferredLanguages))
4020 return @"getPreferredLanguages";
4021 else if (selector == @selector(getPackageById:))
4022 return @"getPackageById";
4023 else if (selector == @selector(getMetadataKeys))
4024 return @"getMetadataKeys";
4025 else if (selector == @selector(getMetadataValue:))
4026 return @"getMetadataValue";
4027 else if (selector == @selector(getSessionValue:))
4028 return @"getSessionValue";
4029 else if (selector == @selector(installPackages:))
4030 return @"installPackages";
4031 else if (selector == @selector(localizedStringForKey:value:table:))
4033 else if (selector == @selector(popViewController:))
4034 return @"popViewController";
4035 else if (selector == @selector(refreshSources))
4036 return @"refreshSources";
4037 else if (selector == @selector(removeButton))
4038 return @"removeButton";
4039 else if (selector == @selector(saveConfig))
4040 return @"saveConfig";
4041 else if (selector == @selector(setCydiaSource:))
4042 return @"setCydiaSource";
4043 else if (selector == @selector(setMetadataValue::))
4044 return @"setMetadataValue";
4045 else if (selector == @selector(setSessionValue::))
4046 return @"setSessionValue";
4047 else if (selector == @selector(substitutePackageNames:))
4048 return @"substitutePackageNames";
4049 else if (selector == @selector(scrollToBottom:))
4050 return @"scrollToBottom";
4051 else if (selector == @selector(setAllowsNavigationAction:))
4052 return @"setAllowsNavigationAction";
4053 else if (selector == @selector(setBadgeValue:))
4054 return @"setBadgeValue";
4055 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4056 return @"setButtonImage";
4057 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4058 return @"setButtonTitle";
4059 else if (selector == @selector(setHidesBackButton:))
4060 return @"setHidesBackButton";
4061 else if (selector == @selector(setHidesNavigationBar:))
4062 return @"setHidesNavigationBar";
4063 else if (selector == @selector(setNavigationBarStyle:))
4064 return @"setNavigationBarStyle";
4065 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4066 return @"setNavigationBarTintColor";
4067 else if (selector == @selector(setPasteboardString:))
4068 return @"setPasteboardString";
4069 else if (selector == @selector(setPasteboardURL:))
4070 return @"setPasteboardURL";
4071 else if (selector == @selector(setToken:))
4073 else if (selector == @selector(setViewportWidth:))
4074 return @"setViewportWidth";
4075 else if (selector == @selector(statfs:))
4077 else if (selector == @selector(supports:))
4079 else if (selector == @selector(unload))
4085 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4086 return [self webScriptNameForSelector:selector] == nil;
4089 - (BOOL) supports:(NSString *)feature {
4090 return [feature isEqualToString:@"window.open"];
4094 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4097 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4098 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4101 - (NSNumber *) getKernelNumber:(NSString *)name {
4102 const char *string([name UTF8String]);
4105 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4106 return (id) [NSNull null];
4108 if (size != sizeof(int))
4109 return (id) [NSNull null];
4112 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4113 return (id) [NSNull null];
4115 return [NSNumber numberWithInt:value];
4118 - (NSString *) getKernelString:(NSString *)name {
4119 const char *string([name UTF8String]);
4122 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4123 return (id) [NSNull null];
4125 char value[size + 1];
4126 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4127 return (id) [NSNull null];
4129 // XXX: just in case you request something ludicrous
4132 return [NSString stringWithCString:value];
4135 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4136 NSObject *value(CYIOGetValue([path UTF8String], entry));
4139 if ([value isKindOfClass:[NSData class]])
4140 value = CYHex((NSData *) value);
4145 - (void) _setCydiaSource:(NSString *)source {
4146 @synchronized (HostConfig_) {
4147 CydiaSource_ = source;
4148 [Metadata_ setObject:source forKey:@"CydiaSource"];
4154 - (void) setCydiaSource:(NSString *)source {
4155 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4158 - (NSString *) cydiaSource {
4159 @synchronized (HostConfig_) {
4160 return (id) CydiaSource_ ?: [NSNull null];
4164 - (NSArray *) getMetadataKeys {
4165 @synchronized (Values_) {
4166 return [Values_ allKeys];
4169 - (id) getMetadataValue:(NSString *)key {
4170 @synchronized (Values_) {
4171 return [Values_ objectForKey:key];
4174 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4175 @synchronized (Values_) {
4176 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4177 [Values_ removeObjectForKey:key];
4179 [Values_ setObject:value forKey:key];
4181 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4184 - (id) getSessionValue:(NSString *)key {
4185 @synchronized (SessionData_) {
4186 return [SessionData_ objectForKey:key];
4189 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4190 @synchronized (SessionData_) {
4191 if (value == (id) [WebUndefined undefined])
4192 [SessionData_ removeObjectForKey:key];
4194 [SessionData_ setObject:value forKey:key];
4197 - (void) addBridgedHost:(NSString *)host {
4198 @synchronized (HostConfig_) {
4199 [BridgedHosts_ addObject:host];
4202 - (void) addInsecureHost:(NSString *)host {
4203 @synchronized (HostConfig_) {
4204 [InsecureHosts_ addObject:host];
4207 - (void) addTokenHost:(NSString *)host {
4208 @synchronized (HostConfig_) {
4209 [TokenHosts_ addObject:host];
4212 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4213 @synchronized (HostConfig_) {
4214 if (scheme != (id) [WebUndefined undefined])
4215 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4217 [PipelinedHosts_ addObject:host];
4220 - (void) popViewController:(NSNumber *)value {
4221 if (value == (id) [WebUndefined undefined])
4222 value = [NSNumber numberWithBool:YES];
4223 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4226 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4227 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4229 for (NSString *section in sections)
4230 [array addObject:section];
4232 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4235 distribution, @"Distribution",
4237 nil] waitUntilDone:NO];
4240 - (void) addTrivialSource:(NSString *)href {
4241 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4244 - (void) refreshSources {
4245 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4248 - (void) saveConfig {
4249 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4252 - (NSArray *) getAllSources {
4253 return [[Database sharedInstance] sources];
4256 - (NSArray *) getInstalledPackages {
4257 Database *database([Database sharedInstance]);
4258 @synchronized (database) {
4259 NSArray *packages([database packages]);
4260 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4261 for (Package *package in packages)
4262 if (![package uninstalled])
4263 [installed addObject:package];
4267 - (Package *) getPackageById:(NSString *)id {
4268 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4272 return (Package *) [NSNull null];
4275 - (NSString *) getLocaleIdentifier {
4276 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4279 - (NSArray *) getPreferredLanguages {
4283 - (NSArray *) statfs:(NSString *)path {
4286 if (path == nil || statfs([path UTF8String], &stat) == -1)
4289 return [NSArray arrayWithObjects:
4290 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4291 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4292 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4296 - (NSNumber *) du:(NSString *)path {
4297 NSNumber *value(nil);
4300 _assert(pipe(fds) != -1);
4302 pid_t pid(ExecFork());
4304 _assert(dup2(fds[1], 1) != -1);
4305 _assert(close(fds[0]) != -1);
4306 _assert(close(fds[1]) != -1);
4307 /* XXX: this should probably not use du */
4308 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4313 _assert(close(fds[1]) != -1);
4315 if (FILE *du = fdopen(fds[0], "r")) {
4317 while (fgets(line, sizeof(line), du) != NULL) {
4318 size_t length(strlen(line));
4319 while (length != 0 && line[length - 1] == '\n')
4320 line[--length] = '\0';
4321 if (char *tab = strchr(line, '\t')) {
4323 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4328 } else _assert(close(fds[0]));
4332 if (waitpid(pid, &status, 0) == -1)
4335 else _assert(false);
4341 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4344 - (void) installPackages:(NSArray *)packages {
4345 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4348 - (NSString *) substitutePackageNames:(NSString *)message {
4349 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4350 for (size_t i(0), e([words count]); i != e; ++i) {
4351 NSString *word([words objectAtIndex:i]);
4352 if (Package *package = [[Database sharedInstance] packageWithName:word])
4353 [words replaceObjectAtIndex:i withObject:[package name]];
4356 return [words componentsJoinedByString:@" "];
4359 - (void) removeButton {
4360 [indirect_ removeButton];
4363 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4364 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4367 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4368 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4371 - (void) setBadgeValue:(id)value {
4372 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4375 - (void) setAllowsNavigationAction:(NSString *)value {
4376 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4379 - (void) setHidesBackButton:(NSString *)value {
4380 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4383 - (void) setHidesNavigationBar:(NSString *)value {
4384 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4387 - (void) setNavigationBarStyle:(NSString *)value {
4388 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4391 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4392 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4393 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4394 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4397 - (void) setPasteboardString:(NSString *)value {
4398 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4401 - (void) setPasteboardURL:(NSString *)value {
4402 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4405 - (void) _setToken:(NSString *)token {
4409 [Metadata_ removeObjectForKey:@"Token"];
4411 [Metadata_ setObject:Token_ forKey:@"Token"];
4416 - (void) setToken:(NSString *)token {
4417 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4420 - (void) scrollToBottom:(NSNumber *)animated {
4421 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4424 - (void) setViewportWidth:(float)width {
4425 [indirect_ setViewportWidthOnMainThread:width];
4428 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4429 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4430 unsigned count([arguments count]);
4432 for (unsigned i(0); i != count; ++i)
4433 values[i] = [arguments objectAtIndex:i];
4434 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4437 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4438 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4440 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4442 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4448 @interface NSURL (CydiaSecure)
4451 @implementation NSURL (CydiaSecure)
4453 - (bool) isCydiaSecure {
4454 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4457 @synchronized (HostConfig_) {
4458 if ([InsecureHosts_ containsObject:[self host]])
4467 /* Cydia Browser Controller {{{ */
4468 @implementation CydiaWebViewController
4470 - (NSURL *) navigationURL {
4471 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4474 + (void) initialize {
4475 Diversions_ = [NSMutableSet setWithCapacity:0];
4478 + (void) addDiversion:(Diversion *)diversion {
4479 [Diversions_ addObject:diversion];
4482 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4483 [super webView:view didClearWindowObject:window forFrame:frame];
4485 WebDataSource *source([frame dataSource]);
4486 NSURLResponse *response([source response]);
4487 NSURL *url([response URL]);
4488 NSString *scheme([[url scheme] lowercaseString]);
4490 bool bridged(false);
4492 @synchronized (HostConfig_) {
4493 if ([scheme isEqualToString:@"file"])
4495 else if ([scheme isEqualToString:@"https"])
4496 if ([BridgedHosts_ containsObject:[url host]])
4501 [window setValue:cydia_ forKey:@"cydia"];
4504 - (void) _setupMail:(MFMailComposeViewController *)controller {
4505 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4507 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4508 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4511 - (NSURL *) URLWithURL:(NSURL *)url {
4512 return [Diversion divertURL:url];
4515 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4516 NSURL *url([request URL]);
4517 NSString *host([url host]);
4519 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4521 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4522 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4523 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4524 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4527 @synchronized (HostConfig_) {
4528 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4531 if ([url isCydiaSecure] && token) {
4532 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4533 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4539 - (void) setDelegate:(id)delegate {
4540 [super setDelegate:delegate];
4541 [cydia_ setDelegate:delegate];
4544 - (NSString *) applicationNameForUserAgent {
4545 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4548 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4550 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4551 if (Product_ != nil)
4552 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4558 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4559 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4567 @interface NSObject (CydiaScript)
4568 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4571 @implementation NSObject (CydiaScript)
4573 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4579 @implementation NSArray (CydiaScript)
4581 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4582 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4583 for (size_t i(0), e([self count]); i != e; ++i)
4584 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4590 @implementation NSDictionary (CydiaScript)
4592 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4593 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4595 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4602 /* Confirmation Controller {{{ */
4603 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4604 if (!iterator.end())
4605 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4606 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4608 pkgCache::PkgIterator package(dep.TargetPkg());
4611 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4618 @protocol ConfirmationControllerDelegate
4619 - (void) cancelAndClear:(bool)clear;
4620 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4624 @interface ConfirmationController : CydiaWebViewController {
4625 _transient Database *database_;
4627 _H<UIAlertView> essential_;
4629 _H<NSDictionary> changes_;
4630 _H<NSMutableArray> issues_;
4631 _H<NSDictionary> sizes_;
4636 - (id) initWithDatabase:(Database *)database;
4640 @implementation ConfirmationController
4644 RestartSubstrate_ = true;
4645 [delegate_ confirmWithNavigationController:[self navigationController]];
4648 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4649 NSString *context([alert context]);
4651 if ([context isEqualToString:@"remove"]) {
4652 if (button == [alert cancelButtonIndex])
4653 [self dismissModalViewControllerAnimated:YES];
4654 else if (button == [alert firstOtherButtonIndex]) {
4658 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4659 } else if ([context isEqualToString:@"unable"]) {
4660 [self dismissModalViewControllerAnimated:YES];
4661 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4663 [super alertView:alert clickedButtonAtIndex:button];
4667 - (void) _doContinue {
4668 [self dismissModalViewControllerAnimated:YES];
4669 [delegate_ cancelAndClear:NO];
4672 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4673 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4677 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4678 [super webView:view didClearWindowObject:window forFrame:frame];
4680 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4681 (id) changes_, @"changes",
4682 (id) issues_, @"issues",
4683 (id) sizes_, @"sizes",
4685 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4688 - (id) initWithDatabase:(Database *)database {
4689 if ((self = [super init]) != nil) {
4690 database_ = database;
4692 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4693 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4694 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4695 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4696 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4700 pkgCacheFile &cache([database_ cache]);
4701 NSArray *packages([database_ packages]);
4702 pkgDepCache::Policy *policy([database_ policy]);
4704 issues_ = [NSMutableArray arrayWithCapacity:4];
4706 for (Package *package in packages) {
4707 pkgCache::PkgIterator iterator([package iterator]);
4708 NSString *name([package id]);
4710 if ([package broken]) {
4711 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4713 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4715 reasons, @"reasons",
4718 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4722 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4723 pkgCache::DepIterator start;
4724 pkgCache::DepIterator end;
4725 dep.GlobOr(start, end); // ++dep
4727 if (!cache->IsImportantDep(end))
4729 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4732 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4734 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4735 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4736 clauses, @"clauses",
4740 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4742 pkgCache::PkgIterator target(start.TargetPkg());
4743 if (target->ProvidesList != 0)
4744 reason = @"missing";
4746 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4748 reason = @"installed";
4749 installed = [NSString stringWithUTF8String:ver.VerStr()];
4750 } else if (!cache[target].CandidateVerIter(cache).end())
4751 reason = @"uninstalled";
4752 else if (target->ProvidesList == 0)
4753 reason = @"uninstallable";
4755 reason = @"virtual";
4758 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4759 [NSString stringWithUTF8String:start.CompType()], @"operator",
4760 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4763 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4764 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4765 version, @"version",
4767 installed, @"installed",
4770 // yes, seriously. (wtf?)
4778 pkgDepCache::StateCache &state(cache[iterator]);
4780 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4782 if (state.NewInstall())
4783 [installs addObject:name];
4784 // XXX: else if (state.Install())
4785 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4786 [reinstalls addObject:name];
4787 // XXX: move before previous if
4788 else if (state.Upgrade())
4789 [upgrades addObject:name];
4790 else if (state.Downgrade())
4791 [downgrades addObject:name];
4792 else if (!state.Delete())
4793 // XXX: _assert(state.Keep());
4795 else if (special_r(name))
4796 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4797 [NSNull null], @"package",
4798 [NSArray arrayWithObjects:
4799 [NSDictionary dictionaryWithObjectsAndKeys:
4800 @"Conflicts", @"relationship",
4801 [NSArray arrayWithObjects:
4802 [NSDictionary dictionaryWithObjectsAndKeys:
4804 [NSNull null], @"version",
4805 @"installed", @"reason",
4812 if ([package essential])
4814 [removes addObject:name];
4817 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4818 substrate_ |= DepSubstrate(iterator.CurrentVer());
4823 else if (Advanced_) {
4824 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4826 essential_ = [[[UIAlertView alloc]
4827 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4828 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4830 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4832 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4836 [essential_ setContext:@"remove"];
4838 essential_ = [[[UIAlertView alloc]
4839 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4840 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4842 cancelButtonTitle:UCLocalize("OKAY")
4843 otherButtonTitles:nil
4846 [essential_ setContext:@"unable"];
4849 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4850 installs, @"installs",
4851 reinstalls, @"reinstalls",
4852 upgrades, @"upgrades",
4853 downgrades, @"downgrades",
4854 removes, @"removes",
4857 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4858 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4859 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4862 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4866 - (UIBarButtonItem *) leftButton {
4867 return [[[UIBarButtonItem alloc]
4868 initWithTitle:UCLocalize("CANCEL")
4869 style:UIBarButtonItemStylePlain
4871 action:@selector(cancelButtonClicked)
4876 - (void) applyRightButton {
4877 if ([issues_ count] == 0 && ![self isLoading])
4878 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4879 initWithTitle:UCLocalize("CONFIRM")
4880 style:UIBarButtonItemStyleDone
4882 action:@selector(confirmButtonClicked)
4885 [[self navigationItem] setRightBarButtonItem:nil];
4889 - (void) cancelButtonClicked {
4890 [self dismissModalViewControllerAnimated:YES];
4891 [delegate_ cancelAndClear:YES];
4895 - (void) confirmButtonClicked {
4896 if (essential_ != nil)
4906 /* Progress Data {{{ */
4907 @interface CydiaProgressData : NSObject {
4908 _transient id delegate_;
4917 _H<NSMutableArray> events_;
4918 _H<NSString> title_;
4920 _H<NSString> status_;
4921 _H<NSString> finish_;
4926 @implementation CydiaProgressData
4928 + (NSArray *) _attributeKeys {
4929 return [NSArray arrayWithObjects:
4941 - (NSArray *) attributeKeys {
4942 return [[self class] _attributeKeys];
4945 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4946 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4950 if ((self = [super init]) != nil) {
4951 events_ = [NSMutableArray arrayWithCapacity:32];
4955 - (void) setDelegate:(id)delegate {
4956 delegate_ = delegate;
4959 - (void) setPercent:(float)value {
4963 - (NSNumber *) percent {
4964 return [NSNumber numberWithFloat:percent_];
4967 - (void) setCurrent:(float)value {
4971 - (NSNumber *) current {
4972 return [NSNumber numberWithFloat:current_];
4975 - (void) setTotal:(float)value {
4979 - (NSNumber *) total {
4980 return [NSNumber numberWithFloat:total_];
4983 - (void) setSpeed:(float)value {
4987 - (NSNumber *) speed {
4988 return [NSNumber numberWithFloat:speed_];
4991 - (NSArray *) events {
4995 - (void) removeAllEvents {
4996 [events_ removeAllObjects];
4999 - (void) addEvent:(CydiaProgressEvent *)event {
5000 [events_ addObject:event];
5003 - (void) setTitle:(NSString *)text {
5007 - (NSString *) title {
5011 - (void) setFinish:(NSString *)text {
5015 - (NSString *) finish {
5016 return (id) finish_ ?: [NSNull null];
5019 - (void) setRunning:(bool)running {
5023 - (NSNumber *) running {
5024 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5029 /* Progress Controller {{{ */
5030 @interface ProgressController : CydiaWebViewController <
5033 _transient Database *database_;
5034 _H<CydiaProgressData, 1> progress_;
5038 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5040 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5042 - (void) setTitle:(NSString *)title;
5043 - (void) setCancellable:(bool)cancellable;
5047 @implementation ProgressController
5050 [database_ setProgressDelegate:nil];
5054 - (UIBarButtonItem *) leftButton {
5055 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5056 initWithTitle:UCLocalize("CANCEL")
5057 style:UIBarButtonItemStylePlain
5059 action:@selector(cancel)
5060 ] autorelease] : nil;
5063 - (void) updateCancel {
5064 [super applyLeftButton];
5067 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5068 if ((self = [super init]) != nil) {
5069 database_ = database;
5070 delegate_ = delegate;
5072 [database_ setProgressDelegate:self];
5074 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5075 [progress_ setDelegate:self];
5077 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5079 [scroller_ setBackgroundColor:[UIColor blackColor]];
5081 [[self navigationItem] setHidesBackButton:YES];
5083 [self updateCancel];
5087 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5088 [super webView:view didClearWindowObject:window forFrame:frame];
5089 [window setValue:progress_ forKey:@"cydiaProgress"];
5092 - (void) updateProgress {
5093 [self dispatchEvent:@"CydiaProgressUpdate"];
5096 - (void) viewWillAppear:(BOOL)animated {
5097 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5098 [super viewWillAppear:animated];
5102 UpdateExternalStatus(0);
5105 [delegate_ saveState];
5112 [delegate_ terminateWithSuccess];
5113 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5114 [delegate_ suspendWithAnimation:YES];
5116 [delegate_ suspend];*/
5128 system("/usr/bin/sbreload");
5134 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5135 SBReboot(SBSSpringBoardServerPort());
5137 reboot2(RB_AUTOBOOT);
5144 - (void) setTitle:(NSString *)title {
5145 [progress_ setTitle:title];
5146 [self updateProgress];
5149 - (UIBarButtonItem *) rightButton {
5150 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5151 initWithTitle:UCLocalize("CLOSE")
5152 style:UIBarButtonItemStylePlain
5154 action:@selector(close)
5158 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5159 UpdateExternalStatus(1);
5161 [progress_ setRunning:true];
5162 [self setTitle:title];
5163 // implicit updateProgress
5165 SHA1SumValue notifyconf; {
5167 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5170 MMap mmap(file, MMap::ReadOnly);
5172 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5173 notifyconf = sha1.Result();
5177 SHA1SumValue springlist; {
5179 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5182 MMap mmap(file, MMap::ReadOnly);
5184 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5185 springlist = sha1.Result();
5189 if (invocation != nil) {
5190 [invocation yieldToSelector:@selector(invoke)];
5191 [self setTitle:@"COMPLETE"];
5196 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5199 MMap mmap(file, MMap::ReadOnly);
5201 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5202 if (!(notifyconf == sha1.Result()))
5209 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5212 MMap mmap(file, MMap::ReadOnly);
5214 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5215 if (!(springlist == sha1.Result()))
5221 if (RestartSubstrate_)
5225 RestartSubstrate_ = false;
5228 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5229 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5230 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5231 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5232 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5236 system("su -c /usr/bin/uicache mobile");
5239 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5241 [progress_ setRunning:false];
5242 [self updateProgress];
5244 [self applyRightButton];
5247 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5248 [progress_ addEvent:event];
5249 [self updateProgress];
5252 - (bool) isProgressCancelled {
5253 return cancel_ == 2;
5258 [self updateCancel];
5261 - (void) setCancellable:(bool)cancellable {
5262 unsigned cancel(cancel_);
5266 else if (cancel_ == 0)
5269 if (cancel != cancel_)
5270 [self updateCancel];
5273 - (void) setProgressCancellable:(NSNumber *)cancellable {
5274 [self setCancellable:[cancellable boolValue]];
5277 - (void) setProgressPercent:(NSNumber *)percent {
5278 [progress_ setPercent:[percent floatValue]];
5279 [self updateProgress];
5282 - (void) setProgressStatus:(NSDictionary *)status {
5283 if (status == nil) {
5284 [progress_ setCurrent:0];
5285 [progress_ setTotal:0];
5286 [progress_ setSpeed:0];
5288 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5290 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5291 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5292 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5295 [self updateProgress];
5301 /* Package Cell {{{ */
5302 @interface PackageCell : CyteTableViewCell <
5303 CyteTableViewCellDelegate
5307 _H<NSString> description_;
5309 _H<NSString> source_;
5311 _H<UIImage> placard_;
5315 - (PackageCell *) init;
5316 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5318 - (void) drawContentRect:(CGRect)rect;
5322 @implementation PackageCell
5324 - (PackageCell *) init {
5325 CGRect frame(CGRectMake(0, 0, 320, 74));
5326 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5327 UIView *content([self contentView]);
5328 CGRect bounds([content bounds]);
5330 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5331 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5332 [content addSubview:content_];
5334 [content_ setDelegate:self];
5335 [content_ setOpaque:YES];
5339 - (NSString *) accessibilityLabel {
5340 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5343 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5344 summarized_ = summary;
5355 Source *source = [package source];
5357 icon_ = [package icon];
5359 if (NSString *name = [package name])
5360 name_ = [NSString stringWithString:name];
5362 NSString *description(nil);
5364 if (description == nil && IsWildcat_)
5365 description = [package longDescription];
5366 if (description == nil)
5367 description = [package shortDescription];
5369 if (description != nil)
5370 description_ = [NSString stringWithString:description];
5372 commercial_ = [package isCommercial];
5374 NSString *label = nil;
5375 bool trusted = false;
5377 if (source != nil) {
5378 label = [source label];
5379 trusted = [source trusted];
5380 } else if ([[package id] isEqualToString:@"firmware"])
5381 label = UCLocalize("APPLE");
5383 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5385 NSString *from(label);
5387 NSString *section = [package simpleSection];
5388 if (section != nil && ![section isEqualToString:label]) {
5389 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5390 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5393 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5395 if (NSString *purpose = [package primaryPurpose])
5396 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5401 if (NSString *mode = [package mode]) {
5402 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5403 color = RemovingColor_;
5404 //placard = @"removing";
5406 color = InstallingColor_;
5407 //placard = @"installing";
5410 // XXX: the removing/installing placards are not @2x
5413 color = [UIColor whiteColor];
5415 if ([package installed] != nil)
5416 placard = @"installed";
5421 [content_ setBackgroundColor:color];
5424 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5426 [self setNeedsDisplay];
5427 [content_ setNeedsDisplay];
5430 - (void) drawSummaryContentRect:(CGRect)rect {
5431 bool highlighted(highlighted_);
5432 float width([self bounds].size.width);
5436 rect.size = [(UIImage *) icon_ size];
5438 rect.size.width /= 4;
5439 rect.size.height /= 4;
5441 rect.origin.x = 14 - rect.size.width / 4;
5442 rect.origin.y = 14 - rect.size.height / 4;
5444 [icon_ drawInRect:rect];
5447 if (badge_ != nil) {
5449 rect.size = [(UIImage *) badge_ size];
5451 rect.size.width /= 4;
5452 rect.size.height /= 4;
5454 rect.origin.x = 20 - rect.size.width / 4;
5455 rect.origin.y = 20 - rect.size.height / 4;
5457 [badge_ drawInRect:rect];
5464 UISetColor(commercial_ ? Purple_ : Black_);
5465 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5467 if (placard_ != nil)
5468 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5471 - (void) drawNormalContentRect:(CGRect)rect {
5472 bool highlighted(highlighted_);
5473 float width([self bounds].size.width);
5477 rect.size = [(UIImage *) icon_ size];
5479 rect.size.width /= 2;
5480 rect.size.height /= 2;
5482 rect.origin.x = 25 - rect.size.width / 2;
5483 rect.origin.y = 25 - rect.size.height / 2;
5485 [icon_ drawInRect:rect];
5488 if (badge_ != nil) {
5490 rect.size = [(UIImage *) badge_ size];
5492 rect.size.width /= 2;
5493 rect.size.height /= 2;
5495 rect.origin.x = 36 - rect.size.width / 2;
5496 rect.origin.y = 36 - rect.size.height / 2;
5498 [badge_ drawInRect:rect];
5505 UISetColor(commercial_ ? Purple_ : Black_);
5506 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5507 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5510 UISetColor(commercial_ ? Purplish_ : Gray_);
5511 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5513 if (placard_ != nil)
5514 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5517 - (void) drawContentRect:(CGRect)rect {
5519 [self drawSummaryContentRect:rect];
5521 [self drawNormalContentRect:rect];
5526 /* Section Cell {{{ */
5527 @interface SectionCell : CyteTableViewCell <
5528 CyteTableViewCellDelegate
5530 _H<NSString> basic_;
5531 _H<NSString> section_;
5533 _H<NSString> count_;
5535 _H<UISwitch> switch_;
5539 - (void) setSection:(Section *)section editing:(BOOL)editing;
5543 @implementation SectionCell
5545 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5546 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5547 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5548 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5549 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5551 UIView *content([self contentView]);
5552 CGRect bounds([content bounds]);
5554 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5555 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5556 [content addSubview:content_];
5557 [content_ setBackgroundColor:[UIColor whiteColor]];
5559 [content_ setDelegate:self];
5563 - (void) onSwitch:(id)sender {
5564 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5565 if (metadata == nil) {
5566 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5567 [Sections_ setObject:metadata forKey:basic_];
5570 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5574 - (void) setSection:(Section *)section editing:(BOOL)editing {
5575 if (editing != editing_) {
5577 [switch_ removeFromSuperview];
5579 [self addSubview:switch_];
5588 if (section == nil) {
5589 name_ = UCLocalize("ALL_PACKAGES");
5592 basic_ = [section name];
5593 section_ = [section localized];
5595 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5596 count_ = [NSString stringWithFormat:@"%d", [section count]];
5599 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5602 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5603 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5605 [content_ setNeedsDisplay];
5608 - (void) setFrame:(CGRect)frame {
5609 [super setFrame:frame];
5611 CGRect rect([switch_ frame]);
5612 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5615 - (NSString *) accessibilityLabel {
5619 - (void) drawContentRect:(CGRect)rect {
5620 bool highlighted(highlighted_ && !editing_);
5622 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5627 float width(rect.size.width);
5633 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5635 CGSize size = [count_ sizeWithFont:Font14_];
5639 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5645 /* File Table {{{ */
5646 @interface FileTable : CyteViewController <
5647 UITableViewDataSource,
5650 _transient Database *database_;
5651 _H<Package> package_;
5653 _H<NSMutableArray> files_;
5654 _H<UITableView, 2> list_;
5657 - (id) initWithDatabase:(Database *)database;
5658 - (void) setPackage:(Package *)package;
5662 @implementation FileTable
5664 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5665 return files_ == nil ? 0 : [files_ count];
5668 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5672 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5673 static NSString *reuseIdentifier = @"Cell";
5675 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5677 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5678 [cell setFont:[UIFont systemFontOfSize:16]];
5680 [cell setText:[files_ objectAtIndex:indexPath.row]];
5681 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5686 - (NSURL *) navigationURL {
5687 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5691 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5693 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5694 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5695 [list_ setRowHeight:24.0f];
5696 [(UITableView *) list_ setDataSource:self];
5697 [list_ setDelegate:self];
5698 [[self view] addSubview:list_];
5701 - (void) viewDidLoad {
5702 [super viewDidLoad];
5704 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5707 - (void) releaseSubviews {
5710 [super releaseSubviews];
5713 - (id) initWithDatabase:(Database *)database {
5714 if ((self = [super init]) != nil) {
5715 database_ = database;
5717 files_ = [NSMutableArray arrayWithCapacity:32];
5721 - (void) setPackage:(Package *)package {
5725 [files_ removeAllObjects];
5727 if (package != nil) {
5729 name_ = [package id];
5731 if (NSArray *files = [package files])
5732 [files_ addObjectsFromArray:files];
5734 if ([files_ count] != 0) {
5735 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5736 [files_ removeObjectAtIndex:0];
5737 [files_ sortUsingSelector:@selector(compareByPath:)];
5739 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5740 [stack addObject:@"/"];
5742 for (int i(0), e([files_ count]); i != e; ++i) {
5743 NSString *file = [files_ objectAtIndex:i];
5744 while (![file hasPrefix:[stack lastObject]])
5745 [stack removeLastObject];
5746 NSString *directory = [stack lastObject];
5747 [stack addObject:[file stringByAppendingString:@"/"]];
5748 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5749 ([stack count] - 2) * 3, "",
5750 [file substringFromIndex:[directory length]]
5759 - (void) reloadData {
5762 [self setPackage:[database_ packageWithName:name_]];
5767 /* Package Controller {{{ */
5768 @interface CYPackageController : CydiaWebViewController <
5769 UIActionSheetDelegate
5771 _transient Database *database_;
5772 _H<Package> package_;
5775 _H<NSMutableArray> buttons_;
5776 _H<UIBarButtonItem> button_;
5779 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5783 @implementation CYPackageController
5785 - (NSURL *) navigationURL {
5786 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5789 /* XXX: this is not safe at all... localization of /fail/ */
5790 - (void) _clickButtonWithName:(NSString *)name {
5791 if ([name isEqualToString:UCLocalize("CLEAR")])
5792 [delegate_ clearPackage:package_];
5793 else if ([name isEqualToString:UCLocalize("INSTALL")])
5794 [delegate_ installPackage:package_];
5795 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5796 [delegate_ installPackage:package_];
5797 else if ([name isEqualToString:UCLocalize("REMOVE")])
5798 [delegate_ removePackage:package_];
5799 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5800 [delegate_ installPackage:package_];
5801 else _assert(false);
5804 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5805 NSString *context([sheet context]);
5807 if ([context isEqualToString:@"modify"]) {
5808 if (button != [sheet cancelButtonIndex]) {
5809 NSString *buttonName = [buttons_ objectAtIndex:button];
5810 [self _clickButtonWithName:buttonName];
5813 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5817 - (bool) _allowJavaScriptPanel {
5822 - (void) _customButtonClicked {
5823 int count([buttons_ count]);
5828 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5830 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5831 [buttons addObjectsFromArray:buttons_];
5833 UIActionSheet *sheet = [[[UIActionSheet alloc]
5836 cancelButtonTitle:nil
5837 destructiveButtonTitle:nil
5838 otherButtonTitles:nil
5841 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5843 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5844 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5846 [sheet setContext:@"modify"];
5848 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5852 // We don't want to allow non-commercial packages to do custom things to the install button,
5853 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5854 - (void) customButtonClicked {
5856 [super customButtonClicked];
5858 [self _customButtonClicked];
5861 - (void) reloadButtonClicked {
5862 // Don't reload a commerical package by tapping the loading button,
5863 // but if it's not an Install button, we should forward it on.
5864 if (![package_ uninstalled])
5865 [self _customButtonClicked];
5868 - (void) applyLoadingTitle {
5869 // Don't show "Loading" as the title. Ever.
5872 - (UIBarButtonItem *) rightButton {
5877 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5878 if ((self = [super init]) != nil) {
5879 database_ = database;
5880 buttons_ = [NSMutableArray arrayWithCapacity:4];
5881 name_ = [NSString stringWithString:name];
5882 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5886 - (void) reloadData {
5889 package_ = [database_ packageWithName:name_];
5891 [buttons_ removeAllObjects];
5893 if (package_ != nil) {
5894 [(Package *) package_ parse];
5896 commercial_ = [package_ isCommercial];
5898 if ([package_ mode] != nil)
5899 [buttons_ addObject:UCLocalize("CLEAR")];
5900 if ([package_ source] == nil);
5901 else if ([package_ upgradableAndEssential:NO])
5902 [buttons_ addObject:UCLocalize("UPGRADE")];
5903 else if ([package_ uninstalled])
5904 [buttons_ addObject:UCLocalize("INSTALL")];
5906 [buttons_ addObject:UCLocalize("REINSTALL")];
5907 if (![package_ uninstalled])
5908 [buttons_ addObject:UCLocalize("REMOVE")];
5912 switch ([buttons_ count]) {
5913 case 0: title = nil; break;
5914 case 1: title = [buttons_ objectAtIndex:0]; break;
5915 default: title = UCLocalize("MODIFY"); break;
5918 button_ = [[[UIBarButtonItem alloc]
5920 style:UIBarButtonItemStylePlain
5922 action:@selector(customButtonClicked)
5926 - (bool) isLoading {
5927 return commercial_ ? [super isLoading] : false;
5933 /* Package List Controller {{{ */
5934 @interface PackageListController : CyteViewController <
5935 UITableViewDataSource,
5938 _transient Database *database_;
5940 _H<NSArray> packages_;
5941 _H<NSMutableArray> sections_;
5942 _H<UITableView, 2> list_;
5943 _H<NSMutableArray> index_;
5944 _H<NSMutableDictionary> indices_;
5945 _H<NSString> title_;
5946 unsigned reloading_;
5949 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5950 - (void) setDelegate:(id)delegate;
5951 - (void) resetCursor;
5956 @implementation PackageListController
5958 - (bool) isSummarized {
5962 - (bool) showsSections {
5966 - (void) deselectWithAnimation:(BOOL)animated {
5967 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5970 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5971 CGRect base = [[self view] bounds];
5972 base.size.height -= bounds.size.height;
5973 base.origin = [list_ frame].origin;
5975 [UIView beginAnimations:nil context:NULL];
5976 [UIView setAnimationBeginsFromCurrentState:YES];
5977 [UIView setAnimationCurve:curve];
5978 [UIView setAnimationDuration:duration];
5979 [list_ setFrame:base];
5980 [UIView commitAnimations];
5983 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5984 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5987 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5988 [self resizeForKeyboardBounds:bounds duration:0];
5991 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5992 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5993 *curve = UIViewAnimationCurveEaseInOut;
5995 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5997 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6000 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6003 - (void) keyboardWillShow:(NSNotification *)notification {
6006 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6007 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6009 NSTimeInterval duration;
6010 UIViewAnimationCurve curve;
6011 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6013 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);
6014 UIViewController *base = self;
6015 while ([base parentViewController] != nil)
6016 base = [base parentViewController];
6017 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6018 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6020 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6021 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6023 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6026 - (void) keyboardWillHide:(NSNotification *)notification {
6027 NSTimeInterval duration;
6028 UIViewAnimationCurve curve;
6029 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6031 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6034 - (void) viewWillAppear:(BOOL)animated {
6035 [super viewWillAppear:animated];
6037 [self resizeForKeyboardBounds:CGRectZero];
6038 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6039 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6042 - (void) viewWillDisappear:(BOOL)animated {
6043 [super viewWillDisappear:animated];
6045 [self resizeForKeyboardBounds:CGRectZero];
6046 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6047 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6050 - (void) viewDidAppear:(BOOL)animated {
6051 [super viewDidAppear:animated];
6052 [self deselectWithAnimation:animated];
6055 - (void) didSelectPackage:(Package *)package {
6056 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6057 [view setDelegate:delegate_];
6058 [[self navigationController] pushViewController:view animated:YES];
6061 #if TryIndexedCollation
6062 + (BOOL) hasIndexedCollation {
6063 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6067 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6068 NSInteger count([sections_ count]);
6069 return count == 0 ? 1 : count;
6072 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6073 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6075 return [[sections_ objectAtIndex:section] name];
6078 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6079 if ([sections_ count] == 0)
6081 return [[sections_ objectAtIndex:section] count];
6084 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6085 @synchronized (database_) {
6086 if ([database_ era] != era_)
6089 Section *section([sections_ objectAtIndex:[path section]]);
6090 NSInteger row([path row]);
6091 Package *package([packages_ objectAtIndex:([section row] + row)]);
6092 return [[package retain] autorelease];
6095 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6096 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6098 cell = [[[PackageCell alloc] init] autorelease];
6100 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6101 [cell setPackage:package asSummary:[self isSummarized]];
6105 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6106 Package *package([self packageAtIndexPath:path]);
6107 package = [database_ packageWithName:[package id]];
6108 [self didSelectPackage:package];
6111 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6112 if (![self showsSections])
6118 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6119 #if TryIndexedCollation
6120 if ([[self class] hasIndexedCollation]) {
6121 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6128 - (void) updateHeight {
6129 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6132 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6133 if ((self = [super init]) != nil) {
6134 database_ = database;
6135 title_ = [title copy];
6136 [[self navigationItem] setTitle:title_];
6138 #if TryIndexedCollation
6139 if ([[self class] hasIndexedCollation])
6140 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6143 index_ = [NSMutableArray arrayWithCapacity:32];
6145 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6147 packages_ = [NSArray array];
6148 sections_ = [NSMutableArray arrayWithCapacity:16];
6153 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6155 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6156 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6157 [[self view] addSubview:list_];
6159 // XXX: is 20 the most optimal number here?
6160 [list_ setSectionIndexMinimumDisplayRowCount:20];
6162 [(UITableView *) list_ setDataSource:self];
6163 [list_ setDelegate:self];
6165 [self updateHeight];
6168 - (void) releaseSubviews {
6171 [super releaseSubviews];
6174 - (void) setDelegate:(id)delegate {
6175 delegate_ = delegate;
6178 - (bool) shouldYield {
6182 - (bool) shouldBlock {
6186 - (NSMutableArray *) _reloadPackages {
6187 @synchronized (database_) {
6188 era_ = [database_ era];
6189 NSArray *packages([database_ packages]);
6191 return [NSMutableArray arrayWithArray:packages];
6194 - (void) _reloadData {
6195 if (reloading_ != 0) {
6202 if ([self shouldYield]) {
6206 if (![self shouldBlock])
6209 hud = [delegate_ addProgressHUD];
6210 [hud setText:UCLocalize("LOADING")];
6214 packages = [self yieldToSelector:@selector(_reloadPackages)];
6217 [delegate_ removeProgressHUD:hud];
6218 } while (reloading_ == 2);
6222 packages = [self _reloadPackages];
6225 packages_ = packages;
6227 [indices_ removeAllObjects];
6228 [sections_ removeAllObjects];
6230 Section *section = nil;
6232 #if TryIndexedCollation
6233 if ([[self class] hasIndexedCollation]) {
6234 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6235 NSArray *titles = [collation sectionIndexTitles];
6238 _profile(PackageTable$reloadData$Section)
6239 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6243 _profile(PackageTable$reloadData$Section$Package)
6244 package = [packages_ objectAtIndex:offset];
6245 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6248 while (secidx < index) {
6251 _profile(PackageTable$reloadData$Section$Allocate)
6252 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6255 _profile(PackageTable$reloadData$Section$Add)
6256 [sections_ addObject:section];
6260 [section addToCount];
6266 [index_ removeAllObjects];
6268 bool sectioned([self showsSections]);
6270 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6271 [sections_ addObject:section];
6274 _profile(PackageTable$reloadData$Section)
6275 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6279 _profile(PackageTable$reloadData$Section$Package)
6280 package = [packages_ objectAtIndex:offset];
6281 index = [package index];
6284 if (sectioned && (section == nil || [section index] != index)) {
6285 _profile(PackageTable$reloadData$Section$Allocate)
6286 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6289 [index_ addObject:[section name]];
6290 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6292 _profile(PackageTable$reloadData$Section$Add)
6293 [sections_ addObject:section];
6297 [section addToCount];
6302 [self updateHeight];
6304 _profile(PackageTable$reloadData$List)
6305 [(UITableView *) list_ setDataSource:self];
6310 - (void) reloadData {
6312 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6315 - (void) resetCursor {
6316 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6319 - (void) clearData {
6320 [self updateHeight];
6322 [list_ setDataSource:nil];
6330 /* Filtered Package List Controller {{{ */
6331 @interface FilteredPackageListController : PackageListController {
6334 _H<NSObject> object_;
6337 - (void) setObject:(id)object;
6338 - (void) setObject:(id)object forFilter:(SEL)filter;
6341 - (void) setFilter:(SEL)filter;
6343 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6347 @implementation FilteredPackageListController
6353 - (void) setFilter:(SEL)filter {
6354 @synchronized (self) {
6357 /* XXX: this is an unsafe optimization of doomy hell */
6358 Method method(class_getInstanceMethod([Package class], filter));
6359 _assert(method != NULL);
6360 imp_ = method_getImplementation(method);
6361 _assert(imp_ != NULL);
6364 - (void) setObject:(id)object {
6365 @synchronized (self) {
6369 - (void) setObject:(id)object forFilter:(SEL)filter {
6370 @synchronized (self) {
6371 [self setFilter:filter];
6372 [self setObject:object];
6375 - (NSMutableArray *) _reloadPackages {
6376 @synchronized (database_) {
6377 era_ = [database_ era];
6378 NSArray *packages([database_ packages]);
6380 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6384 _H<NSObject> object;
6386 @synchronized (self) {
6392 _profile(PackageTable$reloadData$Filter)
6393 for (Package *package in packages)
6394 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6395 [filtered addObject:package];
6401 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6402 if ((self = [super initWithDatabase:database title:title]) != nil) {
6403 [self setFilter:filter];
6404 [self setObject:object];
6411 /* Home Controller {{{ */
6412 @interface HomeController : CydiaWebViewController {
6417 @implementation HomeController
6420 if ((self = [super init]) != nil) {
6421 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6426 - (NSURL *) navigationURL {
6427 return [NSURL URLWithString:@"cydia://home"];
6430 - (void) aboutButtonClicked {
6431 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6433 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6434 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6435 [alert setCancelButtonIndex:0];
6438 @"Copyright \u00a9 2008-2011\n"
6441 "Jay Freeman (saurik)\n"
6442 "saurik@saurik.com\n"
6443 "http://www.saurik.com/"
6449 - (UIBarButtonItem *) leftButton {
6450 return [[[UIBarButtonItem alloc]
6451 initWithTitle:UCLocalize("ABOUT")
6452 style:UIBarButtonItemStylePlain
6454 action:@selector(aboutButtonClicked)
6460 /* Manage Controller {{{ */
6461 @interface ManageController : CydiaWebViewController {
6464 - (void) queueStatusDidChange;
6468 @implementation ManageController
6471 if ((self = [super init]) != nil) {
6472 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6476 - (NSURL *) navigationURL {
6477 return [NSURL URLWithString:@"cydia://manage"];
6480 - (UIBarButtonItem *) leftButton {
6481 return [[[UIBarButtonItem alloc]
6482 initWithTitle:UCLocalize("SETTINGS")
6483 style:UIBarButtonItemStylePlain
6485 action:@selector(settingsButtonClicked)
6489 - (void) settingsButtonClicked {
6490 [delegate_ showSettings];
6493 - (void) queueButtonClicked {
6497 - (UIBarButtonItem *) customButton {
6498 return Queuing_ ? [[[UIBarButtonItem alloc]
6499 initWithTitle:UCLocalize("QUEUE")
6500 style:UIBarButtonItemStyleDone
6502 action:@selector(queueButtonClicked)
6503 ] autorelease] : [super customButton];
6506 - (void) queueStatusDidChange {
6507 [self applyRightButton];
6510 - (bool) isLoading {
6511 return !Queuing_ && [super isLoading];
6517 /* Refresh Bar {{{ */
6518 @interface RefreshBar : UINavigationBar {
6519 _H<UIProgressIndicator> indicator_;
6520 _H<UITextLabel> prompt_;
6521 _H<UIProgressBar> progress_;
6522 _H<UINavigationButton> cancel_;
6527 @implementation RefreshBar
6529 - (void) positionViews {
6530 CGRect frame = [cancel_ frame];
6531 frame.size = [cancel_ sizeThatFits:frame.size];
6532 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6533 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6534 [cancel_ setFrame:frame];
6536 CGSize prgsize = {75, 100};
6538 [self frame].size.width - prgsize.width - 10,
6539 ([self frame].size.height - prgsize.height) / 2
6541 [progress_ setFrame:prgrect];
6543 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6544 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6545 CGRect indrect = {{indoffset, indoffset}, indsize};
6546 [indicator_ setFrame:indrect];
6548 CGSize prmsize = {215, indsize.height + 4};
6550 indoffset * 2 + indsize.width,
6551 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6553 [prompt_ setFrame:prmrect];
6556 - (void) setFrame:(CGRect)frame {
6557 [super setFrame:frame];
6558 [self positionViews];
6561 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6562 if ((self = [super initWithFrame:frame]) != nil) {
6563 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6565 [self setBarStyle:UIBarStyleBlack];
6567 UIBarStyle barstyle([self _barStyle:NO]);
6568 bool ugly(barstyle == UIBarStyleDefault);
6570 UIProgressIndicatorStyle style = ugly ?
6571 UIProgressIndicatorStyleMediumBrown :
6572 UIProgressIndicatorStyleMediumWhite;
6574 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6575 [(UIProgressIndicator *) indicator_ setStyle:style];
6576 [indicator_ startAnimation];
6577 [self addSubview:indicator_];
6579 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6580 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6581 [prompt_ setBackgroundColor:[UIColor clearColor]];
6582 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6583 [self addSubview:prompt_];
6585 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6586 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6587 [(UIProgressBar *) progress_ setStyle:0];
6588 [self addSubview:progress_];
6590 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6591 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6592 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6593 [cancel_ setBarStyle:barstyle];
6595 [self positionViews];
6599 - (void) setCancellable:(bool)cancellable {
6601 [self addSubview:cancel_];
6603 [cancel_ removeFromSuperview];
6607 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6608 [progress_ setProgress:0];
6612 [self setCancellable:NO];
6615 - (void) setPrompt:(NSString *)prompt {
6616 [prompt_ setText:prompt];
6619 - (void) setProgress:(float)progress {
6620 [progress_ setProgress:progress];
6626 /* Cydia Navigation Controller Interface {{{ */
6627 @interface UINavigationController (Cydia)
6629 - (NSArray *) navigationURLCollection;
6630 - (void) unloadData;
6635 /* Cydia Tab Bar Controller {{{ */
6636 @interface CYTabBarController : UITabBarController <
6637 UITabBarControllerDelegate,
6640 _transient Database *database_;
6641 _H<RefreshBar, 1> refreshbar_;
6645 // XXX: ok, "updatedelegate_"?...
6646 _transient NSObject<CydiaDelegate> *updatedelegate_;
6648 _H<UIViewController> remembered_;
6649 _transient UIViewController *transient_;
6652 - (NSArray *) navigationURLCollection;
6653 - (void) dropBar:(BOOL)animated;
6654 - (void) beginUpdate;
6655 - (void) raiseBar:(BOOL)animated;
6657 - (void) unloadData;
6661 @implementation CYTabBarController
6663 - (void) setUnselectedViewController:(UIViewController *)transient {
6664 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6665 if (transient != nil) {
6666 if (transient_ == nil)
6667 remembered_ = [controllers objectAtIndex:0];
6668 transient_ = transient;
6669 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6670 [controllers replaceObjectAtIndex:0 withObject:transient_];
6671 [self setSelectedIndex:0];
6672 [self setViewControllers:controllers];
6673 [self concealTabBarSelection];
6674 } else if (remembered_ != nil) {
6675 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6676 transient_ = transient;
6677 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6679 [self setViewControllers:controllers];
6680 [self revealTabBarSelection];
6684 - (UIViewController *) unselectedViewController {
6688 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6689 if ([self unselectedViewController])
6690 [self setUnselectedViewController:nil];
6693 - (NSArray *) navigationURLCollection {
6694 NSMutableArray *items([NSMutableArray array]);
6696 // XXX: Should this deal with transient view controllers?
6697 for (id navigation in [self viewControllers]) {
6698 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6700 [items addObject:stack];
6706 - (void) unloadData {
6709 for (UINavigationController *controller in [self viewControllers])
6710 [controller unloadData];
6712 if (UIViewController *selected = [self selectedViewController])
6713 [selected reloadData];
6715 if (UIViewController *unselected = [self unselectedViewController]) {
6716 [unselected unloadData];
6717 [unselected reloadData];
6722 [[NSNotificationCenter defaultCenter] removeObserver:self];
6727 - (id) initWithDatabase:(Database *)database {
6728 if ((self = [super init]) != nil) {
6729 database_ = database;
6730 [self setDelegate:self];
6732 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6733 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6735 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6739 - (void) setUpdate:(NSDate *)date {
6743 - (void) beginUpdate {
6744 [(RefreshBar *) refreshbar_ start];
6747 [updatedelegate_ retainNetworkActivityIndicator];
6751 detachNewThreadSelector:@selector(performUpdate)
6757 - (void) performUpdate {
6758 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6761 status.setDelegate(self);
6762 [database_ updateWithStatus:status];
6765 performSelectorOnMainThread:@selector(completeUpdate)
6773 - (void) stopUpdateWithSelector:(SEL)selector {
6775 [updatedelegate_ releaseNetworkActivityIndicator];
6777 [self raiseBar:YES];
6780 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6783 - (void) completeUpdate {
6786 [self stopUpdateWithSelector:@selector(reloadData)];
6789 - (void) cancelUpdate {
6790 [self stopUpdateWithSelector:@selector(updateData)];
6793 - (void) cancelPressed {
6794 [self cancelUpdate];
6801 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6802 [refreshbar_ setPrompt:[event compoundMessage]];
6805 - (bool) isProgressCancelled {
6809 - (void) setProgressCancellable:(NSNumber *)cancellable {
6810 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6813 - (void) setProgressPercent:(NSNumber *)percent {
6814 [refreshbar_ setProgress:[percent floatValue]];
6817 - (void) setProgressStatus:(NSDictionary *)status {
6819 [self setProgressPercent:[status objectForKey:@"Percent"]];
6822 - (void) setUpdateDelegate:(id)delegate {
6823 updatedelegate_ = delegate;
6826 - (UIView *) transitionView {
6827 if ([self respondsToSelector:@selector(_transitionView)])
6828 return [self _transitionView];
6830 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6833 - (void) dropBar:(BOOL)animated {
6838 UIView *transition([self transitionView]);
6839 [[self view] addSubview:refreshbar_];
6841 CGRect barframe([refreshbar_ frame]);
6843 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6844 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6846 barframe.origin.y = 0;
6848 [refreshbar_ setFrame:barframe];
6851 [UIView beginAnimations:nil context:NULL];
6853 CGRect viewframe = [transition frame];
6854 viewframe.origin.y += barframe.size.height;
6855 viewframe.size.height -= barframe.size.height;
6856 [transition setFrame:viewframe];
6859 [UIView commitAnimations];
6861 // Ensure bar has the proper width for our view, it might have changed
6862 barframe.size.width = viewframe.size.width;
6863 [refreshbar_ setFrame:barframe];
6866 - (void) raiseBar:(BOOL)animated {
6871 UIView *transition([self transitionView]);
6872 [refreshbar_ removeFromSuperview];
6874 CGRect barframe([refreshbar_ frame]);
6877 [UIView beginAnimations:nil context:NULL];
6879 CGRect viewframe = [transition frame];
6880 viewframe.origin.y -= barframe.size.height;
6881 viewframe.size.height += barframe.size.height;
6882 [transition setFrame:viewframe];
6885 [UIView commitAnimations];
6888 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6889 bool dropped(dropped_);
6894 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6900 - (void) statusBarFrameChanged:(NSNotification *)notification {
6910 /* Cydia Navigation Controller Implementation {{{ */
6911 @implementation UINavigationController (Cydia)
6913 - (NSArray *) navigationURLCollection {
6914 NSMutableArray *stack([NSMutableArray array]);
6916 for (CyteViewController *controller in [self viewControllers]) {
6917 NSString *url = [[controller navigationURL] absoluteString];
6919 [stack addObject:url];
6925 - (void) reloadData {
6928 if (UIViewController *visible = [self visibleViewController])
6929 [visible reloadData];
6932 - (void) unloadData {
6933 for (CyteViewController *page in [self viewControllers])
6942 /* Cydia:// Protocol {{{ */
6943 @interface CydiaURLProtocol : NSURLProtocol {
6948 @implementation CydiaURLProtocol
6950 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6951 NSURL *url([request URL]);
6955 NSString *scheme([[url scheme] lowercaseString]);
6956 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6958 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6964 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6968 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6969 id<NSURLProtocolClient> client([self client]);
6971 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6973 NSData *data(UIImagePNGRepresentation(icon));
6975 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6976 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6977 [client URLProtocol:self didLoadData:data];
6978 [client URLProtocolDidFinishLoading:self];
6982 - (void) startLoading {
6983 id<NSURLProtocolClient> client([self client]);
6984 NSURLRequest *request([self request]);
6986 NSURL *url([request URL]);
6987 NSString *href([url absoluteString]);
6988 NSString *scheme([[url scheme] lowercaseString]);
6992 if ([scheme isEqualToString:@"cydia"])
6993 path = [href substringFromIndex:8];
6994 else if ([scheme isEqualToString:@"about"])
6995 path = [href substringFromIndex:12];
6996 else _assert(false);
6998 NSRange slash([path rangeOfString:@"/"]);
7001 if (slash.location == NSNotFound) {
7005 command = [path substringToIndex:slash.location];
7006 path = [path substringFromIndex:(slash.location + 1)];
7009 Database *database([Database sharedInstance]);
7011 if ([command isEqualToString:@"package-icon"]) {
7014 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7015 Package *package([database packageWithName:path]);
7019 UIImage *icon([package icon]);
7020 [self _returnPNGWithImage:icon forRequest:request];
7021 } else if ([command isEqualToString:@"source-icon"]) {
7024 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7025 NSString *source(Simplify(path));
7026 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7028 icon = [UIImage applicationImageNamed:@"unknown.png"];
7029 [self _returnPNGWithImage:icon forRequest:request];
7030 } else if ([command isEqualToString:@"uikit-image"]) {
7033 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7034 UIImage *icon(_UIImageWithName(path));
7035 [self _returnPNGWithImage:icon forRequest:request];
7036 } else if ([command isEqualToString:@"section-icon"]) {
7039 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7040 NSString *section(Simplify(path));
7041 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7043 icon = [UIImage applicationImageNamed:@"unknown.png"];
7044 [self _returnPNGWithImage:icon forRequest:request];
7046 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7050 - (void) stopLoading {
7056 /* Section Controller {{{ */
7057 @interface SectionController : FilteredPackageListController {
7058 _H<NSString> section_;
7061 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7065 @implementation SectionController
7067 - (NSURL *) navigationURL {
7068 NSString *name = section_;
7072 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7075 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7078 title = UCLocalize("ALL_PACKAGES");
7079 else if (![name isEqual:@""])
7080 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7082 title = UCLocalize("NO_SECTION");
7084 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7091 /* Sections Controller {{{ */
7092 @interface SectionsController : CyteViewController <
7093 UITableViewDataSource,
7096 _transient Database *database_;
7097 _H<NSMutableArray> sections_;
7098 _H<NSMutableArray> filtered_;
7099 _H<UITableView, 2> list_;
7102 - (id) initWithDatabase:(Database *)database;
7103 - (void) editButtonClicked;
7107 @implementation SectionsController
7109 - (NSURL *) navigationURL {
7110 return [NSURL URLWithString:@"cydia://sections"];
7113 - (void) updateNavigationItem {
7114 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7115 if ([sections_ count] == 0) {
7116 [[self navigationItem] setRightBarButtonItem:nil];
7118 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7119 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7121 action:@selector(editButtonClicked)
7122 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7126 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7127 [super setEditing:editing animated:animated];
7132 [delegate_ updateData];
7134 [self updateNavigationItem];
7137 - (void) viewDidAppear:(BOOL)animated {
7138 [super viewDidAppear:animated];
7139 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7142 - (void) viewWillDisappear:(BOOL)animated {
7143 [super viewWillDisappear:animated];
7144 if ([self isEditing]) [self setEditing:NO];
7147 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7148 Section *section = nil;
7149 int index = [indexPath row];
7150 if (![self isEditing]) {
7153 section = [filtered_ objectAtIndex:index];
7155 section = [sections_ objectAtIndex:index];
7160 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7161 if ([self isEditing])
7162 return [sections_ count];
7164 return [filtered_ count] + 1;
7167 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7171 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7172 static NSString *reuseIdentifier = @"SectionCell";
7174 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7176 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7178 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7183 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7184 if ([self isEditing])
7187 Section *section = [self sectionAtIndexPath:indexPath];
7189 SectionController *controller = [[[SectionController alloc]
7190 initWithDatabase:database_
7191 section:[section name]
7193 [controller setDelegate:delegate_];
7195 [[self navigationController] pushViewController:controller animated:YES];
7199 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7201 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7202 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7203 [list_ setRowHeight:45.0f];
7204 [(UITableView *) list_ setDataSource:self];
7205 [list_ setDelegate:self];
7206 [[self view] addSubview:list_];
7209 - (void) viewDidLoad {
7210 [super viewDidLoad];
7212 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7215 - (void) releaseSubviews {
7218 [super releaseSubviews];
7221 - (id) initWithDatabase:(Database *)database {
7222 if ((self = [super init]) != nil) {
7223 database_ = database;
7225 sections_ = [NSMutableArray arrayWithCapacity:16];
7226 filtered_ = [NSMutableArray arrayWithCapacity:16];
7230 - (void) reloadData {
7233 NSArray *packages = [database_ packages];
7235 [sections_ removeAllObjects];
7236 [filtered_ removeAllObjects];
7238 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7241 for (Package *package in packages) {
7242 NSString *name([package section]);
7243 NSString *key(name == nil ? @"" : name);
7247 _profile(SectionsView$reloadData$Section)
7248 section = [sections objectForKey:key];
7249 if (section == nil) {
7250 _profile(SectionsView$reloadData$Section$Allocate)
7251 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7252 [sections setObject:section forKey:key];
7257 [section addToCount];
7259 _profile(SectionsView$reloadData$Filter)
7260 if (![package valid] || ![package visible])
7268 [sections_ addObjectsFromArray:[sections allValues]];
7270 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7272 for (Section *section in (id) sections_) {
7273 size_t count([section row]);
7277 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7278 [section setCount:count];
7279 [filtered_ addObject:section];
7282 [self updateNavigationItem];
7287 - (void) editButtonClicked {
7288 [self setEditing:![self isEditing] animated:YES];
7294 /* Changes Controller {{{ */
7295 @interface ChangesController : CyteViewController <
7296 UITableViewDataSource,
7299 _transient Database *database_;
7301 _H<NSArray> packages_;
7302 _H<NSMutableArray> sections_;
7303 _H<UITableView, 2> list_;
7307 - (id) initWithDatabase:(Database *)database;
7311 @implementation ChangesController
7313 - (NSURL *) navigationURL {
7314 return [NSURL URLWithString:@"cydia://changes"];
7317 - (void) viewDidAppear:(BOOL)animated {
7318 [super viewDidAppear:animated];
7319 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7322 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7323 NSInteger count([sections_ count]);
7324 return count == 0 ? 1 : count;
7327 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7328 if ([sections_ count] == 0)
7330 return [[sections_ objectAtIndex:section] name];
7333 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7334 if ([sections_ count] == 0)
7336 return [[sections_ objectAtIndex:section] count];
7339 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7340 @synchronized (database_) {
7341 if ([database_ era] != era_)
7344 NSUInteger sectionIndex([path section]);
7345 if (sectionIndex >= [sections_ count])
7347 Section *section([sections_ objectAtIndex:sectionIndex]);
7348 NSInteger row([path row]);
7349 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7352 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7353 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7355 cell = [[[PackageCell alloc] init] autorelease];
7357 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7358 [cell setPackage:package asSummary:false];
7362 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7363 Package *package([self packageAtIndexPath:path]);
7364 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7365 [view setDelegate:delegate_];
7366 [[self navigationController] pushViewController:view animated:YES];
7370 - (void) refreshButtonClicked {
7371 [delegate_ beginUpdate];
7372 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7375 - (void) upgradeButtonClicked {
7376 [delegate_ distUpgrade];
7377 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7381 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7383 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7384 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7385 [list_ setRowHeight:73];
7386 [(UITableView *) list_ setDataSource:self];
7387 [list_ setDelegate:self];
7388 [[self view] addSubview:list_];
7391 - (void) viewDidLoad {
7392 [super viewDidLoad];
7394 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7397 - (void) releaseSubviews {
7400 [super releaseSubviews];
7403 - (id) initWithDatabase:(Database *)database {
7404 if ((self = [super init]) != nil) {
7405 database_ = database;
7407 packages_ = [NSArray array];
7408 sections_ = [NSMutableArray arrayWithCapacity:16];
7412 - (NSMutableArray *) _reloadPackages {
7413 @synchronized (database_) {
7414 era_ = [database_ era];
7415 NSArray *packages([database_ packages]);
7417 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7420 _profile(ChangesController$_reloadPackages$Filter)
7421 for (Package *package in packages)
7422 if ([package upgradableAndEssential:YES] || [package visible])
7423 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7426 _profile(ChangesController$_reloadPackages$radixSort)
7427 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7434 - (void) _reloadData {
7439 UIProgressHUD *hud([delegate_ addProgressHUD]);
7440 [hud setText:UCLocalize("LOADING")];
7441 //NSLog(@"HUD:%@::%@", delegate_, hud);
7442 packages = [self yieldToSelector:@selector(_reloadPackages)];
7443 [delegate_ removeProgressHUD:hud];
7445 packages = [self _reloadPackages];
7448 @synchronized (database_) {
7449 if (era_ != [database_ era])
7452 packages_ = packages;
7453 [sections_ removeAllObjects];
7455 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7456 Section *ignored = nil;
7457 Section *section = nil;
7461 bool unseens = false;
7463 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7465 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7466 Package *package = [packages_ objectAtIndex:offset];
7468 BOOL uae = [package upgradableAndEssential:YES];
7472 time_t seen([package seen]);
7474 if (section == nil || last != seen) {
7478 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7481 _profile(ChangesController$reloadData$Allocate)
7482 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7483 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7484 [sections_ addObject:section];
7488 [section addToCount];
7489 } else if ([package ignored]) {
7490 if (ignored == nil) {
7491 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7493 [ignored addToCount];
7496 [upgradable addToCount];
7501 CFRelease(formatter);
7504 Section *last = [sections_ lastObject];
7505 size_t count = [last count];
7506 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7507 [sections_ removeLastObject];
7510 if ([ignored count] != 0)
7511 [sections_ insertObject:ignored atIndex:0];
7513 [sections_ insertObject:upgradable atIndex:0];
7517 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7518 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7519 style:UIBarButtonItemStylePlain
7521 action:@selector(upgradeButtonClicked)
7522 ] autorelease]) animated:YES];
7524 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7525 initWithTitle:UCLocalize("REFRESH")
7526 style:UIBarButtonItemStylePlain
7528 action:@selector(refreshButtonClicked)
7529 ] autorelease]) animated:YES];
7534 - (void) reloadData {
7536 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7541 /* Search Controller {{{ */
7542 @interface SearchController : FilteredPackageListController <
7545 _H<UISearchBar, 1> search_;
7549 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7550 - (void) reloadData;
7554 @implementation SearchController
7556 - (NSURL *) navigationURL {
7557 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7558 return [NSURL URLWithString:@"cydia://search"];
7560 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7563 - (void) useSearch {
7564 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7569 - (void) viewWillAppear:(BOOL)animated {
7570 [super viewWillAppear:animated];
7572 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7576 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7577 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7582 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7583 [search_ resignFirstResponder];
7587 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7588 [search_ setText:@""];
7589 [self searchBarButtonClicked:searchBar];
7592 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7593 [self searchBarButtonClicked:searchBar];
7596 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7597 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7601 - (bool) shouldYield {
7605 - (bool) shouldBlock {
7606 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7609 - (bool) isSummarized {
7610 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7613 - (bool) showsSections {
7617 - (NSMutableArray *) _reloadPackages {
7618 NSMutableArray *packages([super _reloadPackages]);
7619 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7620 [packages radixSortUsingSelector:@selector(rank)];
7624 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7625 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7626 search_ = [[[UISearchBar alloc] init] autorelease];
7627 [search_ setDelegate:self];
7630 [search_ setText:query];
7634 - (void) viewDidAppear:(BOOL)animated {
7635 [super viewDidAppear:animated];
7637 if (!searchloaded_) {
7638 searchloaded_ = YES;
7639 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7640 [search_ layoutSubviews];
7641 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7643 UITextField *textField;
7644 if ([search_ respondsToSelector:@selector(searchField)])
7645 textField = [search_ searchField];
7647 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7649 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7650 [textField setEnablesReturnKeyAutomatically:NO];
7651 [[self navigationItem] setTitleView:textField];
7655 - (void) reloadData {
7656 id object([search_ text]);
7657 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7658 object = [object componentsSeparatedByString:@" "];
7660 [self setObject:object];
7666 - (void) didSelectPackage:(Package *)package {
7667 [search_ resignFirstResponder];
7668 [super didSelectPackage:package];
7673 /* Package Settings Controller {{{ */
7674 @interface PackageSettingsController : CyteViewController <
7675 UITableViewDataSource,
7678 _transient Database *database_;
7680 _H<Package> package_;
7681 _H<UITableView, 2> table_;
7682 _H<UISwitch> subscribedSwitch_;
7683 _H<UISwitch> ignoredSwitch_;
7684 _H<UITableViewCell> subscribedCell_;
7685 _H<UITableViewCell> ignoredCell_;
7688 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7692 @implementation PackageSettingsController
7694 - (NSURL *) navigationURL {
7695 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7698 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7699 if (package_ == nil)
7702 if ([package_ installed] == nil)
7708 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7709 if (package_ == nil)
7712 // both sections contain just one item right now.
7716 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7720 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7722 return UCLocalize("SHOW_ALL_CHANGES_EX");
7724 return UCLocalize("IGNORE_UPGRADES_EX");
7727 - (void) onSubscribed:(id)control {
7728 bool value([control isOn]);
7729 if (package_ == nil)
7731 if ([package_ setSubscribed:value])
7732 [delegate_ updateData];
7735 - (void) _updateIgnored {
7736 const char *package([name_ UTF8String]);
7737 bool on([ignoredSwitch_ isOn]);
7739 pid_t pid(ExecFork());
7741 FILE *dpkg(popen("dpkg --set-selections", "w"));
7742 fwrite(package, strlen(package), 1, dpkg);
7745 fwrite(" hold\n", 6, 1, dpkg);
7747 fwrite(" install\n", 9, 1, dpkg);
7757 int result(waitpid(pid, &status, 0));
7760 _assert(result == pid);
7766 - (void) onIgnored:(id)control {
7767 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7768 [invocation setTarget:self];
7769 [invocation setSelector:@selector(_updateIgnored)];
7771 [delegate_ reloadDataWithInvocation:invocation];
7774 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7775 if (package_ == nil)
7778 switch ([indexPath section]) {
7779 case 0: return subscribedCell_;
7780 case 1: return ignoredCell_;
7789 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7791 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7792 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7793 [(UITableView *) table_ setDataSource:self];
7794 [table_ setDelegate:self];
7795 [[self view] addSubview:table_];
7797 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7798 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7799 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7801 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7802 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7803 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7805 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7806 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7807 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7808 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7810 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7811 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7812 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7813 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7816 - (void) viewDidLoad {
7817 [super viewDidLoad];
7819 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7822 - (void) releaseSubviews {
7824 subscribedCell_ = nil;
7826 ignoredSwitch_ = nil;
7827 subscribedSwitch_ = nil;
7829 [super releaseSubviews];
7832 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7833 if ((self = [super init]) != nil) {
7834 database_ = database;
7839 - (void) reloadData {
7842 package_ = [database_ packageWithName:name_];
7844 if (package_ != nil) {
7845 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7846 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7847 } // XXX: what now, G?
7849 [table_ reloadData];
7855 /* Installed Controller {{{ */
7856 @interface InstalledController : FilteredPackageListController {
7860 - (id) initWithDatabase:(Database *)database;
7862 - (void) updateRoleButton;
7863 - (void) queueStatusDidChange;
7867 @implementation InstalledController
7869 - (NSURL *) navigationURL {
7870 return [NSURL URLWithString:@"cydia://installed"];
7873 - (id) initWithDatabase:(Database *)database {
7874 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7875 [self updateRoleButton];
7876 [self queueStatusDidChange];
7881 - (void) queueButtonClicked {
7886 - (void) queueStatusDidChange {
7890 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7891 initWithTitle:UCLocalize("QUEUE")
7892 style:UIBarButtonItemStyleDone
7894 action:@selector(queueButtonClicked)
7897 [[self navigationItem] setLeftBarButtonItem:nil];
7903 - (void) updateRoleButton {
7904 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7905 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7906 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7907 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7909 action:@selector(roleButtonClicked)
7913 - (void) roleButtonClicked {
7914 [self setObject:[NSNumber numberWithBool:expert_]];
7918 [self updateRoleButton];
7924 /* Source Cell {{{ */
7925 @interface SourceCell : CyteTableViewCell <
7926 CyteTableViewCellDelegate
7929 _H<NSString> origin_;
7930 _H<NSString> label_;
7933 - (void) setSource:(Source *)source;
7937 @implementation SourceCell
7939 - (void) _setImage:(UIImage *)image {
7941 [content_ setNeedsDisplay];
7944 - (void) _setSource:(Source *)source {
7945 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7947 if (NSString *base = [source base])
7948 if ([base length] != 0) {
7949 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7951 if (NSData *data = [NSURLConnection
7952 sendSynchronousRequest:[NSURLRequest
7954 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7958 returningResponse:NULL
7961 if (UIImage *image = [UIImage imageWithData:data])
7962 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7968 - (void) setSource:(Source *)source {
7969 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7971 origin_ = [source name];
7972 label_ = [source uri];
7974 [content_ setNeedsDisplay];
7976 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7979 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7980 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7981 UIView *content([self contentView]);
7982 CGRect bounds([content bounds]);
7984 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7985 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7986 [content_ setBackgroundColor:[UIColor whiteColor]];
7987 [content addSubview:content_];
7989 [content_ setDelegate:self];
7990 [content_ setOpaque:YES];
7994 - (NSString *) accessibilityLabel {
7998 - (void) drawContentRect:(CGRect)rect {
7999 bool highlighted(highlighted_);
8000 float width(rect.size.width);
8003 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8010 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8014 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8019 /* Source Controller {{{ */
8020 @interface SourceController : FilteredPackageListController {
8021 _transient Source *source_;
8025 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8029 @implementation SourceController
8031 - (NSURL *) navigationURL {
8032 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8035 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8036 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8038 key_ = [source key];
8042 - (void) reloadData {
8043 source_ = [database_ sourceWithKey:key_];
8044 key_ = [source_ key];
8045 [self setObject:source_];
8047 [[self navigationItem] setTitle:[source_ label]];
8054 /* Sources Controller {{{ */
8055 @interface SourcesController : CyteViewController <
8056 UITableViewDataSource,
8059 _transient Database *database_;
8060 _H<UITableView, 2> list_;
8061 _H<NSMutableArray> sources_;
8065 _H<UIProgressHUD> hud_;
8068 //NSURLConnection *installer_;
8069 NSURLConnection *trivial_;
8070 NSURLConnection *trivial_bz2_;
8071 NSURLConnection *trivial_gz_;
8072 //NSURLConnection *automatic_;
8077 - (id) initWithDatabase:(Database *)database;
8078 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8082 @implementation SourcesController
8084 - (void) _releaseConnection:(NSURLConnection *)connection {
8085 if (connection != nil) {
8086 [connection cancel];
8087 //[connection setDelegate:nil];
8088 [connection release];
8093 //[self _releaseConnection:installer_];
8094 [self _releaseConnection:trivial_];
8095 [self _releaseConnection:trivial_gz_];
8096 [self _releaseConnection:trivial_bz2_];
8097 //[self _releaseConnection:automatic_];
8102 - (NSURL *) navigationURL {
8103 return [NSURL URLWithString:@"cydia://sources"];
8106 - (void) viewDidAppear:(BOOL)animated {
8107 [super viewDidAppear:animated];
8108 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8111 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8112 return offset_ == 0 ? 1 : 2;
8115 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8116 switch (section + (offset_ == 0 ? 1 : 0)) {
8117 case 0: return UCLocalize("ENTERED_BY_USER");
8118 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8124 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8125 int count = [sources_ count];
8127 case 0: return (offset_ == 0 ? count : offset_);
8128 case 1: return count - offset_;
8134 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8136 switch (indexPath.section) {
8137 case 0: idx = indexPath.row; break;
8138 case 1: idx = indexPath.row + offset_; break;
8142 return [sources_ objectAtIndex:idx];
8145 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8146 static NSString *cellIdentifier = @"SourceCell";
8148 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8149 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8150 [cell setSource:[self sourceAtIndexPath:indexPath]];
8151 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8156 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8157 Source *source = [self sourceAtIndexPath:indexPath];
8159 SourceController *controller = [[[SourceController alloc]
8160 initWithDatabase:database_
8164 [controller setDelegate:delegate_];
8166 [[self navigationController] pushViewController:controller animated:YES];
8169 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8170 Source *source = [self sourceAtIndexPath:indexPath];
8171 return [source record] != nil;
8174 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8175 if (editingStyle == UITableViewCellEditingStyleDelete) {
8176 Source *source = [self sourceAtIndexPath:indexPath];
8177 [Sources_ removeObjectForKey:[source key]];
8178 [delegate_ syncData];
8183 [delegate_ addTrivialSource:href_];
8184 [delegate_ syncData];
8187 - (NSString *) getWarning {
8188 NSString *href(href_);
8189 NSRange colon([href rangeOfString:@"://"]);
8190 if (colon.location != NSNotFound)
8191 href = [href substringFromIndex:(colon.location + 3)];
8192 href = [href stringByAddingPercentEscapes];
8193 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8194 href = [href stringByCachingURLWithCurrentCDN];
8196 NSURL *url([NSURL URLWithString:href]);
8198 NSStringEncoding encoding;
8199 NSError *error(nil);
8201 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8202 return [warning length] == 0 ? nil : warning;
8206 - (void) _endConnection:(NSURLConnection *)connection {
8207 // XXX: the memory management in this method is horribly awkward
8209 NSURLConnection **field = NULL;
8210 if (connection == trivial_)
8212 else if (connection == trivial_bz2_)
8213 field = &trivial_bz2_;
8214 else if (connection == trivial_gz_)
8215 field = &trivial_gz_;
8216 _assert(field != NULL);
8217 [connection release];
8222 trivial_bz2_ == nil &&
8225 [delegate_ releaseNetworkActivityIndicator];
8227 [delegate_ removeProgressHUD:hud_];
8233 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8236 UIAlertView *alert = [[[UIAlertView alloc]
8237 initWithTitle:UCLocalize("SOURCE_WARNING")
8240 cancelButtonTitle:UCLocalize("CANCEL")
8242 UCLocalize("ADD_ANYWAY"),
8246 [alert setContext:@"warning"];
8247 [alert setNumberOfRows:1];
8251 } else if (error_ != nil) {
8252 UIAlertView *alert = [[[UIAlertView alloc]
8253 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8254 message:[error_ localizedDescription]
8256 cancelButtonTitle:UCLocalize("OK")
8257 otherButtonTitles:nil
8260 [alert setContext:@"urlerror"];
8263 UIAlertView *alert = [[[UIAlertView alloc]
8264 initWithTitle:UCLocalize("NOT_REPOSITORY")
8265 message:UCLocalize("NOT_REPOSITORY_EX")
8267 cancelButtonTitle:UCLocalize("OK")
8268 otherButtonTitles:nil
8271 [alert setContext:@"trivial"];
8280 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8281 switch ([response statusCode]) {
8287 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8288 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8290 [self _endConnection:connection];
8293 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8294 [self _endConnection:connection];
8297 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8298 NSURL *url([NSURL URLWithString:href]);
8300 NSMutableURLRequest *request = [NSMutableURLRequest
8302 cachePolicy:NSURLRequestUseProtocolCachePolicy
8303 timeoutInterval:120.0
8306 [request setHTTPMethod:method];
8308 if (Machine_ != NULL)
8309 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8311 if ([url isCydiaSecure]) {
8312 if (UniqueID_ != nil)
8313 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8316 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8319 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8320 NSString *context([alert context]);
8322 if ([context isEqualToString:@"source"]) {
8325 NSString *href = [[alert textField] text];
8327 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8329 if (![href hasSuffix:@"/"])
8330 href_ = [href stringByAppendingString:@"/"];
8334 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8335 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8336 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8337 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8341 // XXX: this is stupid
8342 hud_ = [delegate_ addProgressHUD];
8343 [hud_ setText:UCLocalize("VERIFYING_URL")];
8344 [delegate_ retainNetworkActivityIndicator];
8353 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8354 } else if ([context isEqualToString:@"trivial"])
8355 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8356 else if ([context isEqualToString:@"urlerror"])
8357 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8358 else if ([context isEqualToString:@"warning"]) {
8372 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8377 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8379 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8380 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8381 [list_ setRowHeight:56];
8382 [(UITableView *) list_ setDataSource:self];
8383 [list_ setDelegate:self];
8384 [[self view] addSubview:list_];
8387 - (void) viewDidLoad {
8388 [super viewDidLoad];
8390 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8391 [self updateButtonsForEditingStatus:NO animated:NO];
8394 - (void) releaseSubviews {
8397 [super releaseSubviews];
8400 - (id) initWithDatabase:(Database *)database {
8401 if ((self = [super init]) != nil) {
8402 database_ = database;
8403 sources_ = [NSMutableArray arrayWithCapacity:16];
8407 - (void) reloadData {
8411 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8414 [sources_ removeAllObjects];
8415 [sources_ addObjectsFromArray:[database_ sources]];
8417 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8420 int count([sources_ count]);
8422 for (int i = 0; i != count; i++) {
8423 if ([[sources_ objectAtIndex:i] record] == nil)
8428 [list_ setEditing:NO];
8429 [self updateButtonsForEditingStatus:NO animated:NO];
8433 - (void) showAddSourcePrompt {
8434 UIAlertView *alert = [[[UIAlertView alloc]
8435 initWithTitle:UCLocalize("ENTER_APT_URL")
8438 cancelButtonTitle:UCLocalize("CANCEL")
8440 UCLocalize("ADD_SOURCE"),
8444 [alert setContext:@"source"];
8446 [alert setNumberOfRows:1];
8447 [alert addTextFieldWithValue:@"http://" label:@""];
8449 UITextInputTraits *traits = [[alert textField] textInputTraits];
8450 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8451 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8452 [traits setKeyboardType:UIKeyboardTypeURL];
8453 // XXX: UIReturnKeyDone
8454 [traits setReturnKeyType:UIReturnKeyNext];
8459 - (void) addButtonClicked {
8460 [self showAddSourcePrompt];
8463 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8464 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8465 initWithTitle:UCLocalize("ADD")
8466 style:UIBarButtonItemStylePlain
8468 action:@selector(addButtonClicked)
8469 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8471 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8472 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8473 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8475 action:@selector(editButtonClicked)
8476 ] autorelease] animated:animated];
8478 if (IsWildcat_ && !editing)
8479 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8480 initWithTitle:UCLocalize("SETTINGS")
8481 style:UIBarButtonItemStylePlain
8483 action:@selector(settingsButtonClicked)
8487 - (void) settingsButtonClicked {
8488 [delegate_ showSettings];
8491 - (void) editButtonClicked {
8492 [list_ setEditing:![list_ isEditing] animated:YES];
8494 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8500 /* Settings Controller {{{ */
8501 @interface SettingsController : CyteViewController <
8502 UITableViewDataSource,
8505 _transient Database *database_;
8506 // XXX: ok, "roledelegate_"?...
8507 _transient id roledelegate_;
8508 _H<UITableView, 2> table_;
8509 _H<UISegmentedControl> segment_;
8510 _H<UIView> container_;
8513 - (void) showDoneButton;
8514 - (void) resizeSegmentedControl;
8518 @implementation SettingsController
8521 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8523 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8524 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8525 [table_ setDelegate:self];
8526 [(UITableView *) table_ setDataSource:self];
8527 [[self view] addSubview:table_];
8529 NSArray *items = [NSArray arrayWithObjects:
8531 UCLocalize("HACKER"),
8532 UCLocalize("DEVELOPER"),
8534 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8535 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8536 [container_ addSubview:segment_];
8539 - (void) viewDidLoad {
8540 [super viewDidLoad];
8542 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8545 if ([Role_ isEqualToString:@"User"]) index = 0;
8546 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8547 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8549 [segment_ setSelectedSegmentIndex:index];
8550 [self showDoneButton];
8553 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8554 [self resizeSegmentedControl];
8557 - (void) releaseSubviews {
8562 [super releaseSubviews];
8565 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8566 if ((self = [super init]) != nil) {
8567 database_ = database;
8568 roledelegate_ = delegate;
8572 - (void) resizeSegmentedControl {
8573 CGFloat width = [[self view] frame].size.width;
8574 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8577 - (void) viewWillAppear:(BOOL)animated {
8578 [super viewWillAppear:animated];
8580 [self resizeSegmentedControl];
8583 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8584 [self resizeSegmentedControl];
8587 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8588 [self resizeSegmentedControl];
8592 NSString *role(nil);
8594 switch ([segment_ selectedSegmentIndex]) {
8595 case 0: role = @"User"; break;
8596 case 1: role = @"Hacker"; break;
8597 case 2: role = @"Developer"; break;
8602 if (![role isEqualToString:Role_]) {
8603 bool rolling(Role_ == nil);
8606 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8610 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8614 [roledelegate_ loadData];
8616 [roledelegate_ updateData];
8620 - (void) segmentChanged:(UISegmentedControl *)control {
8621 [self showDoneButton];
8624 - (void) saveAndClose {
8627 [[self navigationItem] setRightBarButtonItem:nil];
8628 [[self navigationController] dismissModalViewControllerAnimated:YES];
8631 - (void) doneButtonClicked {
8632 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8633 [spinner startAnimating];
8634 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8635 [[self navigationItem] setRightBarButtonItem:spinItem];
8637 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8640 - (void) showDoneButton {
8641 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8642 initWithTitle:UCLocalize("DONE")
8643 style:UIBarButtonItemStyleDone
8645 action:@selector(doneButtonClicked)
8646 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8649 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8650 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8654 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8658 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8659 return nil; // This method is required by the protocol.
8662 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8664 return UCLocalize("ROLE_EX");
8666 return [NSString stringWithFormat:
8667 @"%@: %@\n%@: %@\n%@: %@",
8668 UCLocalize("USER"), UCLocalize("USER_EX"),
8669 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8670 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8675 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8676 return section == 3 ? 44.0f : 0;
8679 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8680 return section == 3 ? container_ : nil;
8683 - (void) reloadData {
8686 [table_ reloadData];
8691 /* Stash Controller {{{ */
8692 @interface StashController : CyteViewController {
8693 _H<UIActivityIndicatorView> spinner_;
8694 _H<UILabel> status_;
8695 _H<UILabel> caption_;
8700 @implementation StashController
8703 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8704 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8706 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8707 CGRect spinrect = [spinner_ frame];
8708 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8709 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8710 [spinner_ setFrame:spinrect];
8711 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8712 [[self view] addSubview:spinner_];
8713 [spinner_ startAnimating];
8716 captrect.size.width = [[self view] frame].size.width;
8717 captrect.size.height = 40.0f;
8718 captrect.origin.x = 0;
8719 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8720 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8721 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8722 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8723 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8724 [caption_ setTextColor:[UIColor whiteColor]];
8725 [caption_ setBackgroundColor:[UIColor clearColor]];
8726 [caption_ setShadowColor:[UIColor blackColor]];
8727 [caption_ setTextAlignment:UITextAlignmentCenter];
8728 [[self view] addSubview:caption_];
8731 statusrect.size.width = [[self view] frame].size.width;
8732 statusrect.size.height = 30.0f;
8733 statusrect.origin.x = 0;
8734 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8735 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8736 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8737 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8738 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8739 [status_ setTextColor:[UIColor whiteColor]];
8740 [status_ setBackgroundColor:[UIColor clearColor]];
8741 [status_ setShadowColor:[UIColor blackColor]];
8742 [status_ setTextAlignment:UITextAlignmentCenter];
8743 [[self view] addSubview:status_];
8746 - (void) releaseSubviews {
8751 [super releaseSubviews];
8757 @interface CYURLCache : SDURLCache {
8762 @implementation CYURLCache
8764 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8767 else if ([event isEqualToString:@"no-cache"])
8769 else if ([event isEqualToString:@"store"])
8771 else if ([event isEqualToString:@"invalid"])
8773 else if ([event isEqualToString:@"memory"])
8775 else if ([event isEqualToString:@"disk"])
8777 else if ([event isEqualToString:@"miss"])
8780 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8784 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8785 if (NSURLResponse *response = [cached response])
8786 if (NSString *mime = [response MIMEType])
8787 if ([mime isEqualToString:@"text/cache-manifest"]) {
8788 NSURL *url([response URL]);
8791 NSLog(@"###: %@", [url absoluteString]);
8794 @synchronized (HostConfig_) {
8795 [CachedURLs_ addObject:url];
8799 [super storeCachedResponse:cached forRequest:request];
8804 @interface Cydia : UIApplication <
8805 ConfirmationControllerDelegate,
8808 UINavigationControllerDelegate,
8809 UITabBarControllerDelegate
8811 _H<UIWindow> window_;
8812 _H<CYTabBarController> tabbar_;
8813 _H<CydiaLoadingViewController> emulated_;
8815 _H<NSMutableArray> essential_;
8816 _H<NSMutableArray> broken_;
8818 Database *database_;
8820 _H<NSURL> starturl_;
8825 _H<StashController> stash_;
8834 @implementation Cydia
8836 - (void) beginUpdate {
8837 [tabbar_ beginUpdate];
8841 return [tabbar_ updating];
8845 if ([broken_ count] != 0) {
8846 int count = [broken_ count];
8848 UIAlertView *alert = [[[UIAlertView alloc]
8849 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8850 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8852 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8854 UCLocalize("TEMPORARY_IGNORE"),
8858 [alert setContext:@"fixhalf"];
8859 [alert setNumberOfRows:2];
8861 } else if (!Ignored_ && [essential_ count] != 0) {
8862 int count = [essential_ count];
8864 UIAlertView *alert = [[[UIAlertView alloc]
8865 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8866 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8868 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8870 UCLocalize("UPGRADE_ESSENTIAL"),
8871 UCLocalize("COMPLETE_UPGRADE"),
8875 [alert setContext:@"upgrade"];
8880 - (void) _saveConfig {
8886 NSString *error(nil);
8888 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8890 NSError *error(nil);
8891 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8892 NSLog(@"failure to save metadata data: %@", error);
8897 NSLog(@"failure to serialize metadata: %@", error);
8904 // Navigation controller for the queuing badge.
8905 - (UINavigationController *) queueNavigationController {
8906 NSArray *controllers = [tabbar_ viewControllers];
8907 return [controllers objectAtIndex:3];
8910 - (void) unloadData {
8911 [tabbar_ unloadData];
8914 - (void) _updateData {
8918 UINavigationController *navigation = [self queueNavigationController];
8920 id queuedelegate = nil;
8921 if ([[navigation viewControllers] count] > 0)
8922 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8924 [queuedelegate queueStatusDidChange];
8925 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8928 - (void) _refreshIfPossible:(NSDate *)update {
8929 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8931 bool recently = false;
8932 if (update != nil) {
8933 NSTimeInterval interval([update timeIntervalSinceNow]);
8934 if (interval <= 0 && interval > -(15*60))
8938 // Don't automatic refresh if:
8939 // - We already refreshed recently.
8940 // - We already auto-refreshed this launch.
8941 // - Auto-refresh is disabled.
8942 if (recently || loaded_ || ManualRefresh) {
8943 // If we are cancelling, we need to make sure it knows it's already loaded.
8946 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8948 // We are going to load, so remember that.
8951 SCNetworkReachabilityFlags flags; {
8952 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8953 SCNetworkReachabilityGetFlags(reachability, &flags);
8954 CFRelease(reachability);
8957 // XXX: this elaborate mess is what Apple is using to determine this? :(
8958 // XXX: do we care if the user has to intervene? maybe that's ok?
8960 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8961 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8962 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8963 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8964 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8965 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8969 // If we can reach the server, auto-refresh!
8971 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8977 - (void) refreshIfPossible {
8978 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8981 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8982 @synchronized (self) {
8983 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8984 [hud setText:UCLocalize("RELOADING_DATA")];
8986 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8989 [self removeProgressHUD:hud];
8993 [essential_ removeAllObjects];
8994 [broken_ removeAllObjects];
8996 NSArray *packages([database_ packages]);
8997 for (Package *package in packages) {
8999 [broken_ addObject:package];
9000 if ([package upgradableAndEssential:NO]) {
9001 if ([package essential])
9002 [essential_ addObject:package];
9007 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9010 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9011 [changesItem setBadgeValue:badge];
9012 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9013 [self setApplicationIconBadgeNumber:changes];
9016 [changesItem setBadgeValue:nil];
9017 [changesItem setAnimatedBadge:NO];
9018 [self setApplicationIconBadgeNumber:0];
9023 [self refreshIfPossible];
9026 - (void) updateData {
9032 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9035 - (void) disemulate {
9036 if (emulated_ == nil)
9039 [window_ addSubview:[tabbar_ view]];
9040 [[emulated_ view] removeFromSuperview];
9042 [window_ setUserInteractionEnabled:YES];
9045 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9046 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9048 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9050 UIViewController *parent;
9051 if (emulated_ == nil)
9060 [parent presentModalViewController:navigation animated:YES];
9063 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9064 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9066 if (navigation != nil)
9067 [navigation pushViewController:progress animated:YES];
9069 [self presentModalViewController:progress force:YES];
9071 [progress invoke:invocation withTitle:title];
9075 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9076 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9079 - (void) repairWithInvocation:(NSInvocation *)invocation {
9081 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9085 - (void) repairWithSelector:(SEL)selector {
9086 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9089 - (void) reloadData {
9090 [self reloadDataWithInvocation:nil];
9095 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9098 - (void) addSource:(NSDictionary *) source {
9102 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9103 AddSource(href, distribution, sections);
9106 - (void) addTrivialSource:(NSString *)href {
9107 AddSource(href, @"./");
9110 - (void) updateValues {
9115 pkgProblemResolver *resolver = [database_ resolver];
9117 resolver->InstallProtect();
9118 if (!resolver->Resolve(true))
9123 // XXX: this is a really crappy way of doing this.
9124 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9125 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9126 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9127 if ([tabbar_ updating])
9128 [tabbar_ cancelUpdate];
9130 if (![database_ prepare])
9133 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9134 [page setDelegate:self];
9135 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9138 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9139 [tabbar_ presentModalViewController:confirm_ animated:YES];
9145 @synchronized (self) {
9150 - (void) clearPackage:(Package *)package {
9151 @synchronized (self) {
9158 - (void) installPackages:(NSArray *)packages {
9159 @synchronized (self) {
9160 for (Package *package in packages)
9167 - (void) installPackage:(Package *)package {
9168 @synchronized (self) {
9175 - (void) removePackage:(Package *)package {
9176 @synchronized (self) {
9183 - (void) distUpgrade {
9184 @synchronized (self) {
9185 if (![database_ upgrade])
9192 [database_ perform];
9193 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9196 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9199 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9203 - (void) showSettings {
9204 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9207 - (void) retainNetworkActivityIndicator {
9208 if (activity_++ == 0)
9209 [self setNetworkActivityIndicatorVisible:YES];
9212 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9216 - (void) releaseNetworkActivityIndicator {
9217 if (--activity_ == 0)
9218 [self setNetworkActivityIndicatorVisible:NO];
9221 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9226 - (void) cancelAndClear:(bool)clear {
9227 @synchronized (self) {
9239 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9240 NSString *context([alert context]);
9242 if ([context isEqualToString:@"conffile"]) {
9243 FILE *input = [database_ input];
9244 if (button == [alert cancelButtonIndex])
9245 fprintf(input, "N\n");
9246 else if (button == [alert firstOtherButtonIndex])
9247 fprintf(input, "Y\n");
9250 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9251 } else if ([context isEqualToString:@"fixhalf"]) {
9252 if (button == [alert cancelButtonIndex]) {
9253 @synchronized (self) {
9254 for (Package *broken in (id) broken_) {
9257 NSString *id = [broken id];
9258 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9259 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9260 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9261 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9267 } else if (button == [alert firstOtherButtonIndex]) {
9268 [broken_ removeAllObjects];
9272 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9273 } else if ([context isEqualToString:@"upgrade"]) {
9274 if (button == [alert firstOtherButtonIndex]) {
9275 @synchronized (self) {
9276 for (Package *essential in (id) essential_)
9277 [essential install];
9282 } else if (button == [alert firstOtherButtonIndex] + 1) {
9284 } else if (button == [alert cancelButtonIndex]) {
9288 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9292 - (void) system:(NSString *)command {
9293 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9296 system([command UTF8String]);
9302 - (void) applicationWillSuspend {
9304 [super applicationWillSuspend];
9307 - (BOOL) isSafeToSuspend {
9310 NSLog(@"isSafeToSuspend: locked_ != 0");
9315 // Use external process status API internally.
9316 // This is probably a really bad idea.
9317 // XXX: what is the point of this? does this solve anything at all?
9318 uint64_t status = 0;
9320 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9321 notify_get_state(notify_token, &status);
9322 notify_cancel(notify_token);
9327 NSLog(@"isSafeToSuspend: status != 0");
9333 NSLog(@"isSafeToSuspend: -> true");
9338 - (void) applicationSuspend:(__GSEvent *)event {
9339 if ([self isSafeToSuspend])
9340 [super applicationSuspend:event];
9343 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9344 if ([self isSafeToSuspend])
9345 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9348 - (void) _setSuspended:(BOOL)value {
9349 if ([self isSafeToSuspend])
9350 [super _setSuspended:value];
9353 - (UIProgressHUD *) addProgressHUD {
9354 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9355 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9357 [window_ setUserInteractionEnabled:NO];
9359 UIViewController *target(tabbar_);
9360 if (UIViewController *modal = [target modalViewController])
9363 UIView *view([target view]);
9364 [view addSubview:hud];
9372 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9375 [hud removeFromSuperview];
9376 [window_ setUserInteractionEnabled:YES];
9379 - (CyteViewController *) pageForPackage:(NSString *)name {
9380 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9383 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9384 NSString *scheme([[url scheme] lowercaseString]);
9385 if ([[url absoluteString] length] <= [scheme length] + 3)
9387 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9388 NSArray *components([path pathComponents]);
9390 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9391 return [self pageForPackage:[components objectAtIndex:1]];
9393 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9396 NSString *base([components objectAtIndex:0]);
9398 CyteViewController *controller = nil;
9400 if ([base isEqualToString:@"url"]) {
9401 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9402 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9403 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9404 } else if (!external && [components count] == 1) {
9405 if ([base isEqualToString:@"manage"]) {
9406 controller = [[[ManageController alloc] init] autorelease];
9409 if ([base isEqualToString:@"sources"]) {
9410 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9413 if ([base isEqualToString:@"home"]) {
9414 controller = [[[HomeController alloc] init] autorelease];
9417 if ([base isEqualToString:@"sections"]) {
9418 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9421 if ([base isEqualToString:@"search"]) {
9422 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9425 if ([base isEqualToString:@"changes"]) {
9426 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9429 if ([base isEqualToString:@"installed"]) {
9430 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9432 } else if ([components count] == 2) {
9433 NSString *argument = [components objectAtIndex:1];
9435 if ([base isEqualToString:@"package"]) {
9436 controller = [self pageForPackage:argument];
9439 if (!external && [base isEqualToString:@"search"]) {
9440 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9443 if (!external && [base isEqualToString:@"sections"]) {
9444 if ([argument isEqualToString:@"all"])
9446 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9449 if (!external && [base isEqualToString:@"sources"]) {
9450 if ([argument isEqualToString:@"add"]) {
9451 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9452 [(SourcesController *)controller showAddSourcePrompt];
9454 Source *source = [database_ sourceWithKey:argument];
9455 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9459 if (!external && [base isEqualToString:@"launch"]) {
9460 [self launchApplicationWithIdentifier:argument suspended:NO];
9463 } else if (!external && [components count] == 3) {
9464 NSString *arg1 = [components objectAtIndex:1];
9465 NSString *arg2 = [components objectAtIndex:2];
9467 if ([base isEqualToString:@"package"]) {
9468 if ([arg2 isEqualToString:@"settings"]) {
9469 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9470 } else if ([arg2 isEqualToString:@"files"]) {
9471 if (Package *package = [database_ packageWithName:arg1]) {
9472 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9473 [(FileTable *)controller setPackage:package];
9479 [controller setDelegate:self];
9483 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9484 CyteViewController *page([self pageForURL:url forExternal:external]);
9487 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9488 [nav setViewControllers:[NSArray arrayWithObject:page]];
9489 [tabbar_ setUnselectedViewController:nav];
9495 - (void) applicationOpenURL:(NSURL *)url {
9496 [super applicationOpenURL:url];
9501 [self openCydiaURL:url forExternal:YES];
9504 - (void) applicationWillResignActive:(UIApplication *)application {
9505 // Stop refreshing if you get a phone call or lock the device.
9506 if ([tabbar_ updating])
9507 [tabbar_ cancelUpdate];
9509 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9510 [super applicationWillResignActive:application];
9513 - (void) saveState {
9514 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9515 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9516 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9522 - (void) applicationWillTerminate:(UIApplication *)application {
9526 - (void) setConfigurationData:(NSString *)data {
9527 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9529 if (!conffile_r(data)) {
9530 lprintf("E:invalid conffile\n");
9534 NSString *ofile = conffile_r[1];
9535 //NSString *nfile = conffile_r[2];
9537 UIAlertView *alert = [[[UIAlertView alloc]
9538 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9539 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9541 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9543 UCLocalize("ACCEPT_NEW_COPY"),
9544 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9548 [alert setContext:@"conffile"];
9549 [alert setNumberOfRows:2];
9553 - (void) addStashController {
9555 stash_ = [[[StashController alloc] init] autorelease];
9556 [window_ addSubview:[stash_ view]];
9559 - (void) removeStashController {
9560 [[stash_ view] removeFromSuperview];
9566 [self setIdleTimerDisabled:YES];
9568 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9569 UpdateExternalStatus(1);
9570 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9571 UpdateExternalStatus(0);
9573 [self removeStashController];
9575 if (ExecFork() == 0) {
9576 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9577 perror("launchctl stop");
9581 - (void) setupViewControllers {
9582 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9584 NSMutableArray *items([NSMutableArray arrayWithObjects:
9585 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9586 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9587 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9588 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9592 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9593 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9595 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9598 NSMutableArray *controllers([NSMutableArray array]);
9599 for (UITabBarItem *item in items) {
9600 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9601 [controller setTabBarItem:item];
9602 [controllers addObject:controller];
9604 [tabbar_ setViewControllers:controllers];
9606 [tabbar_ setUpdateDelegate:self];
9609 - (void) applicationDidFinishLaunching:(id)unused {
9611 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9612 [self setApplicationSupportsShakeToEdit:NO];
9614 @synchronized (HostConfig_) {
9615 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9618 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9619 initWithMemoryCapacity:524288
9620 diskCapacity:10485760
9621 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9624 [CydiaWebViewController _initialize];
9626 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9628 // this would disallow http{,s} URLs from accessing this data
9629 //[WebView registerURLSchemeAsLocal:@"cydia"];
9631 Font12_ = [UIFont systemFontOfSize:12];
9632 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9633 Font14_ = [UIFont systemFontOfSize:14];
9634 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9635 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9637 essential_ = [NSMutableArray arrayWithCapacity:4];
9638 broken_ = [NSMutableArray arrayWithCapacity:4];
9640 // XXX: I really need this thing... like, seriously... I'm sorry
9641 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9643 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9644 [window_ orderFront:self];
9645 [window_ makeKey:self];
9646 [window_ setHidden:NO];
9649 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9650 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9651 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9652 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9653 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9654 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9655 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9656 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9657 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9660 [self addStashController];
9661 // XXX: this would be much cleaner as a yieldToSelector:
9662 // that way the removeStashController could happen right here inline
9663 // we also could no longer require the useless stash_ field anymore
9664 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9668 database_ = [Database sharedInstance];
9669 [database_ setDelegate:self];
9671 [window_ setUserInteractionEnabled:NO];
9672 [self setupViewControllers];
9674 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9675 [window_ addSubview:[emulated_ view]];
9677 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9681 - (NSArray *) defaultStartPages {
9682 NSMutableArray *standard = [NSMutableArray array];
9683 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9684 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9685 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9687 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9689 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9690 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9692 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9699 [window_ setUserInteractionEnabled:YES];
9700 [self showSettings];
9703 if ([emulated_ modalViewController] != nil)
9704 [emulated_ dismissModalViewControllerAnimated:YES];
9705 [window_ setUserInteractionEnabled:NO];
9713 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9714 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9715 int standardIndex = 0;
9716 NSArray *standard = [self defaultStartPages];
9723 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9724 if (valid && closed != nil) {
9725 NSTimeInterval interval([closed timeIntervalSinceNow]);
9726 // XXX: Is 15 minutes the optimal time here?
9727 if (interval > 0 && interval <= -(15*60))
9731 if (valid && [saved count] != [standard count])
9735 for (unsigned int i = 0; i < [standard count]; i++) {
9736 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9737 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9738 // but it's good enough for now.
9739 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9746 NSArray *items = nil;
9748 [tabbar_ setSelectedIndex:savedIndex];
9751 [tabbar_ setSelectedIndex:standardIndex];
9755 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9756 NSArray *stack = [items objectAtIndex:tab];
9757 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9758 NSMutableArray *current = [NSMutableArray array];
9760 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9761 NSString *addr = [stack objectAtIndex:nav];
9762 NSURL *url = [NSURL URLWithString:addr];
9763 CyteViewController *page = [self pageForURL:url forExternal:NO];
9765 [current addObject:page];
9768 [navigation setViewControllers:current];
9771 // (Try to) show the startup URL.
9772 if (starturl_ != nil) {
9773 [self openCydiaURL:starturl_ forExternal:NO];
9778 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9779 if (item != nil && IsWildcat_) {
9780 [sheet showFromBarButtonItem:item animated:YES];
9782 [sheet showInView:window_];
9786 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9787 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9788 [progress setTitle:task];
9789 [progress addProgressEvent:event];
9792 - (void) addProgressEventForTask:(NSArray *)data {
9793 CydiaProgressEvent *event([data objectAtIndex:0]);
9794 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9795 [self addProgressEvent:event forTask:task];
9798 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9799 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9805 id Alloc_(id self, SEL selector) {
9806 id object = alloc_(self, selector);
9807 lprintf("[%s]A-%p\n", self->isa->name, object);
9812 id Dealloc_(id self, SEL selector) {
9813 id object = dealloc_(self, selector);
9814 lprintf("[%s]D-%p\n", self->isa->name, object);
9818 Class $WebDefaultUIKitDelegate;
9820 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9821 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9822 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9823 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9826 static NSSet *MobilizedFiles_;
9828 static NSURL *MobilizeURL(NSURL *url) {
9829 NSString *path([url path]);
9830 if ([path hasPrefix:@"/var/root/"]) {
9831 NSString *file([path substringFromIndex:10]);
9832 if ([MobilizedFiles_ containsObject:file])
9833 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9839 Class $CFXPreferencesPropertyListSource;
9840 @class CFXPreferencesPropertyListSource;
9842 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9843 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9844 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9845 url = MobilizeURL(url);
9846 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9847 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9853 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9854 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9855 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9856 url = MobilizeURL(url);
9857 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9858 //NSLog(@"%@ %@", [url absoluteString], value);
9864 Class $NSURLConnection;
9866 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9867 NSMutableURLRequest *copy([request mutableCopy]);
9869 NSURL *url([copy URL]);
9871 NSString *href([url absoluteString]);
9872 NSString *host([url host]);
9873 NSString *scheme([[url scheme] lowercaseString]);
9875 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9877 @synchronized (HostConfig_) {
9878 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9879 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9880 [copy setHTTPShouldUsePipelining:YES];
9882 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9883 if ([control isEqualToString:@"max-age=0"])
9884 if ([CachedURLs_ containsObject:href]) {
9886 NSLog(@"~~~: %@", href);
9889 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9891 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9892 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9893 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9897 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9901 int main(int argc, char *argv[]) {
9902 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9906 UpdateExternalStatus(0);
9908 if (Class $UIDevice = objc_getClass("UIDevice")) {
9909 UIDevice *device([$UIDevice currentDevice]);
9910 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9914 UIScreen *screen([UIScreen mainScreen]);
9915 if ([screen respondsToSelector:@selector(scale)])
9916 ScreenScale_ = [screen scale];
9920 UIDevice *device([UIDevice currentDevice]);
9921 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9924 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9925 if (idiom == UIUserInterfaceIdiomPhone)
9927 else if (idiom == UIUserInterfaceIdiomPad)
9930 NSLog(@"unknown UIUserInterfaceIdiom!");
9933 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9935 HostConfig_ = [[[NSObject alloc] init] autorelease];
9936 @synchronized (HostConfig_) {
9937 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9938 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9939 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9940 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9941 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9944 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9946 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9948 MobilizedFiles_ = [NSMutableSet setWithObjects:
9949 @"Library/Preferences/com.apple.Accessibility.plist",
9950 @"Library/Preferences/com.apple.preferences.sounds.plist",
9953 /* Library Hacks {{{ */
9954 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9956 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9958 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9959 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9960 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9961 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9964 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9965 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9966 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9967 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9970 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9971 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9972 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9973 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9974 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9977 $NSURLConnection = objc_getClass("NSURLConnection");
9978 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9979 if (NSURLConnection$init$ != NULL) {
9980 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9981 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9984 /* Set Locale {{{ */
9985 Locale_ = CFLocaleCopyCurrent();
9986 Languages_ = [NSLocale preferredLanguages];
9988 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9989 //NSLog(@"%@", [Languages_ description]);
9992 if (Locale_ != NULL)
9993 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9994 else if (Languages_ != nil && [Languages_ count] != 0)
9995 lang = [[Languages_ objectAtIndex:0] UTF8String];
9997 // XXX: consider just setting to C and then falling through?
10000 if (lang != NULL) {
10001 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10002 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10005 NSLog(@"Setting Language: %s", lang);
10007 if (lang != NULL) {
10008 setenv("LANG", lang, true);
10009 std::setlocale(LC_ALL, lang);
10013 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10015 /* Parse Arguments {{{ */
10016 bool substrate(false);
10022 for (int argi(1); argi != argc; ++argi)
10023 if (strcmp(argv[argi], "--") == 0) {
10025 argv[argi] = argv[0];
10031 for (int argi(1); argi != arge; ++argi)
10032 if (strcmp(args[argi], "--substrate") == 0)
10035 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10039 App_ = [[NSBundle mainBundle] bundlePath];
10045 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10046 alloc_ = alloc->method_imp;
10047 alloc->method_imp = (IMP) &Alloc_;*/
10049 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10050 dealloc_ = dealloc->method_imp;
10051 dealloc->method_imp = (IMP) &Dealloc_;*/
10053 /* System Information {{{ */
10057 size = sizeof(maxproc);
10058 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10059 perror("sysctlbyname(\"kern.maxproc\", ?)");
10060 else if (maxproc < 64) {
10062 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10063 perror("sysctlbyname(\"kern.maxproc\", #)");
10066 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10067 char *osversion = new char[size];
10068 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10069 perror("sysctlbyname(\"kern.osversion\", ?)");
10071 System_ = [NSString stringWithUTF8String:osversion];
10073 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10074 char *machine = new char[size];
10075 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10076 perror("sysctlbyname(\"hw.machine\", ?)");
10078 Machine_ = machine;
10080 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10081 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10082 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10084 UniqueID_ = [device uniqueIdentifier];
10086 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10087 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10088 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10090 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10091 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10092 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10094 if (mcc != NULL && mnc != NULL)
10095 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10102 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10103 Build_ = [system objectForKey:@"ProductBuildVersion"];
10104 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10105 Product_ = [info objectForKey:@"SafariProductVersion"];
10106 Safari_ = [info objectForKey:@"CFBundleVersion"];
10109 /* Load Database {{{ */
10111 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10113 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10115 if (Metadata_ == NULL)
10116 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10118 Settings_ = [Metadata_ objectForKey:@"Settings"];
10120 Packages_ = [Metadata_ objectForKey:@"Packages"];
10122 Values_ = [Metadata_ objectForKey:@"Values"];
10123 Sections_ = [Metadata_ objectForKey:@"Sections"];
10124 Sources_ = [Metadata_ objectForKey:@"Sources"];
10126 Token_ = [Metadata_ objectForKey:@"Token"];
10128 Version_ = [Metadata_ objectForKey:@"Version"];
10130 @synchronized (HostConfig_) {
10131 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10135 if (Settings_ != nil)
10136 Role_ = [Settings_ objectForKey:@"Role"];
10138 if (Values_ == nil) {
10139 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10140 [Metadata_ setObject:Values_ forKey:@"Values"];
10143 if (Sections_ == nil) {
10144 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10145 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10148 if (Sources_ == nil) {
10149 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10150 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10153 if (Version_ == nil) {
10154 Version_ = [NSNumber numberWithUnsignedInt:0];
10155 [Metadata_ setObject:Version_ forKey:@"Version"];
10158 @synchronized (HostConfig_) {
10159 if (CydiaSource_ == nil) {
10160 CydiaSource_ = @"apt.saurik.com";
10161 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10165 if ([Version_ unsignedIntValue] == 0) {
10166 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10167 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10168 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10169 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10171 Version_ = [NSNumber numberWithUnsignedInt:1];
10172 [Metadata_ setObject:Version_ forKey:@"Version"];
10181 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10184 if (Packages_ != nil) {
10186 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10190 [Metadata_ removeObjectForKey:@"Packages"];
10196 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10198 #define MobileSubstrate_(name) \
10199 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10200 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10201 if (handle == NULL) \
10202 NSLog(@"%s", dlerror()); \
10205 MobileSubstrate_(Activator)
10206 MobileSubstrate_(libstatusbar)
10207 MobileSubstrate_(SimulatedKeyEvents)
10208 MobileSubstrate_(WinterBoard)
10210 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10211 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10213 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10215 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10216 unlink("/tmp/.cydia.fw");
10218 } else if (access("/User", F_OK) != 0 || version < 4) {
10221 system("/usr/libexec/cydia/firmware.sh");
10225 _assert([[NSFileManager defaultManager]
10226 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10227 withIntermediateDirectories:YES
10232 if (access("/tmp/cydia.chk", F_OK) == 0) {
10233 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10234 _assert(errno == ENOENT);
10235 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10236 _assert(errno == ENOENT);
10239 /* APT Initialization {{{ */
10240 _assert(pkgInitConfig(*_config));
10241 _assert(pkgInitSystem(*_config, _system));
10244 _config->Set("APT::Acquire::Translation", lang);
10246 // XXX: this timeout might be important :(
10247 //_config->Set("Acquire::http::Timeout", 15);
10249 _config->Set("Acquire::http::MaxParallel", 3);
10251 /* Color Choices {{{ */
10252 space_ = CGColorSpaceCreateDeviceRGB();
10254 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10255 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10256 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10257 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10258 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10259 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10260 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10261 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10262 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10264 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10265 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10267 /* UIKit Configuration {{{ */
10268 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10269 if ($GSFontSetUseLegacyFontMetrics != NULL)
10270 $GSFontSetUseLegacyFontMetrics(YES);
10272 // XXX: I have a feeling this was important
10273 //UIKeyboardDisableAutomaticAppearance();
10276 Colon_ = UCLocalize("COLON_DELIMITED");
10277 Elision_ = UCLocalize("ELISION");
10278 Error_ = UCLocalize("ERROR");
10279 Warning_ = UCLocalize("WARNING");
10282 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10284 CGColorSpaceRelease(space_);
10285 CFRelease(Locale_);