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
874 - (void) returnToCydia;
876 - (void) retainNetworkActivityIndicator;
877 - (void) releaseNetworkActivityIndicator;
878 - (void) clearPackage:(Package *)package;
879 - (void) installPackage:(Package *)package;
880 - (void) installPackages:(NSArray *)packages;
881 - (void) removePackage:(Package *)package;
882 - (void) beginUpdate;
884 - (void) distUpgrade;
888 - (void) addSource:(NSDictionary *)source;
889 - (void) addTrivialSource:(NSString *)href;
890 - (void) showSettings;
891 - (UIProgressHUD *) addProgressHUD;
892 - (void) removeProgressHUD:(UIProgressHUD *)hud;
893 - (CyteViewController *) pageForPackage:(NSString *)name;
894 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
895 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
899 /* Status Delegation {{{ */
901 public pkgAcquireStatus
904 _transient NSObject<ProgressDelegate> *delegate_;
914 void setDelegate(NSObject<ProgressDelegate> *delegate) {
915 delegate_ = delegate;
918 NSObject<ProgressDelegate> *getDelegate() const {
922 virtual bool MediaChange(std::string media, std::string drive) {
926 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
929 virtual void Fetch(pkgAcquire::ItemDesc &item) {
930 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
931 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
932 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
935 virtual void Done(pkgAcquire::ItemDesc &item) {
938 virtual void Fail(pkgAcquire::ItemDesc &item) {
940 item.Owner->Status == pkgAcquire::Item::StatIdle ||
941 item.Owner->Status == pkgAcquire::Item::StatDone
945 std::string &error(item.Owner->ErrorText);
949 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
950 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
953 virtual bool Pulse(pkgAcquire *Owner) {
954 bool value = pkgAcquireStatus::Pulse(Owner);
957 double(CurrentBytes + CurrentItems) /
958 double(TotalBytes + TotalItems)
961 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
962 [NSNumber numberWithDouble:percent], @"Percent",
964 [NSNumber numberWithDouble:CurrentBytes], @"Current",
965 [NSNumber numberWithDouble:TotalBytes], @"Total",
966 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
967 nil] waitUntilDone:YES];
969 if (value && ![delegate_ isProgressCancelled])
977 _finline bool WasCancelled() const {
981 virtual void Start() {
982 pkgAcquireStatus::Start();
983 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
986 virtual void Stop() {
987 pkgAcquireStatus::Stop();
988 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
989 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
993 /* Database Interface {{{ */
994 typedef std::map< unsigned long, _H<Source> > SourceMap;
996 @interface Database : NSObject {
1002 pkgCacheFile cache_;
1003 pkgDepCache::Policy *policy_;
1004 pkgRecords *records_;
1005 pkgProblemResolver *resolver_;
1006 pkgAcquire *fetcher_;
1008 SPtr<pkgPackageManager> manager_;
1009 pkgSourceList *list_;
1011 SourceMap sourceMap_;
1012 _H<NSMutableArray> sourceList_;
1014 CFMutableArrayRef packages_;
1016 _transient NSObject<DatabaseDelegate> *delegate_;
1017 _transient NSObject<ProgressDelegate> *progress_;
1025 std::map<const char *, _H<NSString> > sections_;
1028 + (Database *) sharedInstance;
1031 - (void) _readCydia:(NSNumber *)fd;
1032 - (void) _readStatus:(NSNumber *)fd;
1033 - (void) _readOutput:(NSNumber *)fd;
1037 - (Package *) packageWithName:(NSString *)name;
1039 - (pkgCacheFile &) cache;
1040 - (pkgDepCache::Policy *) policy;
1041 - (pkgRecords *) records;
1042 - (pkgProblemResolver *) resolver;
1043 - (pkgAcquire &) fetcher;
1044 - (pkgSourceList &) list;
1045 - (NSArray *) packages;
1046 - (NSArray *) sources;
1047 - (Source *) sourceWithKey:(NSString *)key;
1048 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1056 - (void) updateWithStatus:(Status &)status;
1058 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1060 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1061 - (NSObject<ProgressDelegate> *) progressDelegate;
1063 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1065 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1069 /* ProgressEvent Implementation {{{ */
1070 @implementation CydiaProgressEvent
1072 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1073 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1076 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1077 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1078 [event setPackage:package];
1082 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1083 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1085 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1086 NSArray *fields([description componentsSeparatedByString:@" "]);
1087 [event setItem:fields];
1089 if ([fields count] > 3) {
1090 [event setPackage:[fields objectAtIndex:2]];
1091 [event setVersion:[fields objectAtIndex:3]];
1094 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1099 + (NSArray *) _attributeKeys {
1100 return [NSArray arrayWithObjects:
1110 - (NSArray *) attributeKeys {
1111 return [[self class] _attributeKeys];
1114 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1115 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1118 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1119 if ((self = [super init]) != nil) {
1125 - (NSString *) message {
1129 - (NSString *) type {
1133 - (NSArray *) item {
1134 return (id) item_ ?: [NSNull null];
1137 - (void) setItem:(NSArray *)item {
1141 - (NSString *) package {
1142 return (id) package_ ?: [NSNull null];
1145 - (void) setPackage:(NSString *)package {
1149 - (NSString *) url {
1150 return (id) url_ ?: [NSNull null];
1153 - (void) setURL:(NSString *)url {
1157 - (void) setVersion:(NSString *)version {
1161 - (NSString *) version {
1162 return (id) version_ ?: [NSNull null];
1165 - (NSString *) compound:(NSString *)value {
1167 NSString *mode(nil); {
1168 NSString *type([self type]);
1169 if ([type isEqualToString:kCydiaProgressEventTypeError])
1170 mode = UCLocalize("ERROR");
1171 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1172 mode = UCLocalize("WARNING");
1176 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1182 - (NSString *) compoundMessage {
1183 return [self compound:[self message]];
1186 - (NSString *) compoundTitle {
1189 if (package_ == nil)
1191 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1192 title = [package name];
1196 return [self compound:title];
1202 // Cytore Definitions {{{
1203 struct PackageValue :
1206 Cytore::Offset<PackageValue> next_;
1208 uint32_t index_ : 23;
1209 uint32_t subscribed_ : 1;
1226 Cytore::Offset<PackageValue> packages_[1 << 16];
1229 static Cytore::File<MetaValue> MetaFile_;
1231 // Cytore Helper Functions {{{
1232 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1233 SplitHash nhash = { hashlittle(name, length) };
1235 PackageValue *metadata;
1237 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1238 offset: if (offset->IsNull()) {
1239 *offset = MetaFile_.New<PackageValue>(length + 1);
1240 metadata = &MetaFile_.Get(*offset);
1242 if (metadata == NULL) {
1246 metadata = new PackageValue();
1247 memset(metadata, 0, sizeof(*metadata));
1250 memcpy(metadata->name_, name, length + 1);
1251 metadata->nhash_ = nhash.u16[1];
1253 metadata = &MetaFile_.Get(*offset);
1255 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1256 offset = &metadata->next_;
1264 static void PackageImport(const void *key, const void *value, void *context) {
1265 bool &fail(*reinterpret_cast<bool *>(context));
1268 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1269 NSLog(@"failed to import package %@", key);
1273 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1274 NSDictionary *package((NSDictionary *) value);
1276 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1277 if ([subscribed boolValue] && !metadata->subscribed_)
1278 metadata->subscribed_ = true;
1280 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1281 time_t time([date timeIntervalSince1970]);
1282 if (metadata->first_ > time || metadata->first_ == 0)
1283 metadata->first_ = time;
1286 NSDate *date([package objectForKey:@"LastSeen"]);
1287 NSString *version([package objectForKey:@"LastVersion"]);
1289 if (date != nil && version != nil) {
1290 time_t time([date timeIntervalSince1970]);
1291 if (metadata->last_ < time || metadata->last_ == 0)
1292 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1293 size_t length(strlen(buffer));
1294 uint16_t vhash(hashlittle(buffer, length));
1296 size_t capped(std::min<size_t>(8, length));
1297 char *latest(buffer + length - capped);
1299 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1300 metadata->vhash_ = vhash;
1302 metadata->last_ = time;
1308 /* Source Class {{{ */
1309 @interface Source : NSObject {
1310 CYString depiction_;
1311 CYString description_;
1317 CYString distribution_;
1323 _H<NSString> authority_;
1325 CYString defaultIcon_;
1327 _H<NSDictionary> record_;
1331 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1333 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1335 - (NSString *) depictionForPackage:(NSString *)package;
1336 - (NSString *) supportForPackage:(NSString *)package;
1338 - (NSDictionary *) record;
1342 - (NSString *) distribution;
1343 - (NSString *) type;
1345 - (NSString *) base;
1348 - (NSString *) host;
1350 - (NSString *) name;
1351 - (NSString *) shortDescription;
1352 - (NSString *) label;
1353 - (NSString *) origin;
1354 - (NSString *) version;
1356 - (NSString *) defaultIcon;
1360 @implementation Source
1364 distribution_.clear();
1369 description_.clear();
1375 defaultIcon_.clear();
1382 + (NSString *) webScriptNameForSelector:(SEL)selector {
1384 else if (selector == @selector(addSection:))
1385 return @"addSection";
1386 else if (selector == @selector(removeSection:))
1387 return @"removeSection";
1388 else if (selector == @selector(remove))
1394 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1395 return [self webScriptNameForSelector:selector] == nil;
1398 + (NSArray *) _attributeKeys {
1399 return [NSArray arrayWithObjects:
1407 @"shortDescription",
1415 - (NSArray *) attributeKeys {
1416 return [[self class] _attributeKeys];
1419 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1420 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1423 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1426 trusted_ = index->IsTrusted();
1428 uri_.set(pool, index->GetURI());
1429 distribution_.set(pool, index->GetDist());
1430 type_.set(pool, index->GetType());
1432 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1433 if (dindex != NULL) {
1434 base_.set(pool, dindex->MetaIndexURI(""));
1437 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1440 pkgTagFile tags(&fd);
1442 pkgTagSection section;
1449 {"default-icon", &defaultIcon_},
1450 {"depiction", &depiction_},
1451 {"description", &description_},
1453 {"origin", &origin_},
1454 {"support", &support_},
1455 {"version", &version_},
1458 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1459 const char *start, *end;
1461 if (section.Find(names[i].name_, start, end)) {
1462 CYString &value(*names[i].value_);
1463 value.set(pool, start, end - start);
1469 record_ = [Sources_ objectForKey:[self key]];
1471 NSURL *url([NSURL URLWithString:uri_]);
1475 host_ = [host_ lowercaseString];
1480 authority_ = [url path];
1483 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1484 if ((self = [super init]) != nil) {
1485 [self setMetaIndex:index inPool:pool];
1489 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1490 NSDictionary *lhr = [self record];
1491 NSDictionary *rhr = [source record];
1493 if ((lhr == nil) != (rhr == nil))
1494 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1496 NSString *lhs = [self name];
1497 NSString *rhs = [source name];
1499 if ([lhs length] != 0 && [rhs length] != 0) {
1500 unichar lhc = [lhs characterAtIndex:0];
1501 unichar rhc = [rhs characterAtIndex:0];
1503 if (isalpha(lhc) && !isalpha(rhc))
1504 return NSOrderedAscending;
1505 else if (!isalpha(lhc) && isalpha(rhc))
1506 return NSOrderedDescending;
1509 return [lhs compare:rhs options:LaxCompareOptions_];
1512 - (NSString *) depictionForPackage:(NSString *)package {
1513 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1516 - (NSString *) supportForPackage:(NSString *)package {
1517 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1520 - (NSArray *) sections {
1521 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1524 - (void) _addSection:(NSString *)section {
1527 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1528 if (![sections containsObject:section]) {
1529 [sections addObject:section];
1533 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1538 - (bool) addSection:(NSString *)section {
1542 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1546 - (void) _removeSection:(NSString *)section {
1550 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1551 if ([sections containsObject:section]) {
1552 [sections removeObject:section];
1557 - (bool) removeSection:(NSString *)section {
1561 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1566 [Sources_ removeObjectForKey:[self key]];
1571 bool value(record_ != nil);
1572 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1576 - (NSDictionary *) record {
1584 - (NSString *) uri {
1588 - (NSString *) distribution {
1589 return distribution_;
1592 - (NSString *) type {
1596 - (NSString *) base {
1600 - (NSString *) key {
1601 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1604 - (NSString *) host {
1608 - (NSString *) name {
1609 return origin_.empty() ? (id) authority_ : origin_;
1612 - (NSString *) shortDescription {
1613 return description_;
1616 - (NSString *) label {
1617 return label_.empty() ? (id) authority_ : label_;
1620 - (NSString *) origin {
1624 - (NSString *) version {
1628 - (NSString *) defaultIcon {
1629 return defaultIcon_;
1634 /* CydiaOperation Class {{{ */
1635 @interface CydiaOperation : NSObject {
1636 _H<NSString> operator_;
1637 _H<NSString> value_;
1640 - (NSString *) operator;
1641 - (NSString *) value;
1645 @implementation CydiaOperation
1647 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1648 if ((self = [super init]) != nil) {
1649 operator_ = [NSString stringWithUTF8String:_operator];
1650 value_ = [NSString stringWithUTF8String:value];
1654 + (NSArray *) _attributeKeys {
1655 return [NSArray arrayWithObjects:
1661 - (NSArray *) attributeKeys {
1662 return [[self class] _attributeKeys];
1665 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1666 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1669 - (NSString *) operator {
1673 - (NSString *) value {
1679 /* CydiaClause Class {{{ */
1680 @interface CydiaClause : NSObject {
1681 _H<NSString> package_;
1682 _H<CydiaOperation> version_;
1685 - (NSString *) package;
1686 - (CydiaOperation *) version;
1690 @implementation CydiaClause
1692 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1693 if ((self = [super init]) != nil) {
1694 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1696 if (const char *version = dep.TargetVer())
1697 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1699 version_ = (id) [NSNull null];
1703 + (NSArray *) _attributeKeys {
1704 return [NSArray arrayWithObjects:
1710 - (NSArray *) attributeKeys {
1711 return [[self class] _attributeKeys];
1714 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1715 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1718 - (NSString *) package {
1722 - (CydiaOperation *) version {
1728 /* CydiaRelation Class {{{ */
1729 @interface CydiaRelation : NSObject {
1730 _H<NSString> relationship_;
1731 _H<NSMutableArray> clauses_;
1734 - (NSString *) relationship;
1735 - (NSArray *) clauses;
1739 @implementation CydiaRelation
1741 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1742 if ((self = [super init]) != nil) {
1743 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1744 clauses_ = [NSMutableArray arrayWithCapacity:8];
1746 pkgCache::DepIterator start;
1747 pkgCache::DepIterator end;
1748 dep.GlobOr(start, end); // ++dep
1751 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1753 // yes, seriously. (wtf?)
1761 + (NSArray *) _attributeKeys {
1762 return [NSArray arrayWithObjects:
1768 - (NSArray *) attributeKeys {
1769 return [[self class] _attributeKeys];
1772 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1773 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1776 - (NSString *) relationship {
1777 return relationship_;
1780 - (NSArray *) clauses {
1784 - (void) addClause:(CydiaClause *)clause {
1785 [clauses_ addObject:clause];
1790 /* Package Class {{{ */
1791 struct ParsedPackage {
1794 CYString architecture_;
1797 CYString depiction_;
1807 @interface Package : NSObject {
1810 uint32_t essential_ : 1;
1811 uint32_t obsolete_ : 1;
1812 uint32_t ignored_ : 1;
1818 _transient Database *database_;
1820 pkgCache::VerIterator version_;
1821 pkgCache::PkgIterator iterator_;
1822 pkgCache::VerFileIterator file_;
1828 CYString installed_;
1830 const char *section_;
1831 _transient NSString *section$_;
1835 PackageValue *metadata_;
1836 ParsedPackage *parsed_;
1838 _H<NSMutableArray> tags_;
1841 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1842 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1844 - (pkgCache::PkgIterator) iterator;
1847 - (NSString *) section;
1848 - (NSString *) simpleSection;
1850 - (NSString *) longSection;
1851 - (NSString *) shortSection;
1855 - (MIMEAddress *) maintainer;
1857 - (NSString *) longDescription;
1858 - (NSString *) shortDescription;
1861 - (PackageValue *) metadata;
1864 - (bool) subscribed;
1865 - (bool) setSubscribed:(bool)subscribed;
1869 - (NSString *) latest;
1870 - (NSString *) installed;
1871 - (BOOL) uninstalled;
1874 - (BOOL) upgradableAndEssential:(BOOL)essential;
1877 - (BOOL) unfiltered;
1881 - (BOOL) halfConfigured;
1882 - (BOOL) halfInstalled;
1884 - (NSString *) mode;
1887 - (NSString *) name;
1889 - (NSString *) homepage;
1890 - (NSString *) depiction;
1891 - (MIMEAddress *) author;
1893 - (NSString *) support;
1895 - (NSArray *) files;
1896 - (NSArray *) warnings;
1897 - (NSArray *) applications;
1899 - (Source *) source;
1902 - (BOOL) matches:(NSArray *)query;
1904 - (bool) hasSupportingRole;
1905 - (BOOL) hasTag:(NSString *)tag;
1906 - (NSString *) primaryPurpose;
1907 - (NSArray *) purposes;
1908 - (bool) isCommercial;
1910 - (void) setIndex:(size_t)index;
1912 - (CYString &) cyname;
1914 - (uint32_t) compareBySection:(NSArray *)sections;
1919 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1920 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1921 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1922 - (bool) isVisibleInSection:(NSString *)section;
1923 - (bool) isVisibleInSource:(Source *)source;
1927 uint32_t PackageChangesRadix(Package *self, void *) {
1932 uint32_t timestamp : 30;
1933 uint32_t ignored : 1;
1934 uint32_t upgradable : 1;
1938 bool upgradable([self upgradableAndEssential:YES]);
1939 value.bits.upgradable = upgradable ? 1 : 0;
1942 value.bits.timestamp = 0;
1943 value.bits.ignored = [self ignored] ? 0 : 1;
1944 value.bits.upgradable = 1;
1946 value.bits.timestamp = [self seen] >> 2;
1947 value.bits.ignored = 0;
1948 value.bits.upgradable = 0;
1951 return _not(uint32_t) - value.key;
1954 uint32_t PackagePrefixRadix(Package *self, void *context) {
1955 size_t offset(reinterpret_cast<size_t>(context));
1956 CYString &name([self cyname]);
1958 size_t size(name.size());
1961 char *text(name.data());
1964 if (!isdigit(text[0]))
1968 while (size != digits && isdigit(text[digits]))
1976 if (offset == 0 && zeros != 0) {
1977 memset(data, '0', zeros);
1978 memcpy(data + zeros, text, 4 - zeros);
1980 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1981 if (size <= offset - zeros)
1984 text += offset - zeros;
1985 size -= offset - zeros;
1988 memcpy(data, text, 4);
1990 memcpy(data, text, size);
1991 memset(data + size, 0, 4 - size);
1994 for (size_t i(0); i != 4; ++i)
1995 if (isalpha(data[i]))
2003 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2005 /* XXX: ntohl may be more honest */
2006 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2009 CYString &(*PackageName)(Package *self, SEL sel);
2011 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2012 _profile(PackageNameCompare)
2013 CYString &lhi(PackageName(lhs, @selector(cyname)));
2014 CYString &rhi(PackageName(rhs, @selector(cyname)));
2015 CFStringRef lhn(lhi), rhn(rhi);
2018 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2019 else if (rhn == NULL)
2020 return NSOrderedDescending;
2022 _profile(PackageNameCompare$NumbersLast)
2023 if (!lhi.empty() && !rhi.empty()) {
2024 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2025 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2026 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2027 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2028 return lha ? NSOrderedAscending : NSOrderedDescending;
2032 CFIndex length = CFStringGetLength(lhn);
2034 _profile(PackageNameCompare$Compare)
2035 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2040 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2041 return PackageNameCompare(*lhs, *rhs, context);
2044 struct PackageNameOrdering :
2045 std::binary_function<Package *, Package *, bool>
2047 _finline bool operator ()(Package *lhs, Package *rhs) const {
2048 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2052 @implementation Package
2054 - (NSString *) description {
2055 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2059 if (parsed_ != NULL)
2064 + (NSString *) webScriptNameForSelector:(SEL)selector {
2066 else if (selector == @selector(clear))
2068 else if (selector == @selector(getField:))
2070 else if (selector == @selector(hasTag:))
2072 else if (selector == @selector(install))
2074 else if (selector == @selector(remove))
2080 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2081 return [self webScriptNameForSelector:selector] == nil;
2084 + (NSArray *) _attributeKeys {
2085 return [NSArray arrayWithObjects:
2105 @"shortDescription",
2118 - (NSArray *) attributeKeys {
2119 return [[self class] _attributeKeys];
2122 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2123 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2126 - (NSArray *) relations {
2127 @synchronized (database_) {
2128 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2129 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2130 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2134 - (NSString *) architecture {
2136 @synchronized (database_) {
2137 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2140 - (NSString *) getField:(NSString *)name {
2141 @synchronized (database_) {
2142 if ([database_ era] != era_ || file_.end())
2145 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2147 const char *start, *end;
2148 if (!parser.Find([name UTF8String], start, end))
2149 return (NSString *) [NSNull null];
2151 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2155 if (parsed_ != NULL)
2157 @synchronized (database_) {
2158 if ([database_ era] != era_ || file_.end())
2161 ParsedPackage *parsed(new ParsedPackage);
2164 _profile(Package$parse)
2165 pkgRecords::Parser *parser;
2167 _profile(Package$parse$Lookup)
2168 parser = &[database_ records]->Lookup(file_);
2173 _profile(Package$parse$Find)
2178 {"architecture", &parsed->architecture_},
2179 {"icon", &parsed->icon_},
2180 {"depiction", &parsed->depiction_},
2181 {"homepage", &parsed->homepage_},
2182 {"website", &website},
2183 {"bugs", &parsed->bugs_},
2184 {"support", &parsed->support_},
2185 {"sponsor", &parsed->sponsor_},
2186 {"author", &parsed->author_},
2189 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2190 const char *start, *end;
2192 if (parser->Find(names[i].name_, start, end)) {
2193 CYString &value(*names[i].value_);
2194 _profile(Package$parse$Value)
2195 value.set(pool_, start, end - start);
2201 _profile(Package$parse$Tagline)
2202 const char *start, *end;
2203 if (parser->ShortDesc(start, end)) {
2204 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2207 while (stop != start && stop[-1] == '\r')
2209 parsed->tagline_.set(pool_, start, stop - start);
2213 _profile(Package$parse$Retain)
2214 if (parsed->homepage_.empty())
2215 parsed->homepage_ = website;
2216 if (parsed->homepage_ == parsed->depiction_)
2217 parsed->homepage_.clear();
2222 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2223 if ((self = [super init]) != nil) {
2224 _profile(Package$initWithVersion)
2227 database_ = database;
2228 era_ = [database era];
2232 pkgCache::PkgIterator iterator(version.ParentPkg());
2233 iterator_ = iterator;
2235 _profile(Package$initWithVersion$Version)
2236 if (!version_.end())
2237 file_ = version_.FileList();
2239 pkgCache &cache([database_ cache]);
2240 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2244 _profile(Package$initWithVersion$Cache)
2245 name_.set(NULL, iterator.Display());
2247 latest_.set(NULL, StripVersion_(version_.VerStr()));
2249 pkgCache::VerIterator current(iterator.CurrentVer());
2251 installed_.set(NULL, StripVersion_(current.VerStr()));
2254 _profile(Package$initWithVersion$Tags)
2255 pkgCache::TagIterator tag(iterator.TagList());
2257 tags_ = [NSMutableArray arrayWithCapacity:8];
2259 const char *name(tag.Name());
2260 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2262 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2263 if (strcmp(name + 6, "enduser") == 0)
2265 else if (strcmp(name + 6, "hacker") == 0)
2267 else if (strcmp(name + 6, "developer") == 0)
2269 else if (strcmp(name + 6, "cydia") == 0)
2275 if (strncmp(name, "cydia::", 7) == 0) {
2276 if (strcmp(name + 7, "essential") == 0)
2278 else if (strcmp(name + 7, "obsolete") == 0)
2283 } while (!tag.end());
2287 _profile(Package$initWithVersion$Metadata)
2288 const char *mixed(iterator.Name());
2289 size_t size(strlen(mixed));
2290 char lower[size + 1];
2292 for (size_t i(0); i != size; ++i)
2293 lower[i] = mixed[i] | 0x20;
2296 PackageValue *metadata(PackageFind(lower, size));
2297 metadata_ = metadata;
2299 id_.set(NULL, metadata->name_, size);
2301 const char *latest(version_.VerStr());
2302 size_t length(strlen(latest));
2304 uint16_t vhash(hashlittle(latest, length));
2306 size_t capped(std::min<size_t>(8, length));
2307 latest = latest + length - capped;
2309 if (metadata->first_ == 0)
2310 metadata->first_ = now_;
2312 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2313 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2314 metadata->vhash_ = vhash;
2315 metadata->last_ = now_;
2316 } else if (metadata->last_ == 0)
2317 metadata->last_ = metadata->first_;
2320 _profile(Package$initWithVersion$Section)
2321 section_ = iterator.Section();
2324 _profile(Package$initWithVersion$Flags)
2325 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2326 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2331 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2332 pkgCache::VerIterator version;
2334 _profile(Package$packageWithIterator$GetCandidateVer)
2335 version = [database policy]->GetCandidateVer(iterator);
2343 _profile(Package$packageWithIterator$Allocate)
2344 package = [Package allocWithZone:zone];
2347 _profile(Package$packageWithIterator$Initialize)
2349 initWithVersion:version
2356 _profile(Package$packageWithIterator$Autorelease)
2357 package = [package autorelease];
2363 - (pkgCache::PkgIterator) iterator {
2367 - (NSString *) section {
2368 if (section$_ == nil) {
2369 if (section_ == NULL)
2372 _profile(Package$section$mappedSectionForPointer)
2373 section$_ = [database_ mappedSectionForPointer:section_];
2378 - (NSString *) simpleSection {
2379 if (NSString *section = [self section])
2380 return Simplify(section);
2385 - (NSString *) longSection {
2386 return LocalizeSection([self section]);
2389 - (NSString *) shortSection {
2390 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2393 - (NSString *) uri {
2396 pkgIndexFile *index;
2397 pkgCache::PkgFileIterator file(file_.File());
2398 if (![database_ list].FindIndex(file, index))
2400 return [NSString stringWithUTF8String:iterator_->Path];
2401 //return [NSString stringWithUTF8String:file.Site()];
2402 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2406 - (MIMEAddress *) maintainer {
2407 @synchronized (database_) {
2408 if ([database_ era] != era_ || file_.end())
2411 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2412 const std::string &maintainer(parser->Maintainer());
2413 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2417 @synchronized (database_) {
2418 if ([database_ era] != era_ || version_.end())
2421 return version_->InstalledSize;
2424 - (NSString *) longDescription {
2425 @synchronized (database_) {
2426 if ([database_ era] != era_ || file_.end())
2429 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2430 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2432 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2433 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2434 if ([lines count] < 2)
2437 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2438 for (size_t i(1), e([lines count]); i != e; ++i) {
2439 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2440 [trimmed addObject:trim];
2443 return [trimmed componentsJoinedByString:@"\n"];
2446 - (NSString *) shortDescription {
2447 if (parsed_ != NULL)
2448 return static_cast<NSString *>(parsed_->tagline_);
2450 @synchronized (database_) {
2451 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2453 const char *start, *end;
2454 if (!parser.ShortDesc(start, end))
2457 if (end - start > 100)
2461 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2464 while (end != start && end[-1] == '\r')
2468 return [(id) CYStringCreate(start, end - start) autorelease];
2472 _profile(Package$index)
2473 CFStringRef name((CFStringRef) [self name]);
2474 if (CFStringGetLength(name) == 0)
2476 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2477 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2479 return toupper(character);
2483 - (PackageValue *) metadata {
2488 PackageValue *metadata([self metadata]);
2489 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2492 - (bool) subscribed {
2493 return [self metadata]->subscribed_;
2496 - (bool) setSubscribed:(bool)subscribed {
2497 PackageValue *metadata([self metadata]);
2498 if (metadata->subscribed_ == subscribed)
2500 metadata->subscribed_ = subscribed;
2508 - (NSString *) latest {
2512 - (NSString *) installed {
2516 - (BOOL) uninstalled {
2517 return installed_.empty();
2521 return !version_.end();
2524 - (BOOL) upgradableAndEssential:(BOOL)essential {
2525 _profile(Package$upgradableAndEssential)
2526 pkgCache::VerIterator current(iterator_.CurrentVer());
2528 return essential && essential_;
2530 return !version_.end() && version_ != current;
2534 - (BOOL) essential {
2539 return [database_ cache][iterator_].InstBroken();
2542 - (BOOL) unfiltered {
2543 _profile(Package$unfiltered$obsolete)
2544 if (_unlikely(obsolete_))
2548 _profile(Package$unfiltered$hasSupportingRole)
2549 if (_unlikely(![self hasSupportingRole]))
2557 if (![self unfiltered])
2562 _profile(Package$visible$section)
2563 section = [self section];
2566 _profile(Package$visible$isSectionVisible)
2567 if (!isSectionVisible(section))
2575 unsigned char current(iterator_->CurrentState);
2576 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2579 - (BOOL) halfConfigured {
2580 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2583 - (BOOL) halfInstalled {
2584 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2588 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2589 return state.Mode != pkgDepCache::ModeKeep;
2592 - (NSString *) mode {
2593 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2595 switch (state.Mode) {
2596 case pkgDepCache::ModeDelete:
2597 if ((state.iFlags & pkgDepCache::Purge) != 0)
2601 case pkgDepCache::ModeKeep:
2602 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2603 return @"REINSTALL";
2604 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2608 case pkgDepCache::ModeInstall:
2609 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2610 return @"REINSTALL";
2611 else*/ switch (state.Status) {
2613 return @"DOWNGRADE";
2619 return @"NEW_INSTALL";
2630 - (NSString *) name {
2631 return name_.empty() ? id_ : name_;
2634 - (UIImage *) icon {
2635 NSString *section = [self simpleSection];
2638 if (parsed_ != NULL)
2639 if (NSString *href = parsed_->icon_)
2640 if ([href hasPrefix:@"file:///"])
2641 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2642 if (icon == nil) if (section != nil)
2643 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2644 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2645 if ([dicon hasPrefix:@"file:///"])
2646 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2648 icon = [UIImage applicationImageNamed:@"unknown.png"];
2652 - (NSString *) homepage {
2653 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2656 - (NSString *) depiction {
2657 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2660 - (MIMEAddress *) sponsor {
2661 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2664 - (MIMEAddress *) author {
2665 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2668 - (NSString *) support {
2669 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2672 - (NSArray *) files {
2673 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2674 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2677 fin.open([path UTF8String]);
2682 while (std::getline(fin, line))
2683 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2688 - (NSString *) state {
2689 @synchronized (database_) {
2690 if ([database_ era] != era_ || file_.end())
2693 switch (iterator_->CurrentState) {
2694 case pkgCache::State::NotInstalled:
2695 return @"NotInstalled";
2696 case pkgCache::State::UnPacked:
2698 case pkgCache::State::HalfConfigured:
2699 return @"HalfConfigured";
2700 case pkgCache::State::HalfInstalled:
2701 return @"HalfInstalled";
2702 case pkgCache::State::ConfigFiles:
2703 return @"ConfigFiles";
2704 case pkgCache::State::Installed:
2705 return @"Installed";
2706 case pkgCache::State::TriggersAwaited:
2707 return @"TriggersAwaited";
2708 case pkgCache::State::TriggersPending:
2709 return @"TriggersPending";
2712 return (NSString *) [NSNull null];
2715 - (NSString *) selection {
2716 @synchronized (database_) {
2717 if ([database_ era] != era_ || file_.end())
2720 switch (iterator_->SelectedState) {
2721 case pkgCache::State::Unknown:
2723 case pkgCache::State::Install:
2725 case pkgCache::State::Hold:
2727 case pkgCache::State::DeInstall:
2728 return @"DeInstall";
2729 case pkgCache::State::Purge:
2733 return (NSString *) [NSNull null];
2736 - (NSArray *) warnings {
2737 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2738 const char *name(iterator_.Name());
2740 size_t length(strlen(name));
2741 if (length < 2) invalid:
2742 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2743 else for (size_t i(0); i != length; ++i)
2745 /* XXX: technically this is not allowed */
2746 (name[i] < 'A' || name[i] > 'Z') &&
2747 (name[i] < 'a' || name[i] > 'z') &&
2748 (name[i] < '0' || name[i] > '9') &&
2749 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2752 if (strcmp(name, "cydia") != 0) {
2755 bool _private = false;
2758 bool repository = [[self section] isEqualToString:@"Repositories"];
2760 if (NSArray *files = [self files])
2761 for (NSString *file in files)
2762 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2764 else if (!user && [file isEqualToString:@"/User"])
2766 else if (!_private && [file isEqualToString:@"/private"])
2768 else if (!stash && [file isEqualToString:@"/var/stash"])
2771 /* XXX: this is not sensitive enough. only some folders are valid. */
2772 if (cydia && !repository)
2773 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2775 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2777 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2779 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2782 return [warnings count] == 0 ? nil : warnings;
2785 - (NSArray *) applications {
2786 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2788 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2790 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2791 if (NSArray *files = [self files])
2792 for (NSString *file in files)
2793 if (application_r(file)) {
2794 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2795 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2796 if ([id isEqualToString:me])
2799 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2801 display = application_r[1];
2803 NSString *bundle([file stringByDeletingLastPathComponent]);
2804 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2805 if (icon == nil || [icon length] == 0)
2807 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2809 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2810 [applications addObject:application];
2812 [application addObject:id];
2813 [application addObject:display];
2814 [application addObject:url];
2817 return [applications count] == 0 ? nil : applications;
2820 - (Source *) source {
2821 if (source_ == nil) {
2822 @synchronized (database_) {
2823 if ([database_ era] != era_ || file_.end())
2824 source_ = (Source *) [NSNull null];
2826 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2830 return source_ == (Source *) [NSNull null] ? nil : source_;
2837 - (BOOL) matches:(NSArray *)query {
2838 if (query == nil || [query count] == 0)
2847 string = [self name];
2848 length = [string length];
2850 for (NSString *term in query) {
2851 range = [string rangeOfString:term options:MatchCompareOptions_];
2852 if (range.location != NSNotFound)
2853 rank_ -= 6 * 1000000 / length;
2858 length = [string length];
2860 for (NSString *term in query) {
2861 range = [string rangeOfString:term options:MatchCompareOptions_];
2862 if (range.location != NSNotFound)
2863 rank_ -= 6 * 1000000 / length;
2867 string = [self shortDescription];
2868 length = [string length];
2869 NSUInteger stop(std::min<NSUInteger>(length, 100));
2871 for (NSString *term in query) {
2872 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2873 if (range.location != NSNotFound)
2874 rank_ -= 2 * 100000;
2880 - (bool) hasSupportingRole {
2885 if ([Role_ isEqualToString:@"User"])
2889 if ([Role_ isEqualToString:@"Hacker"])
2893 if ([Role_ isEqualToString:@"Developer"])
2898 - (NSArray *) tags {
2902 - (BOOL) hasTag:(NSString *)tag {
2903 return tags_ == nil ? NO : [tags_ containsObject:tag];
2906 - (NSString *) primaryPurpose {
2907 for (NSString *tag in (NSArray *) tags_)
2908 if ([tag hasPrefix:@"purpose::"])
2909 return [tag substringFromIndex:9];
2913 - (NSArray *) purposes {
2914 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2915 for (NSString *tag in (NSArray *) tags_)
2916 if ([tag hasPrefix:@"purpose::"])
2917 [purposes addObject:[tag substringFromIndex:9]];
2918 return [purposes count] == 0 ? nil : purposes;
2921 - (bool) isCommercial {
2922 return [self hasTag:@"cydia::commercial"];
2925 - (void) setIndex:(size_t)index {
2926 if (metadata_->index_ != index)
2927 metadata_->index_ = index;
2930 - (CYString &) cyname {
2931 return name_.empty() ? id_ : name_;
2934 - (uint32_t) compareBySection:(NSArray *)sections {
2935 NSString *section([self section]);
2936 for (size_t i(0), e([sections count]); i != e; ++i) {
2937 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2941 return _not(uint32_t);
2945 @synchronized (database_) {
2946 pkgProblemResolver *resolver = [database_ resolver];
2947 resolver->Clear(iterator_);
2949 pkgCacheFile &cache([database_ cache]);
2950 cache->SetReInstall(iterator_, false);
2951 cache->MarkKeep(iterator_, false);
2955 @synchronized (database_) {
2956 pkgProblemResolver *resolver = [database_ resolver];
2957 resolver->Clear(iterator_);
2958 resolver->Protect(iterator_);
2960 pkgCacheFile &cache([database_ cache]);
2961 cache->SetReInstall(iterator_, false);
2962 cache->MarkInstall(iterator_, false);
2964 pkgDepCache::StateCache &state((*cache)[iterator_]);
2965 if (!state.Install())
2966 cache->SetReInstall(iterator_, true);
2970 @synchronized (database_) {
2971 pkgProblemResolver *resolver = [database_ resolver];
2972 resolver->Clear(iterator_);
2973 resolver->Remove(iterator_);
2974 resolver->Protect(iterator_);
2976 pkgCacheFile &cache([database_ cache]);
2977 cache->SetReInstall(iterator_, false);
2978 cache->MarkDelete(iterator_, true);
2981 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2982 _profile(Package$isUnfilteredAndSearchedForBy)
2985 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2986 value &= [self unfiltered];
2989 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2990 value &= [self matches:query];
2997 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2998 if ([search length] == 0)
3001 _profile(Package$isUnfilteredAndSelectedForBy)
3004 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3005 value &= [self unfiltered];
3008 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3009 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3016 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3017 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3020 - (bool) isVisibleInSection:(NSString *)name {
3021 NSString *section([self section]);
3025 section == nil && [name length] == 0 ||
3026 [name isEqualToString:section]
3027 ) && [self visible];
3030 - (bool) isVisibleInSource:(Source *)source {
3031 return [self source] == source && [self visible];
3036 /* Section Class {{{ */
3037 @interface Section : NSObject {
3042 _H<NSString> localized_;
3045 - (NSComparisonResult) compareByLocalized:(Section *)section;
3046 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3047 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3048 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3049 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3050 - (NSString *) name;
3057 - (void) addToCount;
3059 - (void) setCount:(size_t)count;
3060 - (NSString *) localized;
3064 @implementation Section
3066 - (NSComparisonResult) compareByLocalized:(Section *)section {
3067 NSString *lhs(localized_);
3068 NSString *rhs([section localized]);
3070 /*if ([lhs length] != 0 && [rhs length] != 0) {
3071 unichar lhc = [lhs characterAtIndex:0];
3072 unichar rhc = [rhs characterAtIndex:0];
3074 if (isalpha(lhc) && !isalpha(rhc))
3075 return NSOrderedAscending;
3076 else if (!isalpha(lhc) && isalpha(rhc))
3077 return NSOrderedDescending;
3080 return [lhs compare:rhs options:LaxCompareOptions_];
3083 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3084 if ((self = [self initWithName:name localize:NO]) != nil) {
3085 if (localized != nil)
3086 localized_ = localized;
3090 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3091 return [self initWithName:name row:0 localize:localize];
3094 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3095 if ((self = [super init]) != nil) {
3100 localized_ = LocalizeSection(name_);
3104 /* XXX: localize the index thingees */
3105 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3106 if ((self = [super init]) != nil) {
3107 name_ = [NSString stringWithCharacters:&index length:1];
3113 - (NSString *) name {
3133 - (void) addToCount {
3137 - (void) setCount:(size_t)count {
3141 - (NSString *) localized {
3148 static NSString *Colon_;
3150 static NSString *Error_;
3151 static NSString *Warning_;
3153 class CydiaLogCleaner :
3154 public pkgArchiveCleaner
3157 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3162 /* Database Implementation {{{ */
3163 @implementation Database
3165 + (Database *) sharedInstance {
3166 static _H<Database> instance;
3167 if (instance == nil)
3168 instance = [[[Database alloc] init] autorelease];
3176 - (void) releasePackages {
3177 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3178 CFArrayRemoveAllValues(packages_);
3182 // XXX: actually implement this thing
3184 [self releasePackages];
3185 apr_pool_destroy(pool_);
3186 NSRecycleZone(zone_);
3190 - (void) _readCydia:(NSNumber *)fd {
3191 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3192 std::istream is(&ib);
3195 static Pcre finish_r("^finish:([^:]*)$");
3197 while (std::getline(is, line)) {
3198 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3200 const char *data(line.c_str());
3201 size_t size = line.size();
3202 lprintf("C:%s\n", data);
3204 if (finish_r(data, size)) {
3205 NSString *finish = finish_r[1];
3206 int index = [Finishes_ indexOfObject:finish];
3207 if (index != INT_MAX && index > Finish_)
3217 - (void) _readStatus:(NSNumber *)fd {
3218 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3219 std::istream is(&ib);
3222 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3223 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3225 while (std::getline(is, line)) {
3226 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3228 const char *data(line.c_str());
3229 size_t size(line.size());
3230 lprintf("S:%s\n", data);
3232 if (conffile_r(data, size)) {
3233 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3234 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3235 } else if (strncmp(data, "status: ", 8) == 0) {
3236 // status: <package>: {unpacked,half-configured,installed}
3237 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3238 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3239 } else if (strncmp(data, "processing: ", 12) == 0) {
3240 // processing: configure: config-test
3241 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3242 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3243 } else if (pmstatus_r(data, size)) {
3244 std::string type([pmstatus_r[1] UTF8String]);
3246 NSString *package = pmstatus_r[2];
3247 if ([package isEqualToString:@"dpkg-exec"])
3250 float percent([pmstatus_r[3] floatValue]);
3251 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3253 NSString *string = pmstatus_r[4];
3255 if (type == "pmerror") {
3256 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3257 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3258 } else if (type == "pmstatus") {
3259 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3260 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3261 } else if (type == "pmconffile")
3262 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3264 lprintf("E:unknown pmstatus\n");
3266 lprintf("E:unknown status\n");
3274 - (void) _readOutput:(NSNumber *)fd {
3275 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3276 std::istream is(&ib);
3279 while (std::getline(is, line)) {
3280 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3282 lprintf("O:%s\n", line.c_str());
3284 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3285 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3297 - (Package *) packageWithName:(NSString *)name {
3300 @synchronized (self) {
3301 if (static_cast<pkgDepCache *>(cache_) == NULL)
3303 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3304 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3308 if ((self = [super init]) != nil) {
3315 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3316 apr_pool_create(&pool_, NULL);
3318 size_t capacity(MetaFile_->active_);
3324 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3325 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3329 _assert(pipe(fds) != -1);
3332 _config->Set("APT::Keep-Fds::", cydiafd_);
3333 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3336 detachNewThreadSelector:@selector(_readCydia:)
3338 withObject:[NSNumber numberWithInt:fds[0]]
3341 _assert(pipe(fds) != -1);
3345 detachNewThreadSelector:@selector(_readStatus:)
3347 withObject:[NSNumber numberWithInt:fds[0]]
3350 _assert(pipe(fds) != -1);
3351 _assert(dup2(fds[0], 0) != -1);
3352 _assert(close(fds[0]) != -1);
3354 input_ = fdopen(fds[1], "a");
3356 _assert(pipe(fds) != -1);
3357 _assert(dup2(fds[1], 1) != -1);
3358 _assert(close(fds[1]) != -1);
3361 detachNewThreadSelector:@selector(_readOutput:)
3363 withObject:[NSNumber numberWithInt:fds[0]]
3368 - (pkgCacheFile &) cache {
3372 - (pkgDepCache::Policy *) policy {
3376 - (pkgRecords *) records {
3380 - (pkgProblemResolver *) resolver {
3384 - (pkgAcquire &) fetcher {
3388 - (pkgSourceList &) list {
3392 - (NSArray *) packages {
3393 return (NSArray *) packages_;
3396 - (NSArray *) sources {
3400 - (Source *) sourceWithKey:(NSString *)key {
3401 for (Source *source in [self sources]) {
3402 if ([[source key] isEqualToString:key])
3407 - (bool) popErrorWithTitle:(NSString *)title {
3410 while (!_error->empty()) {
3412 bool warning(!_error->PopMessage(error));
3417 size_t size(error.size());
3418 if (size == 0 || error[size - 1] != '\n')
3420 error.resize(size - 1);
3423 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3425 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3431 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3432 return [self popErrorWithTitle:title] || !success;
3435 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3436 @synchronized (self) {
3439 [self releasePackages];
3442 [sourceList_ removeAllObjects];
3462 apr_pool_clear(pool_);
3464 NSRecycleZone(zone_);
3465 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3467 int chk(creat("/tmp/cydia.chk", 0644));
3471 if (invocation != nil)
3472 [invocation invoke];
3474 NSString *title(UCLocalize("DATABASE"));
3477 OpProgress progress;
3478 while (!cache_.Open(progress, true)) { pop:
3480 bool warning(!_error->PopMessage(error));
3481 lprintf("cache_.Open():[%s]\n", error.c_str());
3483 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3484 [delegate_ repairWithSelector:@selector(configure)];
3485 else if (error == "The package lists or status file could not be parsed or opened.")
3486 [delegate_ repairWithSelector:@selector(update)];
3487 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3488 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3489 // else if (error == "Malformed Status line")
3490 // else if (error == "The list of sources could not be read.")
3492 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3502 unlink("/tmp/cydia.chk");
3504 now_ = [[NSDate date] timeIntervalSince1970];
3506 policy_ = new pkgDepCache::Policy();
3507 records_ = new pkgRecords(cache_);
3508 resolver_ = new pkgProblemResolver(cache_);
3509 fetcher_ = new pkgAcquire(&status_);
3512 list_ = new pkgSourceList();
3513 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3516 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3517 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3521 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3524 if (cache_->BrokenCount() != 0) {
3525 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3528 if (cache_->BrokenCount() != 0) {
3529 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3533 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3537 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3538 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3539 [sourceList_ addObject:object];
3541 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3542 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3543 // XXX: this could be more intelligent
3544 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3545 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3547 sourceMap_[cached->ID] = object;
3552 /*std::vector<Package *> packages;
3553 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3558 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3559 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3560 //packages.push_back(package);
3561 CFArrayAppendValue(packages_, CFRetain(package));
3565 /*if (packages.empty())
3566 packages_ = [[NSArray alloc] init];
3568 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3571 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3572 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3573 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3581 /*if (!packages.empty())
3582 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3583 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3585 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3587 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3589 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3593 size_t count(CFArrayGetCount(packages_));
3594 MetaFile_->active_ = count;
3596 for (size_t index(0); index != count; ++index)
3597 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3604 @synchronized (self) {
3606 resolver_ = new pkgProblemResolver(cache_);
3608 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3609 if (!cache_[iterator].Keep())
3610 cache_->MarkKeep(iterator, false);
3611 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3612 cache_->SetReInstall(iterator, false);
3615 - (void) configure {
3616 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3618 system([dpkg UTF8String]);
3623 // XXX: I don't remember this condition
3628 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3630 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3632 if ([self popErrorWithTitle:title])
3636 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3638 CydiaLogCleaner cleaner;
3639 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3646 fetcher_->Shutdown();
3648 pkgRecords records(cache_);
3650 lock_ = new FileFd();
3651 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3653 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3655 if ([self popErrorWithTitle:title])
3659 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3662 manager_ = (_system->CreatePM(cache_));
3663 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3670 bool substrate(RestartSubstrate_);
3671 RestartSubstrate_ = false;
3673 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3675 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3677 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3679 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3680 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3683 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3685 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3687 [self popErrorWithTitle:title];
3691 bool failed = false;
3692 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3693 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3695 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3701 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3709 RestartSubstrate_ = true;
3712 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3714 if (_error->PendingError()) {
3719 if (result == pkgPackageManager::Failed) {
3724 if (result != pkgPackageManager::Completed) {
3729 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3731 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3733 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3734 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3737 if (![before isEqualToArray:after])
3742 NSString *title(UCLocalize("UPGRADE"));
3743 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3749 [self updateWithStatus:status_];
3752 - (void) updateWithStatus:(Status &)status {
3753 NSString *title(UCLocalize("REFRESHING_DATA"));
3756 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3760 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3761 if ([self popErrorWithTitle:title])
3764 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3766 bool success(ListUpdate(status, list, PulseInterval_));
3767 if (status.WasCancelled())
3770 [self popErrorWithTitle:title forOperation:success];
3771 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3775 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3778 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3779 delegate_ = delegate;
3782 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3783 progress_ = delegate;
3784 status_.setDelegate(delegate);
3787 - (NSObject<ProgressDelegate> *) progressDelegate {
3791 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3792 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3793 return i == sourceMap_.end() ? nil : i->second;
3796 - (NSString *) mappedSectionForPointer:(const char *)section {
3797 _H<NSString> *mapped;
3799 _profile(Database$mappedSectionForPointer$Cache)
3800 mapped = §ions_[section];
3803 if (*mapped == NULL) {
3804 size_t length(strlen(section));
3805 char spaced[length + 1];
3807 _profile(Database$mappedSectionForPointer$Replace)
3808 for (size_t index(0); index != length; ++index)
3809 spaced[index] = section[index] == '_' ? ' ' : section[index];
3810 spaced[length] = '\0';
3815 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3816 string = [NSString stringWithUTF8String:spaced];
3819 _profile(Database$mappedSectionForPointer$Map)
3820 string = [SectionMap_ objectForKey:string] ?: string;
3830 static _H<NSMutableSet> Diversions_;
3832 @interface Diversion : NSObject {
3835 _H<NSString> format_;
3840 @implementation Diversion
3842 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3843 if ((self = [super init]) != nil) {
3844 pattern_ = [from UTF8String];
3850 - (NSString *) divert:(NSString *)url {
3851 return !pattern_(url) ? nil : pattern_->*format_;
3854 + (NSURL *) divertURL:(NSURL *)url {
3856 NSString *href([url absoluteString]);
3858 for (Diversion *diversion in (id) Diversions_)
3859 if (NSString *diverted = [diversion divert:href]) {
3861 NSLog(@"div: %@", diverted);
3863 url = [NSURL URLWithString:diverted];
3870 - (NSString *) key {
3874 - (NSUInteger) hash {
3878 - (BOOL) isEqual:(Diversion *)object {
3879 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3884 @interface CydiaObject : NSObject {
3885 _H<IndirectDelegate> indirect_;
3886 _transient id delegate_;
3889 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3893 @interface CydiaWebViewController : CyteWebViewController {
3894 _H<CydiaObject> cydia_;
3897 + (void) addDiversion:(Diversion *)diversion;
3901 /* Web Scripting {{{ */
3902 @implementation CydiaObject
3904 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3905 if ((self = [super init]) != nil) {
3906 indirect_ = indirect;
3910 - (void) setDelegate:(id)delegate {
3911 delegate_ = delegate;
3914 + (NSArray *) _attributeKeys {
3915 return [NSArray arrayWithObjects:
3932 - (NSArray *) attributeKeys {
3933 return [[self class] _attributeKeys];
3936 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3937 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3940 - (NSString *) version {
3944 - (NSString *) device {
3945 return [[UIDevice currentDevice] uniqueIdentifier];
3948 - (NSString *) firmware {
3949 return [[UIDevice currentDevice] systemVersion];
3952 - (NSString *) hostname {
3953 return [[UIDevice currentDevice] name];
3956 - (NSString *) idiom {
3957 return (id) Idiom_ ?: [NSNull null];
3960 - (NSString *) plmn {
3961 return (id) PLMN_ ?: [NSNull null];
3964 - (NSString *) bbsnum {
3965 return (id) BBSNum_ ?: [NSNull null];
3968 - (NSString *) ecid {
3969 return (id) ChipID_ ?: [NSNull null];
3972 - (NSString *) serial {
3973 return SerialNumber_;
3976 - (NSString *) role {
3977 return (id) Role_ ?: [NSNull null];
3980 - (NSString *) model {
3981 return [NSString stringWithUTF8String:Machine_];
3984 - (NSString *) token {
3985 return (id) Token_ ?: [NSNull null];
3988 + (NSString *) webScriptNameForSelector:(SEL)selector {
3990 else if (selector == @selector(addBridgedHost:))
3991 return @"addBridgedHost";
3992 else if (selector == @selector(addInsecureHost:))
3993 return @"addInsecureHost";
3994 else if (selector == @selector(addInternalRedirect::))
3995 return @"addInternalRedirect";
3996 else if (selector == @selector(addPipelinedHost:scheme:))
3997 return @"addPipelinedHost";
3998 else if (selector == @selector(addSource:::))
3999 return @"addSource";
4000 else if (selector == @selector(addTokenHost:))
4001 return @"addTokenHost";
4002 else if (selector == @selector(addTrivialSource:))
4003 return @"addTrivialSource";
4004 else if (selector == @selector(close))
4006 else if (selector == @selector(du:))
4008 else if (selector == @selector(stringWithFormat:arguments:))
4010 else if (selector == @selector(getAllSources))
4011 return @"getAllSourcs";
4012 else if (selector == @selector(getKernelNumber:))
4013 return @"getKernelNumber";
4014 else if (selector == @selector(getKernelString:))
4015 return @"getKernelString";
4016 else if (selector == @selector(getInstalledPackages))
4017 return @"getInstalledPackages";
4018 else if (selector == @selector(getIORegistryEntry::))
4019 return @"getIORegistryEntry";
4020 else if (selector == @selector(getLocaleIdentifier))
4021 return @"getLocaleIdentifier";
4022 else if (selector == @selector(getPreferredLanguages))
4023 return @"getPreferredLanguages";
4024 else if (selector == @selector(getPackageById:))
4025 return @"getPackageById";
4026 else if (selector == @selector(getMetadataKeys))
4027 return @"getMetadataKeys";
4028 else if (selector == @selector(getMetadataValue:))
4029 return @"getMetadataValue";
4030 else if (selector == @selector(getSessionValue:))
4031 return @"getSessionValue";
4032 else if (selector == @selector(installPackages:))
4033 return @"installPackages";
4034 else if (selector == @selector(localizedStringForKey:value:table:))
4036 else if (selector == @selector(popViewController:))
4037 return @"popViewController";
4038 else if (selector == @selector(refreshSources))
4039 return @"refreshSources";
4040 else if (selector == @selector(removeButton))
4041 return @"removeButton";
4042 else if (selector == @selector(saveConfig))
4043 return @"saveConfig";
4044 else if (selector == @selector(setCydiaSource:))
4045 return @"setCydiaSource";
4046 else if (selector == @selector(setMetadataValue::))
4047 return @"setMetadataValue";
4048 else if (selector == @selector(setSessionValue::))
4049 return @"setSessionValue";
4050 else if (selector == @selector(substitutePackageNames:))
4051 return @"substitutePackageNames";
4052 else if (selector == @selector(scrollToBottom:))
4053 return @"scrollToBottom";
4054 else if (selector == @selector(setAllowsNavigationAction:))
4055 return @"setAllowsNavigationAction";
4056 else if (selector == @selector(setBadgeValue:))
4057 return @"setBadgeValue";
4058 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4059 return @"setButtonImage";
4060 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4061 return @"setButtonTitle";
4062 else if (selector == @selector(setHidesBackButton:))
4063 return @"setHidesBackButton";
4064 else if (selector == @selector(setHidesNavigationBar:))
4065 return @"setHidesNavigationBar";
4066 else if (selector == @selector(setNavigationBarStyle:))
4067 return @"setNavigationBarStyle";
4068 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4069 return @"setNavigationBarTintColor";
4070 else if (selector == @selector(setPasteboardString:))
4071 return @"setPasteboardString";
4072 else if (selector == @selector(setPasteboardURL:))
4073 return @"setPasteboardURL";
4074 else if (selector == @selector(setToken:))
4076 else if (selector == @selector(setViewportWidth:))
4077 return @"setViewportWidth";
4078 else if (selector == @selector(statfs:))
4080 else if (selector == @selector(supports:))
4082 else if (selector == @selector(unload))
4088 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4089 return [self webScriptNameForSelector:selector] == nil;
4092 - (BOOL) supports:(NSString *)feature {
4093 return [feature isEqualToString:@"window.open"];
4097 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4100 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4101 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4104 - (NSNumber *) getKernelNumber:(NSString *)name {
4105 const char *string([name UTF8String]);
4108 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4109 return (id) [NSNull null];
4111 if (size != sizeof(int))
4112 return (id) [NSNull null];
4115 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4116 return (id) [NSNull null];
4118 return [NSNumber numberWithInt:value];
4121 - (NSString *) getKernelString:(NSString *)name {
4122 const char *string([name UTF8String]);
4125 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4126 return (id) [NSNull null];
4128 char value[size + 1];
4129 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4130 return (id) [NSNull null];
4132 // XXX: just in case you request something ludicrous
4135 return [NSString stringWithCString:value];
4138 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4139 NSObject *value(CYIOGetValue([path UTF8String], entry));
4142 if ([value isKindOfClass:[NSData class]])
4143 value = CYHex((NSData *) value);
4148 - (void) _setCydiaSource:(NSString *)source {
4149 @synchronized (HostConfig_) {
4150 CydiaSource_ = source;
4151 [Metadata_ setObject:source forKey:@"CydiaSource"];
4157 - (void) setCydiaSource:(NSString *)source {
4158 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4161 - (NSString *) cydiaSource {
4162 @synchronized (HostConfig_) {
4163 return (id) CydiaSource_ ?: [NSNull null];
4167 - (NSArray *) getMetadataKeys {
4168 @synchronized (Values_) {
4169 return [Values_ allKeys];
4172 - (id) getMetadataValue:(NSString *)key {
4173 @synchronized (Values_) {
4174 return [Values_ objectForKey:key];
4177 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4178 @synchronized (Values_) {
4179 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4180 [Values_ removeObjectForKey:key];
4182 [Values_ setObject:value forKey:key];
4184 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4187 - (id) getSessionValue:(NSString *)key {
4188 @synchronized (SessionData_) {
4189 return [SessionData_ objectForKey:key];
4192 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4193 @synchronized (SessionData_) {
4194 if (value == (id) [WebUndefined undefined])
4195 [SessionData_ removeObjectForKey:key];
4197 [SessionData_ setObject:value forKey:key];
4200 - (void) addBridgedHost:(NSString *)host {
4201 @synchronized (HostConfig_) {
4202 [BridgedHosts_ addObject:host];
4205 - (void) addInsecureHost:(NSString *)host {
4206 @synchronized (HostConfig_) {
4207 [InsecureHosts_ addObject:host];
4210 - (void) addTokenHost:(NSString *)host {
4211 @synchronized (HostConfig_) {
4212 [TokenHosts_ addObject:host];
4215 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4216 @synchronized (HostConfig_) {
4217 if (scheme != (id) [WebUndefined undefined])
4218 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4220 [PipelinedHosts_ addObject:host];
4223 - (void) popViewController:(NSNumber *)value {
4224 if (value == (id) [WebUndefined undefined])
4225 value = [NSNumber numberWithBool:YES];
4226 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4229 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4230 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4232 for (NSString *section in sections)
4233 [array addObject:section];
4235 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4238 distribution, @"Distribution",
4240 nil] waitUntilDone:NO];
4243 - (void) addTrivialSource:(NSString *)href {
4244 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4247 - (void) refreshSources {
4248 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4251 - (void) saveConfig {
4252 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4255 - (NSArray *) getAllSources {
4256 return [[Database sharedInstance] sources];
4259 - (NSArray *) getInstalledPackages {
4260 Database *database([Database sharedInstance]);
4261 @synchronized (database) {
4262 NSArray *packages([database packages]);
4263 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4264 for (Package *package in packages)
4265 if (![package uninstalled])
4266 [installed addObject:package];
4270 - (Package *) getPackageById:(NSString *)id {
4271 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4275 return (Package *) [NSNull null];
4278 - (NSString *) getLocaleIdentifier {
4279 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4282 - (NSArray *) getPreferredLanguages {
4286 - (NSArray *) statfs:(NSString *)path {
4289 if (path == nil || statfs([path UTF8String], &stat) == -1)
4292 return [NSArray arrayWithObjects:
4293 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4294 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4295 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4299 - (NSNumber *) du:(NSString *)path {
4300 NSNumber *value(nil);
4303 _assert(pipe(fds) != -1);
4305 pid_t pid(ExecFork());
4307 _assert(dup2(fds[1], 1) != -1);
4308 _assert(close(fds[0]) != -1);
4309 _assert(close(fds[1]) != -1);
4310 /* XXX: this should probably not use du */
4311 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4316 _assert(close(fds[1]) != -1);
4318 if (FILE *du = fdopen(fds[0], "r")) {
4320 while (fgets(line, sizeof(line), du) != NULL) {
4321 size_t length(strlen(line));
4322 while (length != 0 && line[length - 1] == '\n')
4323 line[--length] = '\0';
4324 if (char *tab = strchr(line, '\t')) {
4326 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4331 } else _assert(close(fds[0]));
4335 if (waitpid(pid, &status, 0) == -1)
4338 else _assert(false);
4344 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4347 - (void) installPackages:(NSArray *)packages {
4348 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4351 - (NSString *) substitutePackageNames:(NSString *)message {
4352 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4353 for (size_t i(0), e([words count]); i != e; ++i) {
4354 NSString *word([words objectAtIndex:i]);
4355 if (Package *package = [[Database sharedInstance] packageWithName:word])
4356 [words replaceObjectAtIndex:i withObject:[package name]];
4359 return [words componentsJoinedByString:@" "];
4362 - (void) removeButton {
4363 [indirect_ removeButton];
4366 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4367 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4370 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4371 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4374 - (void) setBadgeValue:(id)value {
4375 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4378 - (void) setAllowsNavigationAction:(NSString *)value {
4379 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4382 - (void) setHidesBackButton:(NSString *)value {
4383 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4386 - (void) setHidesNavigationBar:(NSString *)value {
4387 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4390 - (void) setNavigationBarStyle:(NSString *)value {
4391 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4394 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4395 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4396 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4397 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4400 - (void) setPasteboardString:(NSString *)value {
4401 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4404 - (void) setPasteboardURL:(NSString *)value {
4405 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4408 - (void) _setToken:(NSString *)token {
4412 [Metadata_ removeObjectForKey:@"Token"];
4414 [Metadata_ setObject:Token_ forKey:@"Token"];
4419 - (void) setToken:(NSString *)token {
4420 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4423 - (void) scrollToBottom:(NSNumber *)animated {
4424 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4427 - (void) setViewportWidth:(float)width {
4428 [indirect_ setViewportWidthOnMainThread:width];
4431 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4432 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4433 unsigned count([arguments count]);
4435 for (unsigned i(0); i != count; ++i)
4436 values[i] = [arguments objectAtIndex:i];
4437 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4440 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4441 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4443 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4445 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4451 @interface NSURL (CydiaSecure)
4454 @implementation NSURL (CydiaSecure)
4456 - (bool) isCydiaSecure {
4457 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4460 @synchronized (HostConfig_) {
4461 if ([InsecureHosts_ containsObject:[self host]])
4470 /* Cydia Browser Controller {{{ */
4471 @implementation CydiaWebViewController
4473 - (NSURL *) navigationURL {
4474 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4477 + (void) initialize {
4478 Diversions_ = [NSMutableSet setWithCapacity:0];
4481 + (void) addDiversion:(Diversion *)diversion {
4482 [Diversions_ addObject:diversion];
4485 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4486 [super webView:view didClearWindowObject:window forFrame:frame];
4488 WebDataSource *source([frame dataSource]);
4489 NSURLResponse *response([source response]);
4490 NSURL *url([response URL]);
4491 NSString *scheme([[url scheme] lowercaseString]);
4493 bool bridged(false);
4495 @synchronized (HostConfig_) {
4496 if ([scheme isEqualToString:@"file"])
4498 else if ([scheme isEqualToString:@"https"])
4499 if ([BridgedHosts_ containsObject:[url host]])
4504 [window setValue:cydia_ forKey:@"cydia"];
4507 - (void) _setupMail:(MFMailComposeViewController *)controller {
4508 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4510 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4511 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4514 - (NSURL *) URLWithURL:(NSURL *)url {
4515 return [Diversion divertURL:url];
4518 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4519 NSURL *url([request URL]);
4520 NSString *host([url host]);
4522 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4524 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4525 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4526 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4527 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4530 @synchronized (HostConfig_) {
4531 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4534 if ([url isCydiaSecure] && token) {
4535 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4536 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4542 - (void) setDelegate:(id)delegate {
4543 [super setDelegate:delegate];
4544 [cydia_ setDelegate:delegate];
4547 - (NSString *) applicationNameForUserAgent {
4548 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4551 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4553 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4554 if (Product_ != nil)
4555 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4561 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4562 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4570 @interface NSObject (CydiaScript)
4571 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4574 @implementation NSObject (CydiaScript)
4576 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4582 @implementation NSArray (CydiaScript)
4584 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4585 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4586 for (size_t i(0), e([self count]); i != e; ++i)
4587 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4593 @implementation NSDictionary (CydiaScript)
4595 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4596 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4598 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4605 /* Confirmation Controller {{{ */
4606 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4607 if (!iterator.end())
4608 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4609 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4611 pkgCache::PkgIterator package(dep.TargetPkg());
4614 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4621 @protocol ConfirmationControllerDelegate
4622 - (void) cancelAndClear:(bool)clear;
4623 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4627 @interface ConfirmationController : CydiaWebViewController {
4628 _transient Database *database_;
4630 _H<UIAlertView> essential_;
4632 _H<NSDictionary> changes_;
4633 _H<NSMutableArray> issues_;
4634 _H<NSDictionary> sizes_;
4639 - (id) initWithDatabase:(Database *)database;
4643 @implementation ConfirmationController
4647 RestartSubstrate_ = true;
4648 [delegate_ confirmWithNavigationController:[self navigationController]];
4651 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4652 NSString *context([alert context]);
4654 if ([context isEqualToString:@"remove"]) {
4655 if (button == [alert cancelButtonIndex])
4656 [self dismissModalViewControllerAnimated:YES];
4657 else if (button == [alert firstOtherButtonIndex]) {
4661 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4662 } else if ([context isEqualToString:@"unable"]) {
4663 [self dismissModalViewControllerAnimated:YES];
4664 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4666 [super alertView:alert clickedButtonAtIndex:button];
4670 - (void) _doContinue {
4671 [delegate_ cancelAndClear:NO];
4672 [self dismissModalViewControllerAnimated:YES];
4675 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4676 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4680 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4681 [super webView:view didClearWindowObject:window forFrame:frame];
4683 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4684 (id) changes_, @"changes",
4685 (id) issues_, @"issues",
4686 (id) sizes_, @"sizes",
4688 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4691 - (id) initWithDatabase:(Database *)database {
4692 if ((self = [super init]) != nil) {
4693 database_ = database;
4695 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4696 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4697 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4698 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4699 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4703 pkgCacheFile &cache([database_ cache]);
4704 NSArray *packages([database_ packages]);
4705 pkgDepCache::Policy *policy([database_ policy]);
4707 issues_ = [NSMutableArray arrayWithCapacity:4];
4709 for (Package *package in packages) {
4710 pkgCache::PkgIterator iterator([package iterator]);
4711 NSString *name([package id]);
4713 if ([package broken]) {
4714 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4716 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4718 reasons, @"reasons",
4721 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4725 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4726 pkgCache::DepIterator start;
4727 pkgCache::DepIterator end;
4728 dep.GlobOr(start, end); // ++dep
4730 if (!cache->IsImportantDep(end))
4732 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4735 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4737 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4738 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4739 clauses, @"clauses",
4743 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4745 pkgCache::PkgIterator target(start.TargetPkg());
4746 if (target->ProvidesList != 0)
4747 reason = @"missing";
4749 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4751 reason = @"installed";
4752 installed = [NSString stringWithUTF8String:ver.VerStr()];
4753 } else if (!cache[target].CandidateVerIter(cache).end())
4754 reason = @"uninstalled";
4755 else if (target->ProvidesList == 0)
4756 reason = @"uninstallable";
4758 reason = @"virtual";
4761 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4762 [NSString stringWithUTF8String:start.CompType()], @"operator",
4763 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4766 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4767 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4768 version, @"version",
4770 installed, @"installed",
4773 // yes, seriously. (wtf?)
4781 pkgDepCache::StateCache &state(cache[iterator]);
4783 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4785 if (state.NewInstall())
4786 [installs addObject:name];
4787 // XXX: else if (state.Install())
4788 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4789 [reinstalls addObject:name];
4790 // XXX: move before previous if
4791 else if (state.Upgrade())
4792 [upgrades addObject:name];
4793 else if (state.Downgrade())
4794 [downgrades addObject:name];
4795 else if (!state.Delete())
4796 // XXX: _assert(state.Keep());
4798 else if (special_r(name))
4799 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4800 [NSNull null], @"package",
4801 [NSArray arrayWithObjects:
4802 [NSDictionary dictionaryWithObjectsAndKeys:
4803 @"Conflicts", @"relationship",
4804 [NSArray arrayWithObjects:
4805 [NSDictionary dictionaryWithObjectsAndKeys:
4807 [NSNull null], @"version",
4808 @"installed", @"reason",
4815 if ([package essential])
4817 [removes addObject:name];
4820 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4821 substrate_ |= DepSubstrate(iterator.CurrentVer());
4826 else if (Advanced_) {
4827 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4829 essential_ = [[[UIAlertView alloc]
4830 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4831 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4833 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4835 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4839 [essential_ setContext:@"remove"];
4841 essential_ = [[[UIAlertView alloc]
4842 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4843 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4845 cancelButtonTitle:UCLocalize("OKAY")
4846 otherButtonTitles:nil
4849 [essential_ setContext:@"unable"];
4852 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4853 installs, @"installs",
4854 reinstalls, @"reinstalls",
4855 upgrades, @"upgrades",
4856 downgrades, @"downgrades",
4857 removes, @"removes",
4860 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4861 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4862 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4865 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4869 - (UIBarButtonItem *) leftButton {
4870 return [[[UIBarButtonItem alloc]
4871 initWithTitle:UCLocalize("CANCEL")
4872 style:UIBarButtonItemStylePlain
4874 action:@selector(cancelButtonClicked)
4879 - (void) applyRightButton {
4880 if ([issues_ count] == 0 && ![self isLoading])
4881 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4882 initWithTitle:UCLocalize("CONFIRM")
4883 style:UIBarButtonItemStyleDone
4885 action:@selector(confirmButtonClicked)
4888 [[self navigationItem] setRightBarButtonItem:nil];
4892 - (void) cancelButtonClicked {
4893 [self dismissModalViewControllerAnimated:YES];
4894 [delegate_ cancelAndClear:YES];
4898 - (void) confirmButtonClicked {
4899 if (essential_ != nil)
4909 /* Progress Data {{{ */
4910 @interface CydiaProgressData : NSObject {
4911 _transient id delegate_;
4920 _H<NSMutableArray> events_;
4921 _H<NSString> title_;
4923 _H<NSString> status_;
4924 _H<NSString> finish_;
4929 @implementation CydiaProgressData
4931 + (NSArray *) _attributeKeys {
4932 return [NSArray arrayWithObjects:
4944 - (NSArray *) attributeKeys {
4945 return [[self class] _attributeKeys];
4948 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4949 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4953 if ((self = [super init]) != nil) {
4954 events_ = [NSMutableArray arrayWithCapacity:32];
4958 - (void) setDelegate:(id)delegate {
4959 delegate_ = delegate;
4962 - (void) setPercent:(float)value {
4966 - (NSNumber *) percent {
4967 return [NSNumber numberWithFloat:percent_];
4970 - (void) setCurrent:(float)value {
4974 - (NSNumber *) current {
4975 return [NSNumber numberWithFloat:current_];
4978 - (void) setTotal:(float)value {
4982 - (NSNumber *) total {
4983 return [NSNumber numberWithFloat:total_];
4986 - (void) setSpeed:(float)value {
4990 - (NSNumber *) speed {
4991 return [NSNumber numberWithFloat:speed_];
4994 - (NSArray *) events {
4998 - (void) removeAllEvents {
4999 [events_ removeAllObjects];
5002 - (void) addEvent:(CydiaProgressEvent *)event {
5003 [events_ addObject:event];
5006 - (void) setTitle:(NSString *)text {
5010 - (NSString *) title {
5014 - (void) setFinish:(NSString *)text {
5018 - (NSString *) finish {
5019 return (id) finish_ ?: [NSNull null];
5022 - (void) setRunning:(bool)running {
5026 - (NSNumber *) running {
5027 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5032 /* Progress Controller {{{ */
5033 @interface ProgressController : CydiaWebViewController <
5036 _transient Database *database_;
5037 _H<CydiaProgressData, 1> progress_;
5041 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5043 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5045 - (void) setTitle:(NSString *)title;
5046 - (void) setCancellable:(bool)cancellable;
5050 @implementation ProgressController
5053 [database_ setProgressDelegate:nil];
5057 - (UIBarButtonItem *) leftButton {
5058 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5059 initWithTitle:UCLocalize("CANCEL")
5060 style:UIBarButtonItemStylePlain
5062 action:@selector(cancel)
5063 ] autorelease] : nil;
5066 - (void) updateCancel {
5067 [super applyLeftButton];
5070 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5071 if ((self = [super init]) != nil) {
5072 database_ = database;
5073 delegate_ = delegate;
5075 [database_ setProgressDelegate:self];
5077 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5078 [progress_ setDelegate:self];
5080 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5082 [scroller_ setBackgroundColor:[UIColor blackColor]];
5084 [[self navigationItem] setHidesBackButton:YES];
5086 [self updateCancel];
5090 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5091 [super webView:view didClearWindowObject:window forFrame:frame];
5092 [window setValue:progress_ forKey:@"cydiaProgress"];
5095 - (void) updateProgress {
5096 [self dispatchEvent:@"CydiaProgressUpdate"];
5099 - (void) viewWillAppear:(BOOL)animated {
5100 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5101 [super viewWillAppear:animated];
5105 UpdateExternalStatus(0);
5108 [delegate_ saveState];
5112 [delegate_ returnToCydia];
5116 [delegate_ terminateWithSuccess];
5117 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5118 [delegate_ suspendWithAnimation:YES];
5120 [delegate_ suspend];*/
5132 system("/usr/bin/sbreload");
5138 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5139 SBReboot(SBSSpringBoardServerPort());
5141 reboot2(RB_AUTOBOOT);
5148 - (void) setTitle:(NSString *)title {
5149 [progress_ setTitle:title];
5150 [self updateProgress];
5153 - (UIBarButtonItem *) rightButton {
5154 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5155 initWithTitle:UCLocalize("CLOSE")
5156 style:UIBarButtonItemStylePlain
5158 action:@selector(close)
5162 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5163 UpdateExternalStatus(1);
5165 [progress_ setRunning:true];
5166 [self setTitle:title];
5167 // implicit updateProgress
5169 SHA1SumValue notifyconf; {
5171 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5174 MMap mmap(file, MMap::ReadOnly);
5176 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5177 notifyconf = sha1.Result();
5181 SHA1SumValue springlist; {
5183 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5186 MMap mmap(file, MMap::ReadOnly);
5188 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5189 springlist = sha1.Result();
5193 if (invocation != nil) {
5194 [invocation yieldToSelector:@selector(invoke)];
5195 [self setTitle:@"COMPLETE"];
5200 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5203 MMap mmap(file, MMap::ReadOnly);
5205 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5206 if (!(notifyconf == sha1.Result()))
5213 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5216 MMap mmap(file, MMap::ReadOnly);
5218 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5219 if (!(springlist == sha1.Result()))
5225 if (RestartSubstrate_)
5229 RestartSubstrate_ = false;
5232 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5233 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5234 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5235 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5236 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5240 system("su -c /usr/bin/uicache mobile");
5243 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5245 [progress_ setRunning:false];
5246 [self updateProgress];
5248 [self applyRightButton];
5251 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5252 [progress_ addEvent:event];
5253 [self updateProgress];
5256 - (bool) isProgressCancelled {
5257 return cancel_ == 2;
5262 [self updateCancel];
5265 - (void) setCancellable:(bool)cancellable {
5266 unsigned cancel(cancel_);
5270 else if (cancel_ == 0)
5273 if (cancel != cancel_)
5274 [self updateCancel];
5277 - (void) setProgressCancellable:(NSNumber *)cancellable {
5278 [self setCancellable:[cancellable boolValue]];
5281 - (void) setProgressPercent:(NSNumber *)percent {
5282 [progress_ setPercent:[percent floatValue]];
5283 [self updateProgress];
5286 - (void) setProgressStatus:(NSDictionary *)status {
5287 if (status == nil) {
5288 [progress_ setCurrent:0];
5289 [progress_ setTotal:0];
5290 [progress_ setSpeed:0];
5292 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5294 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5295 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5296 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5299 [self updateProgress];
5305 /* Package Cell {{{ */
5306 @interface PackageCell : CyteTableViewCell <
5307 CyteTableViewCellDelegate
5311 _H<NSString> description_;
5313 _H<NSString> source_;
5315 _H<UIImage> placard_;
5319 - (PackageCell *) init;
5320 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5322 - (void) drawContentRect:(CGRect)rect;
5326 @implementation PackageCell
5328 - (PackageCell *) init {
5329 CGRect frame(CGRectMake(0, 0, 320, 74));
5330 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5331 UIView *content([self contentView]);
5332 CGRect bounds([content bounds]);
5334 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5335 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5336 [content addSubview:content_];
5338 [content_ setDelegate:self];
5339 [content_ setOpaque:YES];
5343 - (NSString *) accessibilityLabel {
5344 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5347 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5348 summarized_ = summary;
5359 Source *source = [package source];
5361 icon_ = [package icon];
5363 if (NSString *name = [package name])
5364 name_ = [NSString stringWithString:name];
5366 NSString *description(nil);
5368 if (description == nil && IsWildcat_)
5369 description = [package longDescription];
5370 if (description == nil)
5371 description = [package shortDescription];
5373 if (description != nil)
5374 description_ = [NSString stringWithString:description];
5376 commercial_ = [package isCommercial];
5378 NSString *label = nil;
5379 bool trusted = false;
5381 if (source != nil) {
5382 label = [source label];
5383 trusted = [source trusted];
5384 } else if ([[package id] isEqualToString:@"firmware"])
5385 label = UCLocalize("APPLE");
5387 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5389 NSString *from(label);
5391 NSString *section = [package simpleSection];
5392 if (section != nil && ![section isEqualToString:label]) {
5393 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5394 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5397 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5399 if (NSString *purpose = [package primaryPurpose])
5400 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5405 if (NSString *mode = [package mode]) {
5406 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5407 color = RemovingColor_;
5408 //placard = @"removing";
5410 color = InstallingColor_;
5411 //placard = @"installing";
5414 // XXX: the removing/installing placards are not @2x
5417 color = [UIColor whiteColor];
5419 if ([package installed] != nil)
5420 placard = @"installed";
5425 [content_ setBackgroundColor:color];
5428 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5430 [self setNeedsDisplay];
5431 [content_ setNeedsDisplay];
5434 - (void) drawSummaryContentRect:(CGRect)rect {
5435 bool highlighted(highlighted_);
5436 float width([self bounds].size.width);
5440 rect.size = [(UIImage *) icon_ size];
5442 rect.size.width /= 4;
5443 rect.size.height /= 4;
5445 rect.origin.x = 14 - rect.size.width / 4;
5446 rect.origin.y = 14 - rect.size.height / 4;
5448 [icon_ drawInRect:rect];
5451 if (badge_ != nil) {
5453 rect.size = [(UIImage *) badge_ size];
5455 rect.size.width /= 4;
5456 rect.size.height /= 4;
5458 rect.origin.x = 20 - rect.size.width / 4;
5459 rect.origin.y = 20 - rect.size.height / 4;
5461 [badge_ drawInRect:rect];
5468 UISetColor(commercial_ ? Purple_ : Black_);
5469 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5471 if (placard_ != nil)
5472 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5475 - (void) drawNormalContentRect:(CGRect)rect {
5476 bool highlighted(highlighted_);
5477 float width([self bounds].size.width);
5481 rect.size = [(UIImage *) icon_ size];
5483 rect.size.width /= 2;
5484 rect.size.height /= 2;
5486 rect.origin.x = 25 - rect.size.width / 2;
5487 rect.origin.y = 25 - rect.size.height / 2;
5489 [icon_ drawInRect:rect];
5492 if (badge_ != nil) {
5494 rect.size = [(UIImage *) badge_ size];
5496 rect.size.width /= 2;
5497 rect.size.height /= 2;
5499 rect.origin.x = 36 - rect.size.width / 2;
5500 rect.origin.y = 36 - rect.size.height / 2;
5502 [badge_ drawInRect:rect];
5509 UISetColor(commercial_ ? Purple_ : Black_);
5510 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5511 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5514 UISetColor(commercial_ ? Purplish_ : Gray_);
5515 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5517 if (placard_ != nil)
5518 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5521 - (void) drawContentRect:(CGRect)rect {
5523 [self drawSummaryContentRect:rect];
5525 [self drawNormalContentRect:rect];
5530 /* Section Cell {{{ */
5531 @interface SectionCell : CyteTableViewCell <
5532 CyteTableViewCellDelegate
5534 _H<NSString> basic_;
5535 _H<NSString> section_;
5537 _H<NSString> count_;
5539 _H<UISwitch> switch_;
5543 - (void) setSection:(Section *)section editing:(BOOL)editing;
5547 @implementation SectionCell
5549 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5550 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5551 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5552 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5553 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5555 UIView *content([self contentView]);
5556 CGRect bounds([content bounds]);
5558 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5559 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5560 [content addSubview:content_];
5561 [content_ setBackgroundColor:[UIColor whiteColor]];
5563 [content_ setDelegate:self];
5567 - (void) onSwitch:(id)sender {
5568 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5569 if (metadata == nil) {
5570 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5571 [Sections_ setObject:metadata forKey:basic_];
5574 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5578 - (void) setSection:(Section *)section editing:(BOOL)editing {
5579 if (editing != editing_) {
5581 [switch_ removeFromSuperview];
5583 [self addSubview:switch_];
5592 if (section == nil) {
5593 name_ = UCLocalize("ALL_PACKAGES");
5596 basic_ = [section name];
5597 section_ = [section localized];
5599 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5600 count_ = [NSString stringWithFormat:@"%d", [section count]];
5603 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5606 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5607 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5609 [content_ setNeedsDisplay];
5612 - (void) setFrame:(CGRect)frame {
5613 [super setFrame:frame];
5615 CGRect rect([switch_ frame]);
5616 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5619 - (NSString *) accessibilityLabel {
5623 - (void) drawContentRect:(CGRect)rect {
5624 bool highlighted(highlighted_ && !editing_);
5626 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5631 float width(rect.size.width);
5637 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5639 CGSize size = [count_ sizeWithFont:Font14_];
5643 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5649 /* File Table {{{ */
5650 @interface FileTable : CyteViewController <
5651 UITableViewDataSource,
5654 _transient Database *database_;
5655 _H<Package> package_;
5657 _H<NSMutableArray> files_;
5658 _H<UITableView, 2> list_;
5661 - (id) initWithDatabase:(Database *)database;
5662 - (void) setPackage:(Package *)package;
5666 @implementation FileTable
5668 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5669 return files_ == nil ? 0 : [files_ count];
5672 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5676 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5677 static NSString *reuseIdentifier = @"Cell";
5679 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5681 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5682 [cell setFont:[UIFont systemFontOfSize:16]];
5684 [cell setText:[files_ objectAtIndex:indexPath.row]];
5685 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5690 - (NSURL *) navigationURL {
5691 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5695 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5697 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5698 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5699 [list_ setRowHeight:24.0f];
5700 [(UITableView *) list_ setDataSource:self];
5701 [list_ setDelegate:self];
5702 [[self view] addSubview:list_];
5705 - (void) viewDidLoad {
5706 [super viewDidLoad];
5708 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5711 - (void) releaseSubviews {
5714 [super releaseSubviews];
5717 - (id) initWithDatabase:(Database *)database {
5718 if ((self = [super init]) != nil) {
5719 database_ = database;
5721 files_ = [NSMutableArray arrayWithCapacity:32];
5725 - (void) setPackage:(Package *)package {
5729 [files_ removeAllObjects];
5731 if (package != nil) {
5733 name_ = [package id];
5735 if (NSArray *files = [package files])
5736 [files_ addObjectsFromArray:files];
5738 if ([files_ count] != 0) {
5739 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5740 [files_ removeObjectAtIndex:0];
5741 [files_ sortUsingSelector:@selector(compareByPath:)];
5743 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5744 [stack addObject:@"/"];
5746 for (int i(0), e([files_ count]); i != e; ++i) {
5747 NSString *file = [files_ objectAtIndex:i];
5748 while (![file hasPrefix:[stack lastObject]])
5749 [stack removeLastObject];
5750 NSString *directory = [stack lastObject];
5751 [stack addObject:[file stringByAppendingString:@"/"]];
5752 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5753 ([stack count] - 2) * 3, "",
5754 [file substringFromIndex:[directory length]]
5763 - (void) reloadData {
5766 [self setPackage:[database_ packageWithName:name_]];
5771 /* Package Controller {{{ */
5772 @interface CYPackageController : CydiaWebViewController <
5773 UIActionSheetDelegate
5775 _transient Database *database_;
5776 _H<Package> package_;
5779 _H<NSMutableArray> buttons_;
5780 _H<UIBarButtonItem> button_;
5783 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5787 @implementation CYPackageController
5789 - (NSURL *) navigationURL {
5790 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5793 /* XXX: this is not safe at all... localization of /fail/ */
5794 - (void) _clickButtonWithName:(NSString *)name {
5795 if ([name isEqualToString:UCLocalize("CLEAR")])
5796 [delegate_ clearPackage:package_];
5797 else if ([name isEqualToString:UCLocalize("INSTALL")])
5798 [delegate_ installPackage:package_];
5799 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5800 [delegate_ installPackage:package_];
5801 else if ([name isEqualToString:UCLocalize("REMOVE")])
5802 [delegate_ removePackage:package_];
5803 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5804 [delegate_ installPackage:package_];
5805 else _assert(false);
5808 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5809 NSString *context([sheet context]);
5811 if ([context isEqualToString:@"modify"]) {
5812 if (button != [sheet cancelButtonIndex]) {
5813 NSString *buttonName = [buttons_ objectAtIndex:button];
5814 [self _clickButtonWithName:buttonName];
5817 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5821 - (bool) _allowJavaScriptPanel {
5826 - (void) _customButtonClicked {
5827 int count([buttons_ count]);
5832 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5834 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5835 [buttons addObjectsFromArray:buttons_];
5837 UIActionSheet *sheet = [[[UIActionSheet alloc]
5840 cancelButtonTitle:nil
5841 destructiveButtonTitle:nil
5842 otherButtonTitles:nil
5845 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5847 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5848 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5850 [sheet setContext:@"modify"];
5852 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5856 // We don't want to allow non-commercial packages to do custom things to the install button,
5857 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5858 - (void) customButtonClicked {
5860 [super customButtonClicked];
5862 [self _customButtonClicked];
5865 - (void) reloadButtonClicked {
5866 // Don't reload a commerical package by tapping the loading button,
5867 // but if it's not an Install button, we should forward it on.
5868 if (![package_ uninstalled])
5869 [self _customButtonClicked];
5872 - (void) applyLoadingTitle {
5873 // Don't show "Loading" as the title. Ever.
5876 - (UIBarButtonItem *) rightButton {
5881 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5882 if ((self = [super init]) != nil) {
5883 database_ = database;
5884 buttons_ = [NSMutableArray arrayWithCapacity:4];
5885 name_ = [NSString stringWithString:name];
5886 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5890 - (void) reloadData {
5893 package_ = [database_ packageWithName:name_];
5895 [buttons_ removeAllObjects];
5897 if (package_ != nil) {
5898 [(Package *) package_ parse];
5900 commercial_ = [package_ isCommercial];
5902 if ([package_ mode] != nil)
5903 [buttons_ addObject:UCLocalize("CLEAR")];
5904 if ([package_ source] == nil);
5905 else if ([package_ upgradableAndEssential:NO])
5906 [buttons_ addObject:UCLocalize("UPGRADE")];
5907 else if ([package_ uninstalled])
5908 [buttons_ addObject:UCLocalize("INSTALL")];
5910 [buttons_ addObject:UCLocalize("REINSTALL")];
5911 if (![package_ uninstalled])
5912 [buttons_ addObject:UCLocalize("REMOVE")];
5916 switch ([buttons_ count]) {
5917 case 0: title = nil; break;
5918 case 1: title = [buttons_ objectAtIndex:0]; break;
5919 default: title = UCLocalize("MODIFY"); break;
5922 button_ = [[[UIBarButtonItem alloc]
5924 style:UIBarButtonItemStylePlain
5926 action:@selector(customButtonClicked)
5930 - (bool) isLoading {
5931 return commercial_ ? [super isLoading] : false;
5937 /* Package List Controller {{{ */
5938 @interface PackageListController : CyteViewController <
5939 UITableViewDataSource,
5942 _transient Database *database_;
5944 _H<NSArray> packages_;
5945 _H<NSMutableArray> sections_;
5946 _H<UITableView, 2> list_;
5947 _H<NSMutableArray> index_;
5948 _H<NSMutableDictionary> indices_;
5949 _H<NSString> title_;
5950 unsigned reloading_;
5953 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5954 - (void) setDelegate:(id)delegate;
5955 - (void) resetCursor;
5960 @implementation PackageListController
5962 - (bool) isSummarized {
5966 - (bool) showsSections {
5970 - (void) deselectWithAnimation:(BOOL)animated {
5971 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5974 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5975 CGRect base = [[self view] bounds];
5976 base.size.height -= bounds.size.height;
5977 base.origin = [list_ frame].origin;
5979 [UIView beginAnimations:nil context:NULL];
5980 [UIView setAnimationBeginsFromCurrentState:YES];
5981 [UIView setAnimationCurve:curve];
5982 [UIView setAnimationDuration:duration];
5983 [list_ setFrame:base];
5984 [UIView commitAnimations];
5987 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5988 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5991 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5992 [self resizeForKeyboardBounds:bounds duration:0];
5995 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5996 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5997 *curve = UIViewAnimationCurveEaseInOut;
5999 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6001 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6004 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6007 - (void) keyboardWillShow:(NSNotification *)notification {
6010 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6011 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6013 NSTimeInterval duration;
6014 UIViewAnimationCurve curve;
6015 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6017 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);
6018 UIViewController *base = self;
6019 while ([base parentViewController] != nil)
6020 base = [base parentViewController];
6021 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6022 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6024 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6025 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6027 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6030 - (void) keyboardWillHide:(NSNotification *)notification {
6031 NSTimeInterval duration;
6032 UIViewAnimationCurve curve;
6033 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6035 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6038 - (void) viewWillAppear:(BOOL)animated {
6039 [super viewWillAppear:animated];
6041 [self resizeForKeyboardBounds:CGRectZero];
6042 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6043 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6046 - (void) viewWillDisappear:(BOOL)animated {
6047 [super viewWillDisappear:animated];
6049 [self resizeForKeyboardBounds:CGRectZero];
6050 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6051 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6054 - (void) viewDidAppear:(BOOL)animated {
6055 [super viewDidAppear:animated];
6056 [self deselectWithAnimation:animated];
6059 - (void) didSelectPackage:(Package *)package {
6060 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6061 [view setDelegate:delegate_];
6062 [[self navigationController] pushViewController:view animated:YES];
6065 #if TryIndexedCollation
6066 + (BOOL) hasIndexedCollation {
6067 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6071 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6072 NSInteger count([sections_ count]);
6073 return count == 0 ? 1 : count;
6076 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6077 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6079 return [[sections_ objectAtIndex:section] name];
6082 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6083 if ([sections_ count] == 0)
6085 return [[sections_ objectAtIndex:section] count];
6088 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6089 @synchronized (database_) {
6090 if ([database_ era] != era_)
6093 Section *section([sections_ objectAtIndex:[path section]]);
6094 NSInteger row([path row]);
6095 Package *package([packages_ objectAtIndex:([section row] + row)]);
6096 return [[package retain] autorelease];
6099 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6100 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6102 cell = [[[PackageCell alloc] init] autorelease];
6104 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6105 [cell setPackage:package asSummary:[self isSummarized]];
6109 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6110 Package *package([self packageAtIndexPath:path]);
6111 package = [database_ packageWithName:[package id]];
6112 [self didSelectPackage:package];
6115 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6116 if (![self showsSections])
6122 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6123 #if TryIndexedCollation
6124 if ([[self class] hasIndexedCollation]) {
6125 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6132 - (void) updateHeight {
6133 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6136 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6137 if ((self = [super init]) != nil) {
6138 database_ = database;
6139 title_ = [title copy];
6140 [[self navigationItem] setTitle:title_];
6142 #if TryIndexedCollation
6143 if ([[self class] hasIndexedCollation])
6144 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6147 index_ = [NSMutableArray arrayWithCapacity:32];
6149 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6151 packages_ = [NSArray array];
6152 sections_ = [NSMutableArray arrayWithCapacity:16];
6157 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6159 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6160 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6161 [[self view] addSubview:list_];
6163 // XXX: is 20 the most optimal number here?
6164 [list_ setSectionIndexMinimumDisplayRowCount:20];
6166 [(UITableView *) list_ setDataSource:self];
6167 [list_ setDelegate:self];
6169 [self updateHeight];
6172 - (void) releaseSubviews {
6175 [super releaseSubviews];
6178 - (void) setDelegate:(id)delegate {
6179 delegate_ = delegate;
6182 - (bool) shouldYield {
6186 - (bool) shouldBlock {
6190 - (NSMutableArray *) _reloadPackages {
6191 @synchronized (database_) {
6192 era_ = [database_ era];
6193 NSArray *packages([database_ packages]);
6195 return [NSMutableArray arrayWithArray:packages];
6198 - (void) _reloadData {
6199 if (reloading_ != 0) {
6206 if ([self shouldYield]) {
6210 if (![self shouldBlock])
6213 hud = [delegate_ addProgressHUD];
6214 [hud setText:UCLocalize("LOADING")];
6218 packages = [self yieldToSelector:@selector(_reloadPackages)];
6221 [delegate_ removeProgressHUD:hud];
6222 } while (reloading_ == 2);
6226 packages = [self _reloadPackages];
6229 packages_ = packages;
6231 [indices_ removeAllObjects];
6232 [sections_ removeAllObjects];
6234 Section *section = nil;
6236 #if TryIndexedCollation
6237 if ([[self class] hasIndexedCollation]) {
6238 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6239 NSArray *titles = [collation sectionIndexTitles];
6242 _profile(PackageTable$reloadData$Section)
6243 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6247 _profile(PackageTable$reloadData$Section$Package)
6248 package = [packages_ objectAtIndex:offset];
6249 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6252 while (secidx < index) {
6255 _profile(PackageTable$reloadData$Section$Allocate)
6256 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6259 _profile(PackageTable$reloadData$Section$Add)
6260 [sections_ addObject:section];
6264 [section addToCount];
6270 [index_ removeAllObjects];
6272 bool sectioned([self showsSections]);
6274 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6275 [sections_ addObject:section];
6278 _profile(PackageTable$reloadData$Section)
6279 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6283 _profile(PackageTable$reloadData$Section$Package)
6284 package = [packages_ objectAtIndex:offset];
6285 index = [package index];
6288 if (sectioned && (section == nil || [section index] != index)) {
6289 _profile(PackageTable$reloadData$Section$Allocate)
6290 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6293 [index_ addObject:[section name]];
6294 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6296 _profile(PackageTable$reloadData$Section$Add)
6297 [sections_ addObject:section];
6301 [section addToCount];
6306 [self updateHeight];
6308 _profile(PackageTable$reloadData$List)
6309 [(UITableView *) list_ setDataSource:self];
6314 - (void) reloadData {
6316 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6319 - (void) resetCursor {
6320 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6323 - (void) clearData {
6324 [self updateHeight];
6326 [list_ setDataSource:nil];
6334 /* Filtered Package List Controller {{{ */
6335 @interface FilteredPackageListController : PackageListController {
6338 _H<NSObject> object_;
6341 - (void) setObject:(id)object;
6342 - (void) setObject:(id)object forFilter:(SEL)filter;
6345 - (void) setFilter:(SEL)filter;
6347 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6351 @implementation FilteredPackageListController
6357 - (void) setFilter:(SEL)filter {
6358 @synchronized (self) {
6361 /* XXX: this is an unsafe optimization of doomy hell */
6362 Method method(class_getInstanceMethod([Package class], filter));
6363 _assert(method != NULL);
6364 imp_ = method_getImplementation(method);
6365 _assert(imp_ != NULL);
6368 - (void) setObject:(id)object {
6369 @synchronized (self) {
6373 - (void) setObject:(id)object forFilter:(SEL)filter {
6374 @synchronized (self) {
6375 [self setFilter:filter];
6376 [self setObject:object];
6379 - (NSMutableArray *) _reloadPackages {
6380 @synchronized (database_) {
6381 era_ = [database_ era];
6382 NSArray *packages([database_ packages]);
6384 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6388 _H<NSObject> object;
6390 @synchronized (self) {
6396 _profile(PackageTable$reloadData$Filter)
6397 for (Package *package in packages)
6398 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6399 [filtered addObject:package];
6405 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6406 if ((self = [super initWithDatabase:database title:title]) != nil) {
6407 [self setFilter:filter];
6408 [self setObject:object];
6415 /* Home Controller {{{ */
6416 @interface HomeController : CydiaWebViewController {
6421 @implementation HomeController
6424 if ((self = [super init]) != nil) {
6425 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6430 - (NSURL *) navigationURL {
6431 return [NSURL URLWithString:@"cydia://home"];
6434 - (void) aboutButtonClicked {
6435 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6437 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6438 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6439 [alert setCancelButtonIndex:0];
6442 @"Copyright \u00a9 2008-2011\n"
6445 "Jay Freeman (saurik)\n"
6446 "saurik@saurik.com\n"
6447 "http://www.saurik.com/"
6453 - (UIBarButtonItem *) leftButton {
6454 return [[[UIBarButtonItem alloc]
6455 initWithTitle:UCLocalize("ABOUT")
6456 style:UIBarButtonItemStylePlain
6458 action:@selector(aboutButtonClicked)
6464 /* Manage Controller {{{ */
6465 @interface ManageController : CydiaWebViewController {
6468 - (void) queueStatusDidChange;
6472 @implementation ManageController
6475 if ((self = [super init]) != nil) {
6476 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6480 - (NSURL *) navigationURL {
6481 return [NSURL URLWithString:@"cydia://manage"];
6484 - (UIBarButtonItem *) leftButton {
6485 return [[[UIBarButtonItem alloc]
6486 initWithTitle:UCLocalize("SETTINGS")
6487 style:UIBarButtonItemStylePlain
6489 action:@selector(settingsButtonClicked)
6493 - (void) settingsButtonClicked {
6494 [delegate_ showSettings];
6497 - (void) queueButtonClicked {
6501 - (UIBarButtonItem *) customButton {
6502 return Queuing_ ? [[[UIBarButtonItem alloc]
6503 initWithTitle:UCLocalize("QUEUE")
6504 style:UIBarButtonItemStyleDone
6506 action:@selector(queueButtonClicked)
6507 ] autorelease] : [super customButton];
6510 - (void) queueStatusDidChange {
6511 [self applyRightButton];
6514 - (bool) isLoading {
6515 return !Queuing_ && [super isLoading];
6521 /* Refresh Bar {{{ */
6522 @interface RefreshBar : UINavigationBar {
6523 _H<UIProgressIndicator> indicator_;
6524 _H<UITextLabel> prompt_;
6525 _H<UIProgressBar> progress_;
6526 _H<UINavigationButton> cancel_;
6531 @implementation RefreshBar
6533 - (void) positionViews {
6534 CGRect frame = [cancel_ frame];
6535 frame.size = [cancel_ sizeThatFits:frame.size];
6536 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6537 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6538 [cancel_ setFrame:frame];
6540 CGSize prgsize = {75, 100};
6542 [self frame].size.width - prgsize.width - 10,
6543 ([self frame].size.height - prgsize.height) / 2
6545 [progress_ setFrame:prgrect];
6547 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6548 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6549 CGRect indrect = {{indoffset, indoffset}, indsize};
6550 [indicator_ setFrame:indrect];
6552 CGSize prmsize = {215, indsize.height + 4};
6554 indoffset * 2 + indsize.width,
6555 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6557 [prompt_ setFrame:prmrect];
6560 - (void) setFrame:(CGRect)frame {
6561 [super setFrame:frame];
6562 [self positionViews];
6565 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6566 if ((self = [super initWithFrame:frame]) != nil) {
6567 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6569 [self setBarStyle:UIBarStyleBlack];
6571 UIBarStyle barstyle([self _barStyle:NO]);
6572 bool ugly(barstyle == UIBarStyleDefault);
6574 UIProgressIndicatorStyle style = ugly ?
6575 UIProgressIndicatorStyleMediumBrown :
6576 UIProgressIndicatorStyleMediumWhite;
6578 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6579 [(UIProgressIndicator *) indicator_ setStyle:style];
6580 [indicator_ startAnimation];
6581 [self addSubview:indicator_];
6583 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6584 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6585 [prompt_ setBackgroundColor:[UIColor clearColor]];
6586 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6587 [self addSubview:prompt_];
6589 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6590 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6591 [(UIProgressBar *) progress_ setStyle:0];
6592 [self addSubview:progress_];
6594 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6595 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6596 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6597 [cancel_ setBarStyle:barstyle];
6599 [self positionViews];
6603 - (void) setCancellable:(bool)cancellable {
6605 [self addSubview:cancel_];
6607 [cancel_ removeFromSuperview];
6611 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6612 [progress_ setProgress:0];
6616 [self setCancellable:NO];
6619 - (void) setPrompt:(NSString *)prompt {
6620 [prompt_ setText:prompt];
6623 - (void) setProgress:(float)progress {
6624 [progress_ setProgress:progress];
6630 /* Cydia Navigation Controller Interface {{{ */
6631 @interface UINavigationController (Cydia)
6633 - (NSArray *) navigationURLCollection;
6634 - (void) unloadData;
6639 /* Cydia Tab Bar Controller {{{ */
6640 @interface CYTabBarController : UITabBarController <
6641 UITabBarControllerDelegate,
6644 _transient Database *database_;
6645 _H<RefreshBar, 1> refreshbar_;
6649 // XXX: ok, "updatedelegate_"?...
6650 _transient NSObject<CydiaDelegate> *updatedelegate_;
6652 _H<UIViewController> remembered_;
6653 _transient UIViewController *transient_;
6656 - (NSArray *) navigationURLCollection;
6657 - (void) dropBar:(BOOL)animated;
6658 - (void) beginUpdate;
6659 - (void) raiseBar:(BOOL)animated;
6661 - (void) unloadData;
6665 @implementation CYTabBarController
6667 - (void) setUnselectedViewController:(UIViewController *)transient {
6668 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6669 if (transient != nil) {
6670 if (transient_ == nil)
6671 remembered_ = [controllers objectAtIndex:0];
6672 transient_ = transient;
6673 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6674 [controllers replaceObjectAtIndex:0 withObject:transient_];
6675 [self setSelectedIndex:0];
6676 [self setViewControllers:controllers];
6677 [self concealTabBarSelection];
6678 } else if (remembered_ != nil) {
6679 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6680 transient_ = transient;
6681 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6683 [self setViewControllers:controllers];
6684 [self revealTabBarSelection];
6688 - (UIViewController *) unselectedViewController {
6692 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6693 if ([self unselectedViewController])
6694 [self setUnselectedViewController:nil];
6697 - (NSArray *) navigationURLCollection {
6698 NSMutableArray *items([NSMutableArray array]);
6700 // XXX: Should this deal with transient view controllers?
6701 for (id navigation in [self viewControllers]) {
6702 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6704 [items addObject:stack];
6710 - (void) unloadData {
6713 for (UINavigationController *controller in [self viewControllers])
6714 [controller unloadData];
6716 if (UIViewController *selected = [self selectedViewController])
6717 [selected reloadData];
6719 if (UIViewController *unselected = [self unselectedViewController]) {
6720 [unselected unloadData];
6721 [unselected reloadData];
6726 [[NSNotificationCenter defaultCenter] removeObserver:self];
6731 - (id) initWithDatabase:(Database *)database {
6732 if ((self = [super init]) != nil) {
6733 database_ = database;
6734 [self setDelegate:self];
6736 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6737 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6739 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6743 - (void) setUpdate:(NSDate *)date {
6747 - (void) beginUpdate {
6748 [(RefreshBar *) refreshbar_ start];
6751 [updatedelegate_ retainNetworkActivityIndicator];
6755 detachNewThreadSelector:@selector(performUpdate)
6761 - (void) performUpdate {
6762 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6765 status.setDelegate(self);
6766 [database_ updateWithStatus:status];
6769 performSelectorOnMainThread:@selector(completeUpdate)
6777 - (void) stopUpdateWithSelector:(SEL)selector {
6779 [updatedelegate_ releaseNetworkActivityIndicator];
6781 [self raiseBar:YES];
6784 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6787 - (void) completeUpdate {
6790 [self stopUpdateWithSelector:@selector(reloadData)];
6793 - (void) cancelUpdate {
6794 [self stopUpdateWithSelector:@selector(updateData)];
6797 - (void) cancelPressed {
6798 [self cancelUpdate];
6805 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6806 [refreshbar_ setPrompt:[event compoundMessage]];
6809 - (bool) isProgressCancelled {
6813 - (void) setProgressCancellable:(NSNumber *)cancellable {
6814 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6817 - (void) setProgressPercent:(NSNumber *)percent {
6818 [refreshbar_ setProgress:[percent floatValue]];
6821 - (void) setProgressStatus:(NSDictionary *)status {
6823 [self setProgressPercent:[status objectForKey:@"Percent"]];
6826 - (void) setUpdateDelegate:(id)delegate {
6827 updatedelegate_ = delegate;
6830 - (UIView *) transitionView {
6831 if ([self respondsToSelector:@selector(_transitionView)])
6832 return [self _transitionView];
6834 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6837 - (void) dropBar:(BOOL)animated {
6842 UIView *transition([self transitionView]);
6843 [[self view] addSubview:refreshbar_];
6845 CGRect barframe([refreshbar_ frame]);
6847 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6848 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6850 barframe.origin.y = 0;
6852 [refreshbar_ setFrame:barframe];
6855 [UIView beginAnimations:nil context:NULL];
6857 CGRect viewframe = [transition frame];
6858 viewframe.origin.y += barframe.size.height;
6859 viewframe.size.height -= barframe.size.height;
6860 [transition setFrame:viewframe];
6863 [UIView commitAnimations];
6865 // Ensure bar has the proper width for our view, it might have changed
6866 barframe.size.width = viewframe.size.width;
6867 [refreshbar_ setFrame:barframe];
6870 - (void) raiseBar:(BOOL)animated {
6875 UIView *transition([self transitionView]);
6876 [refreshbar_ removeFromSuperview];
6878 CGRect barframe([refreshbar_ frame]);
6881 [UIView beginAnimations:nil context:NULL];
6883 CGRect viewframe = [transition frame];
6884 viewframe.origin.y -= barframe.size.height;
6885 viewframe.size.height += barframe.size.height;
6886 [transition setFrame:viewframe];
6889 [UIView commitAnimations];
6892 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6893 bool dropped(dropped_);
6898 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6904 - (void) statusBarFrameChanged:(NSNotification *)notification {
6914 /* Cydia Navigation Controller Implementation {{{ */
6915 @implementation UINavigationController (Cydia)
6917 - (NSArray *) navigationURLCollection {
6918 NSMutableArray *stack([NSMutableArray array]);
6920 for (CyteViewController *controller in [self viewControllers]) {
6921 NSString *url = [[controller navigationURL] absoluteString];
6923 [stack addObject:url];
6929 - (void) reloadData {
6932 UIViewController *visible([self visibleViewController]);
6934 [visible reloadData];
6936 // on the iPad, this view controller is ALSO visible. :(
6938 if (UIViewController *top = [self topViewController])
6943 - (void) unloadData {
6944 for (CyteViewController *page in [self viewControllers])
6953 /* Cydia:// Protocol {{{ */
6954 @interface CydiaURLProtocol : NSURLProtocol {
6959 @implementation CydiaURLProtocol
6961 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6962 NSURL *url([request URL]);
6966 NSString *scheme([[url scheme] lowercaseString]);
6967 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6969 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6975 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6979 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6980 id<NSURLProtocolClient> client([self client]);
6982 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6984 NSData *data(UIImagePNGRepresentation(icon));
6986 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6987 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6988 [client URLProtocol:self didLoadData:data];
6989 [client URLProtocolDidFinishLoading:self];
6993 - (void) startLoading {
6994 id<NSURLProtocolClient> client([self client]);
6995 NSURLRequest *request([self request]);
6997 NSURL *url([request URL]);
6998 NSString *href([url absoluteString]);
6999 NSString *scheme([[url scheme] lowercaseString]);
7003 if ([scheme isEqualToString:@"cydia"])
7004 path = [href substringFromIndex:8];
7005 else if ([scheme isEqualToString:@"about"])
7006 path = [href substringFromIndex:12];
7007 else _assert(false);
7009 NSRange slash([path rangeOfString:@"/"]);
7012 if (slash.location == NSNotFound) {
7016 command = [path substringToIndex:slash.location];
7017 path = [path substringFromIndex:(slash.location + 1)];
7020 Database *database([Database sharedInstance]);
7022 if ([command isEqualToString:@"package-icon"]) {
7025 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7026 Package *package([database packageWithName:path]);
7030 UIImage *icon([package icon]);
7031 [self _returnPNGWithImage:icon forRequest:request];
7032 } else if ([command isEqualToString:@"source-icon"]) {
7035 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7036 NSString *source(Simplify(path));
7037 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7039 icon = [UIImage applicationImageNamed:@"unknown.png"];
7040 [self _returnPNGWithImage:icon forRequest:request];
7041 } else if ([command isEqualToString:@"uikit-image"]) {
7044 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7045 UIImage *icon(_UIImageWithName(path));
7046 [self _returnPNGWithImage:icon forRequest:request];
7047 } else if ([command isEqualToString:@"section-icon"]) {
7050 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7051 NSString *section(Simplify(path));
7052 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7054 icon = [UIImage applicationImageNamed:@"unknown.png"];
7055 [self _returnPNGWithImage:icon forRequest:request];
7057 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7061 - (void) stopLoading {
7067 /* Section Controller {{{ */
7068 @interface SectionController : FilteredPackageListController {
7069 _H<NSString> section_;
7072 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7076 @implementation SectionController
7078 - (NSURL *) navigationURL {
7079 NSString *name = section_;
7083 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7086 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7089 title = UCLocalize("ALL_PACKAGES");
7090 else if (![name isEqual:@""])
7091 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7093 title = UCLocalize("NO_SECTION");
7095 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7102 /* Sections Controller {{{ */
7103 @interface SectionsController : CyteViewController <
7104 UITableViewDataSource,
7107 _transient Database *database_;
7108 _H<NSMutableArray> sections_;
7109 _H<NSMutableArray> filtered_;
7110 _H<UITableView, 2> list_;
7113 - (id) initWithDatabase:(Database *)database;
7114 - (void) editButtonClicked;
7118 @implementation SectionsController
7120 - (NSURL *) navigationURL {
7121 return [NSURL URLWithString:@"cydia://sections"];
7124 - (void) updateNavigationItem {
7125 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7126 if ([sections_ count] == 0) {
7127 [[self navigationItem] setRightBarButtonItem:nil];
7129 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7130 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7132 action:@selector(editButtonClicked)
7133 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7137 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7138 [super setEditing:editing animated:animated];
7143 [delegate_ updateData];
7145 [self updateNavigationItem];
7148 - (void) viewDidAppear:(BOOL)animated {
7149 [super viewDidAppear:animated];
7150 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7153 - (void) viewWillDisappear:(BOOL)animated {
7154 [super viewWillDisappear:animated];
7155 if ([self isEditing]) [self setEditing:NO];
7158 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7159 Section *section = nil;
7160 int index = [indexPath row];
7161 if (![self isEditing]) {
7164 section = [filtered_ objectAtIndex:index];
7166 section = [sections_ objectAtIndex:index];
7171 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7172 if ([self isEditing])
7173 return [sections_ count];
7175 return [filtered_ count] + 1;
7178 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7182 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7183 static NSString *reuseIdentifier = @"SectionCell";
7185 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7187 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7189 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7194 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7195 if ([self isEditing])
7198 Section *section = [self sectionAtIndexPath:indexPath];
7200 SectionController *controller = [[[SectionController alloc]
7201 initWithDatabase:database_
7202 section:[section name]
7204 [controller setDelegate:delegate_];
7206 [[self navigationController] pushViewController:controller animated:YES];
7210 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7212 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7213 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7214 [list_ setRowHeight:45.0f];
7215 [(UITableView *) list_ setDataSource:self];
7216 [list_ setDelegate:self];
7217 [[self view] addSubview:list_];
7220 - (void) viewDidLoad {
7221 [super viewDidLoad];
7223 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7226 - (void) releaseSubviews {
7229 [super releaseSubviews];
7232 - (id) initWithDatabase:(Database *)database {
7233 if ((self = [super init]) != nil) {
7234 database_ = database;
7236 sections_ = [NSMutableArray arrayWithCapacity:16];
7237 filtered_ = [NSMutableArray arrayWithCapacity:16];
7241 - (void) reloadData {
7244 NSArray *packages = [database_ packages];
7246 [sections_ removeAllObjects];
7247 [filtered_ removeAllObjects];
7249 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7252 for (Package *package in packages) {
7253 NSString *name([package section]);
7254 NSString *key(name == nil ? @"" : name);
7258 _profile(SectionsView$reloadData$Section)
7259 section = [sections objectForKey:key];
7260 if (section == nil) {
7261 _profile(SectionsView$reloadData$Section$Allocate)
7262 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7263 [sections setObject:section forKey:key];
7268 [section addToCount];
7270 _profile(SectionsView$reloadData$Filter)
7271 if (![package valid] || ![package visible])
7279 [sections_ addObjectsFromArray:[sections allValues]];
7281 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7283 for (Section *section in (id) sections_) {
7284 size_t count([section row]);
7288 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7289 [section setCount:count];
7290 [filtered_ addObject:section];
7293 [self updateNavigationItem];
7298 - (void) editButtonClicked {
7299 [self setEditing:![self isEditing] animated:YES];
7305 /* Changes Controller {{{ */
7306 @interface ChangesController : CyteViewController <
7307 UITableViewDataSource,
7310 _transient Database *database_;
7312 _H<NSArray> packages_;
7313 _H<NSMutableArray> sections_;
7314 _H<UITableView, 2> list_;
7318 - (id) initWithDatabase:(Database *)database;
7322 @implementation ChangesController
7324 - (NSURL *) navigationURL {
7325 return [NSURL URLWithString:@"cydia://changes"];
7328 - (void) viewDidAppear:(BOOL)animated {
7329 [super viewDidAppear:animated];
7330 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7333 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7334 NSInteger count([sections_ count]);
7335 return count == 0 ? 1 : count;
7338 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7339 if ([sections_ count] == 0)
7341 return [[sections_ objectAtIndex:section] name];
7344 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7345 if ([sections_ count] == 0)
7347 return [[sections_ objectAtIndex:section] count];
7350 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7351 @synchronized (database_) {
7352 if ([database_ era] != era_)
7355 NSUInteger sectionIndex([path section]);
7356 if (sectionIndex >= [sections_ count])
7358 Section *section([sections_ objectAtIndex:sectionIndex]);
7359 NSInteger row([path row]);
7360 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7363 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7364 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7366 cell = [[[PackageCell alloc] init] autorelease];
7368 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7369 [cell setPackage:package asSummary:false];
7373 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7374 Package *package([self packageAtIndexPath:path]);
7375 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7376 [view setDelegate:delegate_];
7377 [[self navigationController] pushViewController:view animated:YES];
7381 - (void) refreshButtonClicked {
7382 [delegate_ beginUpdate];
7383 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7386 - (void) upgradeButtonClicked {
7387 [delegate_ distUpgrade];
7388 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7392 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7394 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7395 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7396 [list_ setRowHeight:73];
7397 [(UITableView *) list_ setDataSource:self];
7398 [list_ setDelegate:self];
7399 [[self view] addSubview:list_];
7402 - (void) viewDidLoad {
7403 [super viewDidLoad];
7405 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7408 - (void) releaseSubviews {
7411 [super releaseSubviews];
7414 - (id) initWithDatabase:(Database *)database {
7415 if ((self = [super init]) != nil) {
7416 database_ = database;
7418 packages_ = [NSArray array];
7419 sections_ = [NSMutableArray arrayWithCapacity:16];
7423 - (NSMutableArray *) _reloadPackages {
7424 @synchronized (database_) {
7425 era_ = [database_ era];
7426 NSArray *packages([database_ packages]);
7428 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7431 _profile(ChangesController$_reloadPackages$Filter)
7432 for (Package *package in packages)
7433 if ([package upgradableAndEssential:YES] || [package visible])
7434 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7437 _profile(ChangesController$_reloadPackages$radixSort)
7438 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7445 - (void) _reloadData {
7450 UIProgressHUD *hud([delegate_ addProgressHUD]);
7451 [hud setText:UCLocalize("LOADING")];
7452 //NSLog(@"HUD:%@::%@", delegate_, hud);
7453 packages = [self yieldToSelector:@selector(_reloadPackages)];
7454 [delegate_ removeProgressHUD:hud];
7456 packages = [self _reloadPackages];
7459 @synchronized (database_) {
7460 if (era_ != [database_ era])
7463 packages_ = packages;
7464 [sections_ removeAllObjects];
7466 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7467 Section *ignored = nil;
7468 Section *section = nil;
7472 bool unseens = false;
7474 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7476 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7477 Package *package = [packages_ objectAtIndex:offset];
7479 BOOL uae = [package upgradableAndEssential:YES];
7483 time_t seen([package seen]);
7485 if (section == nil || last != seen) {
7489 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7492 _profile(ChangesController$reloadData$Allocate)
7493 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7494 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7495 [sections_ addObject:section];
7499 [section addToCount];
7500 } else if ([package ignored]) {
7501 if (ignored == nil) {
7502 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7504 [ignored addToCount];
7507 [upgradable addToCount];
7512 CFRelease(formatter);
7515 Section *last = [sections_ lastObject];
7516 size_t count = [last count];
7517 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7518 [sections_ removeLastObject];
7521 if ([ignored count] != 0)
7522 [sections_ insertObject:ignored atIndex:0];
7524 [sections_ insertObject:upgradable atIndex:0];
7528 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7529 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7530 style:UIBarButtonItemStylePlain
7532 action:@selector(upgradeButtonClicked)
7533 ] autorelease]) animated:YES];
7535 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7536 initWithTitle:UCLocalize("REFRESH")
7537 style:UIBarButtonItemStylePlain
7539 action:@selector(refreshButtonClicked)
7540 ] autorelease]) animated:YES];
7545 - (void) reloadData {
7547 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7552 /* Search Controller {{{ */
7553 @interface SearchController : FilteredPackageListController <
7556 _H<UISearchBar, 1> search_;
7560 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7561 - (void) reloadData;
7565 @implementation SearchController
7567 - (NSURL *) navigationURL {
7568 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7569 return [NSURL URLWithString:@"cydia://search"];
7571 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7574 - (void) useSearch {
7575 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7580 - (void) viewWillAppear:(BOOL)animated {
7581 [super viewWillAppear:animated];
7583 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7587 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7588 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7593 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7594 [search_ resignFirstResponder];
7598 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7599 [search_ setText:@""];
7600 [self searchBarButtonClicked:searchBar];
7603 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7604 [self searchBarButtonClicked:searchBar];
7607 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7608 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7612 - (bool) shouldYield {
7616 - (bool) shouldBlock {
7617 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7620 - (bool) isSummarized {
7621 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7624 - (bool) showsSections {
7628 - (NSMutableArray *) _reloadPackages {
7629 NSMutableArray *packages([super _reloadPackages]);
7630 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7631 [packages radixSortUsingSelector:@selector(rank)];
7635 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7636 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7637 search_ = [[[UISearchBar alloc] init] autorelease];
7638 [search_ setDelegate:self];
7641 [search_ setText:query];
7645 - (void) viewDidAppear:(BOOL)animated {
7646 [super viewDidAppear:animated];
7648 if (!searchloaded_) {
7649 searchloaded_ = YES;
7650 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7651 [search_ layoutSubviews];
7652 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7654 UITextField *textField;
7655 if ([search_ respondsToSelector:@selector(searchField)])
7656 textField = [search_ searchField];
7658 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7660 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7661 [textField setEnablesReturnKeyAutomatically:NO];
7662 [[self navigationItem] setTitleView:textField];
7666 - (void) reloadData {
7667 id object([search_ text]);
7668 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7669 object = [object componentsSeparatedByString:@" "];
7671 [self setObject:object];
7677 - (void) didSelectPackage:(Package *)package {
7678 [search_ resignFirstResponder];
7679 [super didSelectPackage:package];
7684 /* Package Settings Controller {{{ */
7685 @interface PackageSettingsController : CyteViewController <
7686 UITableViewDataSource,
7689 _transient Database *database_;
7691 _H<Package> package_;
7692 _H<UITableView, 2> table_;
7693 _H<UISwitch> subscribedSwitch_;
7694 _H<UISwitch> ignoredSwitch_;
7695 _H<UITableViewCell> subscribedCell_;
7696 _H<UITableViewCell> ignoredCell_;
7699 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7703 @implementation PackageSettingsController
7705 - (NSURL *) navigationURL {
7706 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7709 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7710 if (package_ == nil)
7713 if ([package_ installed] == nil)
7719 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7720 if (package_ == nil)
7723 // both sections contain just one item right now.
7727 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7731 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7733 return UCLocalize("SHOW_ALL_CHANGES_EX");
7735 return UCLocalize("IGNORE_UPGRADES_EX");
7738 - (void) onSubscribed:(id)control {
7739 bool value([control isOn]);
7740 if (package_ == nil)
7742 if ([package_ setSubscribed:value])
7743 [delegate_ updateData];
7746 - (void) _updateIgnored {
7747 const char *package([name_ UTF8String]);
7748 bool on([ignoredSwitch_ isOn]);
7750 pid_t pid(ExecFork());
7752 FILE *dpkg(popen("dpkg --set-selections", "w"));
7753 fwrite(package, strlen(package), 1, dpkg);
7756 fwrite(" hold\n", 6, 1, dpkg);
7758 fwrite(" install\n", 9, 1, dpkg);
7768 int result(waitpid(pid, &status, 0));
7771 _assert(result == pid);
7777 - (void) onIgnored:(id)control {
7778 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7779 [invocation setTarget:self];
7780 [invocation setSelector:@selector(_updateIgnored)];
7782 [delegate_ reloadDataWithInvocation:invocation];
7785 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7786 if (package_ == nil)
7789 switch ([indexPath section]) {
7790 case 0: return subscribedCell_;
7791 case 1: return ignoredCell_;
7800 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7802 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7803 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7804 [(UITableView *) table_ setDataSource:self];
7805 [table_ setDelegate:self];
7806 [[self view] addSubview:table_];
7808 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7809 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7810 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7812 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7813 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7814 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7816 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7817 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7818 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7819 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7821 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7822 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7823 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7824 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7827 - (void) viewDidLoad {
7828 [super viewDidLoad];
7830 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7833 - (void) releaseSubviews {
7835 subscribedCell_ = nil;
7837 ignoredSwitch_ = nil;
7838 subscribedSwitch_ = nil;
7840 [super releaseSubviews];
7843 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7844 if ((self = [super init]) != nil) {
7845 database_ = database;
7850 - (void) reloadData {
7853 package_ = [database_ packageWithName:name_];
7855 if (package_ != nil) {
7856 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7857 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7858 } // XXX: what now, G?
7860 [table_ reloadData];
7866 /* Installed Controller {{{ */
7867 @interface InstalledController : FilteredPackageListController {
7871 - (id) initWithDatabase:(Database *)database;
7873 - (void) updateRoleButton;
7874 - (void) queueStatusDidChange;
7878 @implementation InstalledController
7880 - (NSURL *) navigationURL {
7881 return [NSURL URLWithString:@"cydia://installed"];
7884 - (id) initWithDatabase:(Database *)database {
7885 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7886 [self updateRoleButton];
7887 [self queueStatusDidChange];
7892 - (void) queueButtonClicked {
7897 - (void) queueStatusDidChange {
7901 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7902 initWithTitle:UCLocalize("QUEUE")
7903 style:UIBarButtonItemStyleDone
7905 action:@selector(queueButtonClicked)
7908 [[self navigationItem] setLeftBarButtonItem:nil];
7914 - (void) updateRoleButton {
7915 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7916 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7917 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7918 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7920 action:@selector(roleButtonClicked)
7924 - (void) roleButtonClicked {
7925 [self setObject:[NSNumber numberWithBool:expert_]];
7929 [self updateRoleButton];
7935 /* Source Cell {{{ */
7936 @interface SourceCell : CyteTableViewCell <
7937 CyteTableViewCellDelegate
7940 _H<NSString> origin_;
7941 _H<NSString> label_;
7944 - (void) setSource:(Source *)source;
7948 @implementation SourceCell
7950 - (void) _setImage:(UIImage *)image {
7952 [content_ setNeedsDisplay];
7955 - (void) _setSource:(Source *)source {
7956 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7958 if (NSString *base = [source base])
7959 if ([base length] != 0) {
7960 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7962 if (NSData *data = [NSURLConnection
7963 sendSynchronousRequest:[NSURLRequest
7965 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7969 returningResponse:NULL
7972 if (UIImage *image = [UIImage imageWithData:data])
7973 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7979 - (void) setSource:(Source *)source {
7980 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7982 origin_ = [source name];
7983 label_ = [source uri];
7985 [content_ setNeedsDisplay];
7987 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7990 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7991 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7992 UIView *content([self contentView]);
7993 CGRect bounds([content bounds]);
7995 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7996 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7997 [content_ setBackgroundColor:[UIColor whiteColor]];
7998 [content addSubview:content_];
8000 [content_ setDelegate:self];
8001 [content_ setOpaque:YES];
8005 - (NSString *) accessibilityLabel {
8009 - (void) drawContentRect:(CGRect)rect {
8010 bool highlighted(highlighted_);
8011 float width(rect.size.width);
8014 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8021 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8025 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8030 /* Source Controller {{{ */
8031 @interface SourceController : FilteredPackageListController {
8032 _transient Source *source_;
8036 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8040 @implementation SourceController
8042 - (NSURL *) navigationURL {
8043 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8046 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8047 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8049 key_ = [source key];
8053 - (void) reloadData {
8054 source_ = [database_ sourceWithKey:key_];
8055 key_ = [source_ key];
8056 [self setObject:source_];
8058 [[self navigationItem] setTitle:[source_ label]];
8065 /* Sources Controller {{{ */
8066 @interface SourcesController : CyteViewController <
8067 UITableViewDataSource,
8070 _transient Database *database_;
8071 _H<UITableView, 2> list_;
8072 _H<NSMutableArray> sources_;
8076 _H<UIProgressHUD> hud_;
8079 //NSURLConnection *installer_;
8080 NSURLConnection *trivial_;
8081 NSURLConnection *trivial_bz2_;
8082 NSURLConnection *trivial_gz_;
8083 //NSURLConnection *automatic_;
8088 - (id) initWithDatabase:(Database *)database;
8089 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8093 @implementation SourcesController
8095 - (void) _releaseConnection:(NSURLConnection *)connection {
8096 if (connection != nil) {
8097 [connection cancel];
8098 //[connection setDelegate:nil];
8099 [connection release];
8104 //[self _releaseConnection:installer_];
8105 [self _releaseConnection:trivial_];
8106 [self _releaseConnection:trivial_gz_];
8107 [self _releaseConnection:trivial_bz2_];
8108 //[self _releaseConnection:automatic_];
8113 - (NSURL *) navigationURL {
8114 return [NSURL URLWithString:@"cydia://sources"];
8117 - (void) viewDidAppear:(BOOL)animated {
8118 [super viewDidAppear:animated];
8119 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8122 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8123 return offset_ == 0 ? 1 : 2;
8126 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8127 switch (section + (offset_ == 0 ? 1 : 0)) {
8128 case 0: return UCLocalize("ENTERED_BY_USER");
8129 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8135 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8136 int count = [sources_ count];
8138 case 0: return (offset_ == 0 ? count : offset_);
8139 case 1: return count - offset_;
8145 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8147 switch (indexPath.section) {
8148 case 0: idx = indexPath.row; break;
8149 case 1: idx = indexPath.row + offset_; break;
8153 return [sources_ objectAtIndex:idx];
8156 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8157 static NSString *cellIdentifier = @"SourceCell";
8159 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8160 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8161 [cell setSource:[self sourceAtIndexPath:indexPath]];
8162 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8167 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8168 Source *source = [self sourceAtIndexPath:indexPath];
8170 SourceController *controller = [[[SourceController alloc]
8171 initWithDatabase:database_
8175 [controller setDelegate:delegate_];
8177 [[self navigationController] pushViewController:controller animated:YES];
8180 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8181 Source *source = [self sourceAtIndexPath:indexPath];
8182 return [source record] != nil;
8185 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8186 if (editingStyle == UITableViewCellEditingStyleDelete) {
8187 Source *source = [self sourceAtIndexPath:indexPath];
8188 [Sources_ removeObjectForKey:[source key]];
8189 [delegate_ syncData];
8194 [delegate_ addTrivialSource:href_];
8195 [delegate_ syncData];
8198 - (NSString *) getWarning {
8199 NSString *href(href_);
8200 NSRange colon([href rangeOfString:@"://"]);
8201 if (colon.location != NSNotFound)
8202 href = [href substringFromIndex:(colon.location + 3)];
8203 href = [href stringByAddingPercentEscapes];
8204 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8205 href = [href stringByCachingURLWithCurrentCDN];
8207 NSURL *url([NSURL URLWithString:href]);
8209 NSStringEncoding encoding;
8210 NSError *error(nil);
8212 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8213 return [warning length] == 0 ? nil : warning;
8217 - (void) _endConnection:(NSURLConnection *)connection {
8218 // XXX: the memory management in this method is horribly awkward
8220 NSURLConnection **field = NULL;
8221 if (connection == trivial_)
8223 else if (connection == trivial_bz2_)
8224 field = &trivial_bz2_;
8225 else if (connection == trivial_gz_)
8226 field = &trivial_gz_;
8227 _assert(field != NULL);
8228 [connection release];
8233 trivial_bz2_ == nil &&
8236 [delegate_ releaseNetworkActivityIndicator];
8238 [delegate_ removeProgressHUD:hud_];
8244 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8247 UIAlertView *alert = [[[UIAlertView alloc]
8248 initWithTitle:UCLocalize("SOURCE_WARNING")
8251 cancelButtonTitle:UCLocalize("CANCEL")
8253 UCLocalize("ADD_ANYWAY"),
8257 [alert setContext:@"warning"];
8258 [alert setNumberOfRows:1];
8262 } else if (error_ != nil) {
8263 UIAlertView *alert = [[[UIAlertView alloc]
8264 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8265 message:[error_ localizedDescription]
8267 cancelButtonTitle:UCLocalize("OK")
8268 otherButtonTitles:nil
8271 [alert setContext:@"urlerror"];
8274 UIAlertView *alert = [[[UIAlertView alloc]
8275 initWithTitle:UCLocalize("NOT_REPOSITORY")
8276 message:UCLocalize("NOT_REPOSITORY_EX")
8278 cancelButtonTitle:UCLocalize("OK")
8279 otherButtonTitles:nil
8282 [alert setContext:@"trivial"];
8291 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8292 switch ([response statusCode]) {
8298 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8299 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8301 [self _endConnection:connection];
8304 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8305 [self _endConnection:connection];
8308 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8309 NSURL *url([NSURL URLWithString:href]);
8311 NSMutableURLRequest *request = [NSMutableURLRequest
8313 cachePolicy:NSURLRequestUseProtocolCachePolicy
8314 timeoutInterval:120.0
8317 [request setHTTPMethod:method];
8319 if (Machine_ != NULL)
8320 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8322 if ([url isCydiaSecure]) {
8323 if (UniqueID_ != nil)
8324 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8327 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8330 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8331 NSString *context([alert context]);
8333 if ([context isEqualToString:@"source"]) {
8336 NSString *href = [[alert textField] text];
8338 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8340 if (![href hasSuffix:@"/"])
8341 href_ = [href stringByAppendingString:@"/"];
8345 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8346 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8347 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8348 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8352 // XXX: this is stupid
8353 hud_ = [delegate_ addProgressHUD];
8354 [hud_ setText:UCLocalize("VERIFYING_URL")];
8355 [delegate_ retainNetworkActivityIndicator];
8364 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8365 } else if ([context isEqualToString:@"trivial"])
8366 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8367 else if ([context isEqualToString:@"urlerror"])
8368 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8369 else if ([context isEqualToString:@"warning"]) {
8383 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8388 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8390 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8391 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8392 [list_ setRowHeight:56];
8393 [(UITableView *) list_ setDataSource:self];
8394 [list_ setDelegate:self];
8395 [[self view] addSubview:list_];
8398 - (void) viewDidLoad {
8399 [super viewDidLoad];
8401 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8402 [self updateButtonsForEditingStatus:NO animated:NO];
8405 - (void) releaseSubviews {
8408 [super releaseSubviews];
8411 - (id) initWithDatabase:(Database *)database {
8412 if ((self = [super init]) != nil) {
8413 database_ = database;
8414 sources_ = [NSMutableArray arrayWithCapacity:16];
8418 - (void) reloadData {
8422 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8425 [sources_ removeAllObjects];
8426 [sources_ addObjectsFromArray:[database_ sources]];
8428 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8431 int count([sources_ count]);
8433 for (int i = 0; i != count; i++) {
8434 if ([[sources_ objectAtIndex:i] record] == nil)
8439 [list_ setEditing:NO];
8440 [self updateButtonsForEditingStatus:NO animated:NO];
8444 - (void) showAddSourcePrompt {
8445 UIAlertView *alert = [[[UIAlertView alloc]
8446 initWithTitle:UCLocalize("ENTER_APT_URL")
8449 cancelButtonTitle:UCLocalize("CANCEL")
8451 UCLocalize("ADD_SOURCE"),
8455 [alert setContext:@"source"];
8457 [alert setNumberOfRows:1];
8458 [alert addTextFieldWithValue:@"http://" label:@""];
8460 UITextInputTraits *traits = [[alert textField] textInputTraits];
8461 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8462 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8463 [traits setKeyboardType:UIKeyboardTypeURL];
8464 // XXX: UIReturnKeyDone
8465 [traits setReturnKeyType:UIReturnKeyNext];
8470 - (void) addButtonClicked {
8471 [self showAddSourcePrompt];
8474 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8475 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8476 initWithTitle:UCLocalize("ADD")
8477 style:UIBarButtonItemStylePlain
8479 action:@selector(addButtonClicked)
8480 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8482 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8483 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8484 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8486 action:@selector(editButtonClicked)
8487 ] autorelease] animated:animated];
8489 if (IsWildcat_ && !editing)
8490 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8491 initWithTitle:UCLocalize("SETTINGS")
8492 style:UIBarButtonItemStylePlain
8494 action:@selector(settingsButtonClicked)
8498 - (void) settingsButtonClicked {
8499 [delegate_ showSettings];
8502 - (void) editButtonClicked {
8503 [list_ setEditing:![list_ isEditing] animated:YES];
8505 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8511 /* Settings Controller {{{ */
8512 @interface SettingsController : CyteViewController <
8513 UITableViewDataSource,
8516 _transient Database *database_;
8517 // XXX: ok, "roledelegate_"?...
8518 _transient id roledelegate_;
8519 _H<UITableView, 2> table_;
8520 _H<UISegmentedControl> segment_;
8521 _H<UIView> container_;
8524 - (void) showDoneButton;
8525 - (void) resizeSegmentedControl;
8529 @implementation SettingsController
8532 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8534 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8535 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8536 [table_ setDelegate:self];
8537 [(UITableView *) table_ setDataSource:self];
8538 [[self view] addSubview:table_];
8540 NSArray *items = [NSArray arrayWithObjects:
8542 UCLocalize("HACKER"),
8543 UCLocalize("DEVELOPER"),
8545 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8546 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8547 [container_ addSubview:segment_];
8550 - (void) viewDidLoad {
8551 [super viewDidLoad];
8553 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8556 if ([Role_ isEqualToString:@"User"]) index = 0;
8557 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8558 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8560 [segment_ setSelectedSegmentIndex:index];
8561 [self showDoneButton];
8564 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8565 [self resizeSegmentedControl];
8568 - (void) releaseSubviews {
8573 [super releaseSubviews];
8576 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8577 if ((self = [super init]) != nil) {
8578 database_ = database;
8579 roledelegate_ = delegate;
8583 - (void) resizeSegmentedControl {
8584 CGFloat width = [[self view] frame].size.width;
8585 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8588 - (void) viewWillAppear:(BOOL)animated {
8589 [super viewWillAppear:animated];
8591 [self resizeSegmentedControl];
8594 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8595 [self resizeSegmentedControl];
8598 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8599 [self resizeSegmentedControl];
8603 NSString *role(nil);
8605 switch ([segment_ selectedSegmentIndex]) {
8606 case 0: role = @"User"; break;
8607 case 1: role = @"Hacker"; break;
8608 case 2: role = @"Developer"; break;
8613 if (![role isEqualToString:Role_]) {
8614 bool rolling(Role_ == nil);
8617 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8621 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8625 [roledelegate_ loadData];
8627 [roledelegate_ updateData];
8631 - (void) segmentChanged:(UISegmentedControl *)control {
8632 [self showDoneButton];
8635 - (void) saveAndClose {
8638 [[self navigationItem] setRightBarButtonItem:nil];
8639 [[self navigationController] dismissModalViewControllerAnimated:YES];
8642 - (void) doneButtonClicked {
8643 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8644 [spinner startAnimating];
8645 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8646 [[self navigationItem] setRightBarButtonItem:spinItem];
8648 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8651 - (void) showDoneButton {
8652 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8653 initWithTitle:UCLocalize("DONE")
8654 style:UIBarButtonItemStyleDone
8656 action:@selector(doneButtonClicked)
8657 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8660 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8661 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8665 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8669 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8670 return nil; // This method is required by the protocol.
8673 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8675 return UCLocalize("ROLE_EX");
8677 return [NSString stringWithFormat:
8678 @"%@: %@\n%@: %@\n%@: %@",
8679 UCLocalize("USER"), UCLocalize("USER_EX"),
8680 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8681 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8686 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8687 return section == 3 ? 44.0f : 0;
8690 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8691 return section == 3 ? container_ : nil;
8694 - (void) reloadData {
8697 [table_ reloadData];
8702 /* Stash Controller {{{ */
8703 @interface StashController : CyteViewController {
8704 _H<UIActivityIndicatorView> spinner_;
8705 _H<UILabel> status_;
8706 _H<UILabel> caption_;
8711 @implementation StashController
8714 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8715 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8717 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8718 CGRect spinrect = [spinner_ frame];
8719 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8720 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8721 [spinner_ setFrame:spinrect];
8722 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8723 [[self view] addSubview:spinner_];
8724 [spinner_ startAnimating];
8727 captrect.size.width = [[self view] frame].size.width;
8728 captrect.size.height = 40.0f;
8729 captrect.origin.x = 0;
8730 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8731 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8732 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8733 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8734 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8735 [caption_ setTextColor:[UIColor whiteColor]];
8736 [caption_ setBackgroundColor:[UIColor clearColor]];
8737 [caption_ setShadowColor:[UIColor blackColor]];
8738 [caption_ setTextAlignment:UITextAlignmentCenter];
8739 [[self view] addSubview:caption_];
8742 statusrect.size.width = [[self view] frame].size.width;
8743 statusrect.size.height = 30.0f;
8744 statusrect.origin.x = 0;
8745 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8746 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8747 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8748 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8749 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8750 [status_ setTextColor:[UIColor whiteColor]];
8751 [status_ setBackgroundColor:[UIColor clearColor]];
8752 [status_ setShadowColor:[UIColor blackColor]];
8753 [status_ setTextAlignment:UITextAlignmentCenter];
8754 [[self view] addSubview:status_];
8757 - (void) releaseSubviews {
8762 [super releaseSubviews];
8768 @interface CYURLCache : SDURLCache {
8773 @implementation CYURLCache
8775 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8778 else if ([event isEqualToString:@"no-cache"])
8780 else if ([event isEqualToString:@"store"])
8782 else if ([event isEqualToString:@"invalid"])
8784 else if ([event isEqualToString:@"memory"])
8786 else if ([event isEqualToString:@"disk"])
8788 else if ([event isEqualToString:@"miss"])
8791 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8795 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8796 if (NSURLResponse *response = [cached response])
8797 if (NSString *mime = [response MIMEType])
8798 if ([mime isEqualToString:@"text/cache-manifest"]) {
8799 NSURL *url([response URL]);
8802 NSLog(@"###: %@", [url absoluteString]);
8805 @synchronized (HostConfig_) {
8806 [CachedURLs_ addObject:url];
8810 [super storeCachedResponse:cached forRequest:request];
8815 @interface Cydia : UIApplication <
8816 ConfirmationControllerDelegate,
8819 UINavigationControllerDelegate,
8820 UITabBarControllerDelegate
8822 _H<UIWindow> window_;
8823 _H<CYTabBarController> tabbar_;
8824 _H<CydiaLoadingViewController> emulated_;
8826 _H<NSMutableArray> essential_;
8827 _H<NSMutableArray> broken_;
8829 Database *database_;
8831 _H<NSURL> starturl_;
8836 _H<StashController> stash_;
8845 @implementation Cydia
8847 - (void) beginUpdate {
8848 [tabbar_ beginUpdate];
8852 return [tabbar_ updating];
8856 if ([broken_ count] != 0) {
8857 int count = [broken_ count];
8859 UIAlertView *alert = [[[UIAlertView alloc]
8860 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8861 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8863 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8865 UCLocalize("TEMPORARY_IGNORE"),
8869 [alert setContext:@"fixhalf"];
8870 [alert setNumberOfRows:2];
8872 } else if (!Ignored_ && [essential_ count] != 0) {
8873 int count = [essential_ count];
8875 UIAlertView *alert = [[[UIAlertView alloc]
8876 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8877 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8879 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8881 UCLocalize("UPGRADE_ESSENTIAL"),
8882 UCLocalize("COMPLETE_UPGRADE"),
8886 [alert setContext:@"upgrade"];
8891 - (void) returnToCydia {
8895 - (void) _saveConfig {
8901 NSString *error(nil);
8903 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8905 NSError *error(nil);
8906 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8907 NSLog(@"failure to save metadata data: %@", error);
8912 NSLog(@"failure to serialize metadata: %@", error);
8919 // Navigation controller for the queuing badge.
8920 - (UINavigationController *) queueNavigationController {
8921 NSArray *controllers = [tabbar_ viewControllers];
8922 return [controllers objectAtIndex:3];
8925 - (void) unloadData {
8926 [tabbar_ unloadData];
8929 - (void) _updateData {
8933 UINavigationController *navigation = [self queueNavigationController];
8935 id queuedelegate = nil;
8936 if ([[navigation viewControllers] count] > 0)
8937 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8939 [queuedelegate queueStatusDidChange];
8940 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8943 - (void) _refreshIfPossible:(NSDate *)update {
8944 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8946 bool recently = false;
8947 if (update != nil) {
8948 NSTimeInterval interval([update timeIntervalSinceNow]);
8949 if (interval <= 0 && interval > -(15*60))
8953 // Don't automatic refresh if:
8954 // - We already refreshed recently.
8955 // - We already auto-refreshed this launch.
8956 // - Auto-refresh is disabled.
8957 if (recently || loaded_ || ManualRefresh) {
8958 // If we are cancelling, we need to make sure it knows it's already loaded.
8961 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8963 // We are going to load, so remember that.
8966 SCNetworkReachabilityFlags flags; {
8967 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8968 SCNetworkReachabilityGetFlags(reachability, &flags);
8969 CFRelease(reachability);
8972 // XXX: this elaborate mess is what Apple is using to determine this? :(
8973 // XXX: do we care if the user has to intervene? maybe that's ok?
8975 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8976 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8977 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8978 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8979 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8980 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8984 // If we can reach the server, auto-refresh!
8986 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8992 - (void) refreshIfPossible {
8993 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8996 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8997 @synchronized (self) {
8998 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8999 [hud setText:UCLocalize("RELOADING_DATA")];
9001 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9004 [self removeProgressHUD:hud];
9008 [essential_ removeAllObjects];
9009 [broken_ removeAllObjects];
9011 NSArray *packages([database_ packages]);
9012 for (Package *package in packages) {
9014 [broken_ addObject:package];
9015 if ([package upgradableAndEssential:NO]) {
9016 if ([package essential])
9017 [essential_ addObject:package];
9022 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9025 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9026 [changesItem setBadgeValue:badge];
9027 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9028 [self setApplicationIconBadgeNumber:changes];
9031 [changesItem setBadgeValue:nil];
9032 [changesItem setAnimatedBadge:NO];
9033 [self setApplicationIconBadgeNumber:0];
9039 - (void) updateData {
9045 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9048 - (void) disemulate {
9049 if (emulated_ == nil)
9052 [window_ addSubview:[tabbar_ view]];
9053 [[emulated_ view] removeFromSuperview];
9055 [window_ setUserInteractionEnabled:YES];
9058 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9059 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9061 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9063 UIViewController *parent;
9064 if (emulated_ == nil)
9073 [parent presentModalViewController:navigation animated:YES];
9076 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9077 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9079 if (navigation != nil)
9080 [navigation pushViewController:progress animated:YES];
9082 [self presentModalViewController:progress force:YES];
9084 [progress invoke:invocation withTitle:title];
9088 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9089 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9092 - (void) repairWithInvocation:(NSInvocation *)invocation {
9094 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9098 - (void) repairWithSelector:(SEL)selector {
9099 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9102 - (void) reloadData {
9103 [self reloadDataWithInvocation:nil];
9104 if ([database_ progressDelegate] == nil)
9110 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9113 - (void) addSource:(NSDictionary *) source {
9117 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9118 AddSource(href, distribution, sections);
9121 - (void) addTrivialSource:(NSString *)href {
9122 AddSource(href, @"./");
9125 - (void) updateValues {
9130 pkgProblemResolver *resolver = [database_ resolver];
9132 resolver->InstallProtect();
9133 if (!resolver->Resolve(true))
9138 // XXX: this is a really crappy way of doing this.
9139 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9140 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9141 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9142 if ([tabbar_ updating])
9143 [tabbar_ cancelUpdate];
9145 if (![database_ prepare])
9148 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9149 [page setDelegate:self];
9150 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9153 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9154 [tabbar_ presentModalViewController:confirm_ animated:YES];
9160 @synchronized (self) {
9165 - (void) clearPackage:(Package *)package {
9166 @synchronized (self) {
9173 - (void) installPackages:(NSArray *)packages {
9174 @synchronized (self) {
9175 for (Package *package in packages)
9182 - (void) installPackage:(Package *)package {
9183 @synchronized (self) {
9190 - (void) removePackage:(Package *)package {
9191 @synchronized (self) {
9198 - (void) distUpgrade {
9199 @synchronized (self) {
9200 if (![database_ upgrade])
9207 [database_ perform];
9208 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9211 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9214 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9216 [self refreshIfPossible];
9219 - (void) showSettings {
9220 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9223 - (void) retainNetworkActivityIndicator {
9224 if (activity_++ == 0)
9225 [self setNetworkActivityIndicatorVisible:YES];
9228 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9232 - (void) releaseNetworkActivityIndicator {
9233 if (--activity_ == 0)
9234 [self setNetworkActivityIndicatorVisible:NO];
9237 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9242 - (void) cancelAndClear:(bool)clear {
9243 @synchronized (self) {
9255 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9256 NSString *context([alert context]);
9258 if ([context isEqualToString:@"conffile"]) {
9259 FILE *input = [database_ input];
9260 if (button == [alert cancelButtonIndex])
9261 fprintf(input, "N\n");
9262 else if (button == [alert firstOtherButtonIndex])
9263 fprintf(input, "Y\n");
9266 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9267 } else if ([context isEqualToString:@"fixhalf"]) {
9268 if (button == [alert cancelButtonIndex]) {
9269 @synchronized (self) {
9270 for (Package *broken in (id) broken_) {
9273 NSString *id = [broken id];
9274 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9275 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9276 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9277 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9283 } else if (button == [alert firstOtherButtonIndex]) {
9284 [broken_ removeAllObjects];
9288 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9289 } else if ([context isEqualToString:@"upgrade"]) {
9290 if (button == [alert firstOtherButtonIndex]) {
9291 @synchronized (self) {
9292 for (Package *essential in (id) essential_)
9293 [essential install];
9298 } else if (button == [alert firstOtherButtonIndex] + 1) {
9300 } else if (button == [alert cancelButtonIndex]) {
9304 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9308 - (void) system:(NSString *)command {
9309 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9312 system([command UTF8String]);
9318 - (void) applicationWillSuspend {
9320 [super applicationWillSuspend];
9323 - (BOOL) isSafeToSuspend {
9326 NSLog(@"isSafeToSuspend: locked_ != 0");
9331 // Use external process status API internally.
9332 // This is probably a really bad idea.
9333 // XXX: what is the point of this? does this solve anything at all?
9334 uint64_t status = 0;
9336 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9337 notify_get_state(notify_token, &status);
9338 notify_cancel(notify_token);
9343 NSLog(@"isSafeToSuspend: status != 0");
9349 NSLog(@"isSafeToSuspend: -> true");
9354 - (void) applicationSuspend:(__GSEvent *)event {
9355 if ([self isSafeToSuspend])
9356 [super applicationSuspend:event];
9359 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9360 if ([self isSafeToSuspend])
9361 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9364 - (void) _setSuspended:(BOOL)value {
9365 if ([self isSafeToSuspend])
9366 [super _setSuspended:value];
9369 - (UIProgressHUD *) addProgressHUD {
9370 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9371 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9373 [window_ setUserInteractionEnabled:NO];
9375 UIViewController *target(tabbar_);
9376 if (UIViewController *modal = [target modalViewController])
9379 UIView *view([target view]);
9380 [view addSubview:hud];
9382 [hud showInView:[tabbar_ view]];
9388 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9391 [hud removeFromSuperview];
9392 [window_ setUserInteractionEnabled:YES];
9395 - (CyteViewController *) pageForPackage:(NSString *)name {
9396 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9399 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9400 NSString *scheme([[url scheme] lowercaseString]);
9401 if ([[url absoluteString] length] <= [scheme length] + 3)
9403 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9404 NSArray *components([path pathComponents]);
9406 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9407 return [self pageForPackage:[components objectAtIndex:1]];
9409 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9412 NSString *base([components objectAtIndex:0]);
9414 CyteViewController *controller = nil;
9416 if ([base isEqualToString:@"url"]) {
9417 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9418 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9419 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9420 } else if (!external && [components count] == 1) {
9421 if ([base isEqualToString:@"manage"]) {
9422 controller = [[[ManageController alloc] init] autorelease];
9425 if ([base isEqualToString:@"sources"]) {
9426 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9429 if ([base isEqualToString:@"home"]) {
9430 controller = [[[HomeController alloc] init] autorelease];
9433 if ([base isEqualToString:@"sections"]) {
9434 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9437 if ([base isEqualToString:@"search"]) {
9438 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9441 if ([base isEqualToString:@"changes"]) {
9442 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9445 if ([base isEqualToString:@"installed"]) {
9446 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9448 } else if ([components count] == 2) {
9449 NSString *argument = [components objectAtIndex:1];
9451 if ([base isEqualToString:@"package"]) {
9452 controller = [self pageForPackage:argument];
9455 if (!external && [base isEqualToString:@"search"]) {
9456 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9459 if (!external && [base isEqualToString:@"sections"]) {
9460 if ([argument isEqualToString:@"all"])
9462 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9465 if (!external && [base isEqualToString:@"sources"]) {
9466 if ([argument isEqualToString:@"add"]) {
9467 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9468 [(SourcesController *)controller showAddSourcePrompt];
9470 Source *source = [database_ sourceWithKey:argument];
9471 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9475 if (!external && [base isEqualToString:@"launch"]) {
9476 [self launchApplicationWithIdentifier:argument suspended:NO];
9479 } else if (!external && [components count] == 3) {
9480 NSString *arg1 = [components objectAtIndex:1];
9481 NSString *arg2 = [components objectAtIndex:2];
9483 if ([base isEqualToString:@"package"]) {
9484 if ([arg2 isEqualToString:@"settings"]) {
9485 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9486 } else if ([arg2 isEqualToString:@"files"]) {
9487 if (Package *package = [database_ packageWithName:arg1]) {
9488 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9489 [(FileTable *)controller setPackage:package];
9495 [controller setDelegate:self];
9499 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9500 CyteViewController *page([self pageForURL:url forExternal:external]);
9503 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9504 [nav setViewControllers:[NSArray arrayWithObject:page]];
9505 [tabbar_ setUnselectedViewController:nav];
9511 - (void) applicationOpenURL:(NSURL *)url {
9512 [super applicationOpenURL:url];
9517 [self openCydiaURL:url forExternal:YES];
9520 - (void) applicationWillResignActive:(UIApplication *)application {
9521 // Stop refreshing if you get a phone call or lock the device.
9522 if ([tabbar_ updating])
9523 [tabbar_ cancelUpdate];
9525 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9526 [super applicationWillResignActive:application];
9529 - (void) saveState {
9530 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9531 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9532 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9538 - (void) applicationWillTerminate:(UIApplication *)application {
9542 - (void) setConfigurationData:(NSString *)data {
9543 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9545 if (!conffile_r(data)) {
9546 lprintf("E:invalid conffile\n");
9550 NSString *ofile = conffile_r[1];
9551 //NSString *nfile = conffile_r[2];
9553 UIAlertView *alert = [[[UIAlertView alloc]
9554 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9555 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9557 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9559 UCLocalize("ACCEPT_NEW_COPY"),
9560 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9564 [alert setContext:@"conffile"];
9565 [alert setNumberOfRows:2];
9569 - (void) addStashController {
9571 stash_ = [[[StashController alloc] init] autorelease];
9572 [window_ addSubview:[stash_ view]];
9575 - (void) removeStashController {
9576 [[stash_ view] removeFromSuperview];
9582 [self setIdleTimerDisabled:YES];
9584 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9585 UpdateExternalStatus(1);
9586 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9587 UpdateExternalStatus(0);
9589 [self removeStashController];
9591 if (ExecFork() == 0) {
9592 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9593 perror("launchctl stop");
9597 - (void) setupViewControllers {
9598 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9600 NSMutableArray *items([NSMutableArray arrayWithObjects:
9601 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9602 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9603 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9604 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9608 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9609 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9611 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9614 NSMutableArray *controllers([NSMutableArray array]);
9615 for (UITabBarItem *item in items) {
9616 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9617 [controller setTabBarItem:item];
9618 [controllers addObject:controller];
9620 [tabbar_ setViewControllers:controllers];
9622 [tabbar_ setUpdateDelegate:self];
9625 - (void) applicationDidFinishLaunching:(id)unused {
9627 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9628 [self setApplicationSupportsShakeToEdit:NO];
9630 @synchronized (HostConfig_) {
9631 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9634 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9635 initWithMemoryCapacity:524288
9636 diskCapacity:10485760
9637 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9640 [CydiaWebViewController _initialize];
9642 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9644 // this would disallow http{,s} URLs from accessing this data
9645 //[WebView registerURLSchemeAsLocal:@"cydia"];
9647 Font12_ = [UIFont systemFontOfSize:12];
9648 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9649 Font14_ = [UIFont systemFontOfSize:14];
9650 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9651 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9653 essential_ = [NSMutableArray arrayWithCapacity:4];
9654 broken_ = [NSMutableArray arrayWithCapacity:4];
9656 // XXX: I really need this thing... like, seriously... I'm sorry
9657 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9659 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9660 [window_ orderFront:self];
9661 [window_ makeKey:self];
9662 [window_ setHidden:NO];
9665 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9666 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9667 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9668 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9669 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9670 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9671 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9672 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9673 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9676 [self addStashController];
9677 // XXX: this would be much cleaner as a yieldToSelector:
9678 // that way the removeStashController could happen right here inline
9679 // we also could no longer require the useless stash_ field anymore
9680 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9684 database_ = [Database sharedInstance];
9685 [database_ setDelegate:self];
9687 [window_ setUserInteractionEnabled:NO];
9688 [self setupViewControllers];
9690 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9691 [window_ addSubview:[emulated_ view]];
9693 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9697 - (NSArray *) defaultStartPages {
9698 NSMutableArray *standard = [NSMutableArray array];
9699 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9700 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9701 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9703 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9705 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9706 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9708 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9715 [window_ setUserInteractionEnabled:YES];
9716 [self showSettings];
9719 if ([emulated_ modalViewController] != nil)
9720 [emulated_ dismissModalViewControllerAnimated:YES];
9721 [window_ setUserInteractionEnabled:NO];
9724 [self reloadDataWithInvocation:nil];
9725 [self refreshIfPossible];
9730 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9731 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9732 int standardIndex = 0;
9733 NSArray *standard = [self defaultStartPages];
9740 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9741 if (valid && closed != nil) {
9742 NSTimeInterval interval([closed timeIntervalSinceNow]);
9743 // XXX: Is 15 minutes the optimal time here?
9744 if (interval > 0 && interval <= -(15*60))
9748 if (valid && [saved count] != [standard count])
9752 for (unsigned int i = 0; i < [standard count]; i++) {
9753 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9754 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9755 // but it's good enough for now.
9756 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9763 NSArray *items = nil;
9765 [tabbar_ setSelectedIndex:savedIndex];
9768 [tabbar_ setSelectedIndex:standardIndex];
9772 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9773 NSArray *stack = [items objectAtIndex:tab];
9774 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9775 NSMutableArray *current = [NSMutableArray array];
9777 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9778 NSString *addr = [stack objectAtIndex:nav];
9779 NSURL *url = [NSURL URLWithString:addr];
9780 CyteViewController *page = [self pageForURL:url forExternal:NO];
9782 [current addObject:page];
9785 [navigation setViewControllers:current];
9788 // (Try to) show the startup URL.
9789 if (starturl_ != nil) {
9790 [self openCydiaURL:starturl_ forExternal:NO];
9795 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9796 if (item != nil && IsWildcat_) {
9797 [sheet showFromBarButtonItem:item animated:YES];
9799 [sheet showInView:window_];
9803 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9804 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9805 [progress setTitle:task];
9806 [progress addProgressEvent:event];
9809 - (void) addProgressEventForTask:(NSArray *)data {
9810 CydiaProgressEvent *event([data objectAtIndex:0]);
9811 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9812 [self addProgressEvent:event forTask:task];
9815 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9816 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9822 id Alloc_(id self, SEL selector) {
9823 id object = alloc_(self, selector);
9824 lprintf("[%s]A-%p\n", self->isa->name, object);
9829 id Dealloc_(id self, SEL selector) {
9830 id object = dealloc_(self, selector);
9831 lprintf("[%s]D-%p\n", self->isa->name, object);
9835 Class $WebDefaultUIKitDelegate;
9837 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9838 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9839 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9840 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9843 static NSSet *MobilizedFiles_;
9845 static NSURL *MobilizeURL(NSURL *url) {
9846 NSString *path([url path]);
9847 if ([path hasPrefix:@"/var/root/"]) {
9848 NSString *file([path substringFromIndex:10]);
9849 if ([MobilizedFiles_ containsObject:file])
9850 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9856 Class $CFXPreferencesPropertyListSource;
9857 @class CFXPreferencesPropertyListSource;
9859 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9860 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9861 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9862 url = MobilizeURL(url);
9863 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9864 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9870 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9871 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9872 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9873 url = MobilizeURL(url);
9874 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9875 //NSLog(@"%@ %@", [url absoluteString], value);
9881 Class $NSURLConnection;
9883 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9884 NSMutableURLRequest *copy([request mutableCopy]);
9886 NSURL *url([copy URL]);
9888 NSString *href([url absoluteString]);
9889 NSString *host([url host]);
9890 NSString *scheme([[url scheme] lowercaseString]);
9892 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9894 @synchronized (HostConfig_) {
9895 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9896 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9897 [copy setHTTPShouldUsePipelining:YES];
9899 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9900 if ([control isEqualToString:@"max-age=0"])
9901 if ([CachedURLs_ containsObject:href]) {
9903 NSLog(@"~~~: %@", href);
9906 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9908 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9909 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9910 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9914 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9918 int main(int argc, char *argv[]) {
9919 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9923 UpdateExternalStatus(0);
9925 if (Class $UIDevice = objc_getClass("UIDevice")) {
9926 UIDevice *device([$UIDevice currentDevice]);
9927 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9931 UIScreen *screen([UIScreen mainScreen]);
9932 if ([screen respondsToSelector:@selector(scale)])
9933 ScreenScale_ = [screen scale];
9937 UIDevice *device([UIDevice currentDevice]);
9938 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9941 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9942 if (idiom == UIUserInterfaceIdiomPhone)
9944 else if (idiom == UIUserInterfaceIdiomPad)
9947 NSLog(@"unknown UIUserInterfaceIdiom!");
9950 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9952 HostConfig_ = [[[NSObject alloc] init] autorelease];
9953 @synchronized (HostConfig_) {
9954 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9955 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9956 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9957 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9958 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9961 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9963 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9965 MobilizedFiles_ = [NSMutableSet setWithObjects:
9966 @"Library/Preferences/com.apple.Accessibility.plist",
9967 @"Library/Preferences/com.apple.preferences.sounds.plist",
9970 /* Library Hacks {{{ */
9971 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9973 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9975 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9976 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9977 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9978 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9981 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9982 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9983 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9984 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9987 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9988 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9989 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9990 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9991 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9994 $NSURLConnection = objc_getClass("NSURLConnection");
9995 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9996 if (NSURLConnection$init$ != NULL) {
9997 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9998 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10001 /* Set Locale {{{ */
10002 Locale_ = CFLocaleCopyCurrent();
10003 Languages_ = [NSLocale preferredLanguages];
10005 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10006 //NSLog(@"%@", [Languages_ description]);
10009 if (Locale_ != NULL)
10010 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10011 else if (Languages_ != nil && [Languages_ count] != 0)
10012 lang = [[Languages_ objectAtIndex:0] UTF8String];
10014 // XXX: consider just setting to C and then falling through?
10017 if (lang != NULL) {
10018 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10019 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10022 NSLog(@"Setting Language: %s", lang);
10024 if (lang != NULL) {
10025 setenv("LANG", lang, true);
10026 std::setlocale(LC_ALL, lang);
10030 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10032 /* Parse Arguments {{{ */
10033 bool substrate(false);
10039 for (int argi(1); argi != argc; ++argi)
10040 if (strcmp(argv[argi], "--") == 0) {
10042 argv[argi] = argv[0];
10048 for (int argi(1); argi != arge; ++argi)
10049 if (strcmp(args[argi], "--substrate") == 0)
10052 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10056 App_ = [[NSBundle mainBundle] bundlePath];
10062 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10063 alloc_ = alloc->method_imp;
10064 alloc->method_imp = (IMP) &Alloc_;*/
10066 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10067 dealloc_ = dealloc->method_imp;
10068 dealloc->method_imp = (IMP) &Dealloc_;*/
10070 /* System Information {{{ */
10074 size = sizeof(maxproc);
10075 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10076 perror("sysctlbyname(\"kern.maxproc\", ?)");
10077 else if (maxproc < 64) {
10079 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10080 perror("sysctlbyname(\"kern.maxproc\", #)");
10083 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10084 char *osversion = new char[size];
10085 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10086 perror("sysctlbyname(\"kern.osversion\", ?)");
10088 System_ = [NSString stringWithUTF8String:osversion];
10090 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10091 char *machine = new char[size];
10092 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10093 perror("sysctlbyname(\"hw.machine\", ?)");
10095 Machine_ = machine;
10097 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10098 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10099 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10101 UniqueID_ = [device uniqueIdentifier];
10103 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10104 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10105 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10107 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10108 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10109 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10111 if (mcc != NULL && mnc != NULL)
10112 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10119 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10120 Build_ = [system objectForKey:@"ProductBuildVersion"];
10121 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10122 Product_ = [info objectForKey:@"SafariProductVersion"];
10123 Safari_ = [info objectForKey:@"CFBundleVersion"];
10126 /* Load Database {{{ */
10128 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10130 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10132 if (Metadata_ == NULL)
10133 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10135 Settings_ = [Metadata_ objectForKey:@"Settings"];
10137 Packages_ = [Metadata_ objectForKey:@"Packages"];
10139 Values_ = [Metadata_ objectForKey:@"Values"];
10140 Sections_ = [Metadata_ objectForKey:@"Sections"];
10141 Sources_ = [Metadata_ objectForKey:@"Sources"];
10143 Token_ = [Metadata_ objectForKey:@"Token"];
10145 Version_ = [Metadata_ objectForKey:@"Version"];
10147 @synchronized (HostConfig_) {
10148 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10152 if (Settings_ != nil)
10153 Role_ = [Settings_ objectForKey:@"Role"];
10155 if (Values_ == nil) {
10156 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10157 [Metadata_ setObject:Values_ forKey:@"Values"];
10160 if (Sections_ == nil) {
10161 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10162 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10165 if (Sources_ == nil) {
10166 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10167 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10170 if (Version_ == nil) {
10171 Version_ = [NSNumber numberWithUnsignedInt:0];
10172 [Metadata_ setObject:Version_ forKey:@"Version"];
10175 @synchronized (HostConfig_) {
10176 if (CydiaSource_ == nil) {
10177 CydiaSource_ = @"apt.saurik.com";
10178 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10182 if ([Version_ unsignedIntValue] == 0) {
10183 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10184 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10185 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10186 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10188 Version_ = [NSNumber numberWithUnsignedInt:1];
10189 [Metadata_ setObject:Version_ forKey:@"Version"];
10198 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10201 if (Packages_ != nil) {
10203 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10207 [Metadata_ removeObjectForKey:@"Packages"];
10213 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10215 #define MobileSubstrate_(name) \
10216 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10217 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10218 if (handle == NULL) \
10219 NSLog(@"%s", dlerror()); \
10222 MobileSubstrate_(Activator)
10223 MobileSubstrate_(libstatusbar)
10224 MobileSubstrate_(SimulatedKeyEvents)
10225 MobileSubstrate_(WinterBoard)
10227 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10228 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10230 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10232 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10233 unlink("/tmp/.cydia.fw");
10235 } else if (access("/User", F_OK) != 0 || version < 4) {
10238 system("/usr/libexec/cydia/firmware.sh");
10242 _assert([[NSFileManager defaultManager]
10243 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10244 withIntermediateDirectories:YES
10249 if (access("/tmp/cydia.chk", F_OK) == 0) {
10250 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10251 _assert(errno == ENOENT);
10252 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10253 _assert(errno == ENOENT);
10256 /* APT Initialization {{{ */
10257 _assert(pkgInitConfig(*_config));
10258 _assert(pkgInitSystem(*_config, _system));
10261 _config->Set("APT::Acquire::Translation", lang);
10263 // XXX: this timeout might be important :(
10264 //_config->Set("Acquire::http::Timeout", 15);
10266 _config->Set("Acquire::http::MaxParallel", 3);
10268 /* Color Choices {{{ */
10269 space_ = CGColorSpaceCreateDeviceRGB();
10271 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10272 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10273 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10274 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10275 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10276 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10277 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10278 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10279 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10281 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10282 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10284 /* UIKit Configuration {{{ */
10285 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10286 if ($GSFontSetUseLegacyFontMetrics != NULL)
10287 $GSFontSetUseLegacyFontMetrics(YES);
10289 // XXX: I have a feeling this was important
10290 //UIKeyboardDisableAutomaticAppearance();
10293 Colon_ = UCLocalize("COLON_DELIMITED");
10294 Elision_ = UCLocalize("ELISION");
10295 Error_ = UCLocalize("ERROR");
10296 Warning_ = UCLocalize("WARNING");
10299 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10301 CGColorSpaceRelease(space_);
10302 CFRelease(Locale_);