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) retainNetworkActivityIndicator;
875 - (void) releaseNetworkActivityIndicator;
876 - (void) clearPackage:(Package *)package;
877 - (void) installPackage:(Package *)package;
878 - (void) installPackages:(NSArray *)packages;
879 - (void) removePackage:(Package *)package;
880 - (void) beginUpdate;
882 - (void) distUpgrade;
886 - (void) addSource:(NSDictionary *)source;
887 - (void) addTrivialSource:(NSString *)href;
888 - (void) showSettings;
889 - (UIProgressHUD *) addProgressHUD;
890 - (void) removeProgressHUD:(UIProgressHUD *)hud;
891 - (CyteViewController *) pageForPackage:(NSString *)name;
892 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
893 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
897 /* Status Delegation {{{ */
899 public pkgAcquireStatus
902 _transient NSObject<ProgressDelegate> *delegate_;
912 void setDelegate(NSObject<ProgressDelegate> *delegate) {
913 delegate_ = delegate;
916 NSObject<ProgressDelegate> *getDelegate() const {
920 virtual bool MediaChange(std::string media, std::string drive) {
924 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
927 virtual void Fetch(pkgAcquire::ItemDesc &item) {
928 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
929 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
930 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
933 virtual void Done(pkgAcquire::ItemDesc &item) {
936 virtual void Fail(pkgAcquire::ItemDesc &item) {
938 item.Owner->Status == pkgAcquire::Item::StatIdle ||
939 item.Owner->Status == pkgAcquire::Item::StatDone
943 std::string &error(item.Owner->ErrorText);
947 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
948 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
951 virtual bool Pulse(pkgAcquire *Owner) {
952 bool value = pkgAcquireStatus::Pulse(Owner);
955 double(CurrentBytes + CurrentItems) /
956 double(TotalBytes + TotalItems)
959 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
960 [NSNumber numberWithDouble:percent], @"Percent",
962 [NSNumber numberWithDouble:CurrentBytes], @"Current",
963 [NSNumber numberWithDouble:TotalBytes], @"Total",
964 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
965 nil] waitUntilDone:YES];
967 if (value && ![delegate_ isProgressCancelled])
975 _finline bool WasCancelled() const {
979 virtual void Start() {
980 pkgAcquireStatus::Start();
981 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
984 virtual void Stop() {
985 pkgAcquireStatus::Stop();
986 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
987 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
991 /* Database Interface {{{ */
992 typedef std::map< unsigned long, _H<Source> > SourceMap;
994 @interface Database : NSObject {
1000 pkgCacheFile cache_;
1001 pkgDepCache::Policy *policy_;
1002 pkgRecords *records_;
1003 pkgProblemResolver *resolver_;
1004 pkgAcquire *fetcher_;
1006 SPtr<pkgPackageManager> manager_;
1007 pkgSourceList *list_;
1009 SourceMap sourceMap_;
1010 _H<NSMutableArray> sourceList_;
1012 CFMutableArrayRef packages_;
1014 _transient NSObject<DatabaseDelegate> *delegate_;
1015 _transient NSObject<ProgressDelegate> *progress_;
1023 std::map<const char *, _H<NSString> > sections_;
1026 + (Database *) sharedInstance;
1029 - (void) _readCydia:(NSNumber *)fd;
1030 - (void) _readStatus:(NSNumber *)fd;
1031 - (void) _readOutput:(NSNumber *)fd;
1035 - (Package *) packageWithName:(NSString *)name;
1037 - (pkgCacheFile &) cache;
1038 - (pkgDepCache::Policy *) policy;
1039 - (pkgRecords *) records;
1040 - (pkgProblemResolver *) resolver;
1041 - (pkgAcquire &) fetcher;
1042 - (pkgSourceList &) list;
1043 - (NSArray *) packages;
1044 - (NSArray *) sources;
1045 - (Source *) sourceWithKey:(NSString *)key;
1046 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1054 - (void) updateWithStatus:(Status &)status;
1056 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1058 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1059 - (NSObject<ProgressDelegate> *) progressDelegate;
1061 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1063 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1067 /* ProgressEvent Implementation {{{ */
1068 @implementation CydiaProgressEvent
1070 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1071 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1074 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1075 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1076 [event setPackage:package];
1080 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1081 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1083 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1084 NSArray *fields([description componentsSeparatedByString:@" "]);
1085 [event setItem:fields];
1087 if ([fields count] > 3) {
1088 [event setPackage:[fields objectAtIndex:2]];
1089 [event setVersion:[fields objectAtIndex:3]];
1092 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1097 + (NSArray *) _attributeKeys {
1098 return [NSArray arrayWithObjects:
1108 - (NSArray *) attributeKeys {
1109 return [[self class] _attributeKeys];
1112 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1113 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1116 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1117 if ((self = [super init]) != nil) {
1123 - (NSString *) message {
1127 - (NSString *) type {
1131 - (NSArray *) item {
1132 return (id) item_ ?: [NSNull null];
1135 - (void) setItem:(NSArray *)item {
1139 - (NSString *) package {
1140 return (id) package_ ?: [NSNull null];
1143 - (void) setPackage:(NSString *)package {
1147 - (NSString *) url {
1148 return (id) url_ ?: [NSNull null];
1151 - (void) setURL:(NSString *)url {
1155 - (void) setVersion:(NSString *)version {
1159 - (NSString *) version {
1160 return (id) version_ ?: [NSNull null];
1163 - (NSString *) compound:(NSString *)value {
1165 NSString *mode(nil); {
1166 NSString *type([self type]);
1167 if ([type isEqualToString:kCydiaProgressEventTypeError])
1168 mode = UCLocalize("ERROR");
1169 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1170 mode = UCLocalize("WARNING");
1174 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1180 - (NSString *) compoundMessage {
1181 return [self compound:[self message]];
1184 - (NSString *) compoundTitle {
1187 if (package_ == nil)
1189 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1190 title = [package name];
1194 return [self compound:title];
1200 // Cytore Definitions {{{
1201 struct PackageValue :
1204 Cytore::Offset<PackageValue> next_;
1206 uint32_t index_ : 23;
1207 uint32_t subscribed_ : 1;
1224 Cytore::Offset<PackageValue> packages_[1 << 16];
1227 static Cytore::File<MetaValue> MetaFile_;
1229 // Cytore Helper Functions {{{
1230 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1231 SplitHash nhash = { hashlittle(name, length) };
1233 PackageValue *metadata;
1235 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1236 offset: if (offset->IsNull()) {
1237 *offset = MetaFile_.New<PackageValue>(length + 1);
1238 metadata = &MetaFile_.Get(*offset);
1240 if (metadata == NULL) {
1244 metadata = new PackageValue();
1245 memset(metadata, 0, sizeof(*metadata));
1248 memcpy(metadata->name_, name, length + 1);
1249 metadata->nhash_ = nhash.u16[1];
1251 metadata = &MetaFile_.Get(*offset);
1253 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1254 offset = &metadata->next_;
1262 static void PackageImport(const void *key, const void *value, void *context) {
1263 bool &fail(*reinterpret_cast<bool *>(context));
1266 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1267 NSLog(@"failed to import package %@", key);
1271 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1272 NSDictionary *package((NSDictionary *) value);
1274 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1275 if ([subscribed boolValue] && !metadata->subscribed_)
1276 metadata->subscribed_ = true;
1278 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1279 time_t time([date timeIntervalSince1970]);
1280 if (metadata->first_ > time || metadata->first_ == 0)
1281 metadata->first_ = time;
1284 NSDate *date([package objectForKey:@"LastSeen"]);
1285 NSString *version([package objectForKey:@"LastVersion"]);
1287 if (date != nil && version != nil) {
1288 time_t time([date timeIntervalSince1970]);
1289 if (metadata->last_ < time || metadata->last_ == 0)
1290 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1291 size_t length(strlen(buffer));
1292 uint16_t vhash(hashlittle(buffer, length));
1294 size_t capped(std::min<size_t>(8, length));
1295 char *latest(buffer + length - capped);
1297 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1298 metadata->vhash_ = vhash;
1300 metadata->last_ = time;
1306 /* Source Class {{{ */
1307 @interface Source : NSObject {
1308 CYString depiction_;
1309 CYString description_;
1315 CYString distribution_;
1321 _H<NSString> authority_;
1323 CYString defaultIcon_;
1325 _H<NSDictionary> record_;
1329 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1331 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1333 - (NSString *) depictionForPackage:(NSString *)package;
1334 - (NSString *) supportForPackage:(NSString *)package;
1336 - (NSDictionary *) record;
1340 - (NSString *) distribution;
1341 - (NSString *) type;
1343 - (NSString *) base;
1346 - (NSString *) host;
1348 - (NSString *) name;
1349 - (NSString *) shortDescription;
1350 - (NSString *) label;
1351 - (NSString *) origin;
1352 - (NSString *) version;
1354 - (NSString *) defaultIcon;
1358 @implementation Source
1362 distribution_.clear();
1367 description_.clear();
1373 defaultIcon_.clear();
1380 + (NSString *) webScriptNameForSelector:(SEL)selector {
1382 else if (selector == @selector(addSection:))
1383 return @"addSection";
1384 else if (selector == @selector(removeSection:))
1385 return @"removeSection";
1386 else if (selector == @selector(remove))
1392 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1393 return [self webScriptNameForSelector:selector] == nil;
1396 + (NSArray *) _attributeKeys {
1397 return [NSArray arrayWithObjects:
1405 @"shortDescription",
1413 - (NSArray *) attributeKeys {
1414 return [[self class] _attributeKeys];
1417 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1418 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1421 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1424 trusted_ = index->IsTrusted();
1426 uri_.set(pool, index->GetURI());
1427 distribution_.set(pool, index->GetDist());
1428 type_.set(pool, index->GetType());
1430 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1431 if (dindex != NULL) {
1432 base_.set(pool, dindex->MetaIndexURI(""));
1435 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1438 pkgTagFile tags(&fd);
1440 pkgTagSection section;
1447 {"default-icon", &defaultIcon_},
1448 {"depiction", &depiction_},
1449 {"description", &description_},
1451 {"origin", &origin_},
1452 {"support", &support_},
1453 {"version", &version_},
1456 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1457 const char *start, *end;
1459 if (section.Find(names[i].name_, start, end)) {
1460 CYString &value(*names[i].value_);
1461 value.set(pool, start, end - start);
1467 record_ = [Sources_ objectForKey:[self key]];
1469 NSURL *url([NSURL URLWithString:uri_]);
1473 host_ = [host_ lowercaseString];
1478 authority_ = [url path];
1481 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1482 if ((self = [super init]) != nil) {
1483 [self setMetaIndex:index inPool:pool];
1487 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1488 NSDictionary *lhr = [self record];
1489 NSDictionary *rhr = [source record];
1492 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1494 NSString *lhs = [self name];
1495 NSString *rhs = [source name];
1497 if ([lhs length] != 0 && [rhs length] != 0) {
1498 unichar lhc = [lhs characterAtIndex:0];
1499 unichar rhc = [rhs characterAtIndex:0];
1501 if (isalpha(lhc) && !isalpha(rhc))
1502 return NSOrderedAscending;
1503 else if (!isalpha(lhc) && isalpha(rhc))
1504 return NSOrderedDescending;
1507 return [lhs compare:rhs options:LaxCompareOptions_];
1510 - (NSString *) depictionForPackage:(NSString *)package {
1511 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1514 - (NSString *) supportForPackage:(NSString *)package {
1515 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1518 - (NSArray *) sections {
1519 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1522 - (void) _addSection:(NSString *)section {
1525 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1526 if (![sections containsObject:section]) {
1527 [sections addObject:section];
1531 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1536 - (bool) addSection:(NSString *)section {
1540 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1544 - (void) _removeSection:(NSString *)section {
1548 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1549 if ([sections containsObject:section]) {
1550 [sections removeObject:section];
1555 - (bool) removeSection:(NSString *)section {
1559 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1564 [Sources_ removeObjectForKey:[self key]];
1569 bool value(record_ != nil);
1570 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1574 - (NSDictionary *) record {
1582 - (NSString *) uri {
1586 - (NSString *) distribution {
1587 return distribution_;
1590 - (NSString *) type {
1594 - (NSString *) base {
1598 - (NSString *) key {
1599 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1602 - (NSString *) host {
1606 - (NSString *) name {
1607 return origin_.empty() ? (id) authority_ : origin_;
1610 - (NSString *) shortDescription {
1611 return description_;
1614 - (NSString *) label {
1615 return label_.empty() ? (id) authority_ : label_;
1618 - (NSString *) origin {
1622 - (NSString *) version {
1626 - (NSString *) defaultIcon {
1627 return defaultIcon_;
1632 /* CydiaOperation Class {{{ */
1633 @interface CydiaOperation : NSObject {
1634 _H<NSString> operator_;
1635 _H<NSString> value_;
1638 - (NSString *) operator;
1639 - (NSString *) value;
1643 @implementation CydiaOperation
1645 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1646 if ((self = [super init]) != nil) {
1647 operator_ = [NSString stringWithUTF8String:_operator];
1648 value_ = [NSString stringWithUTF8String:value];
1652 + (NSArray *) _attributeKeys {
1653 return [NSArray arrayWithObjects:
1659 - (NSArray *) attributeKeys {
1660 return [[self class] _attributeKeys];
1663 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1664 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1667 - (NSString *) operator {
1671 - (NSString *) value {
1677 /* CydiaClause Class {{{ */
1678 @interface CydiaClause : NSObject {
1679 _H<NSString> package_;
1680 _H<CydiaOperation> version_;
1683 - (NSString *) package;
1684 - (CydiaOperation *) version;
1688 @implementation CydiaClause
1690 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1691 if ((self = [super init]) != nil) {
1692 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1694 if (const char *version = dep.TargetVer())
1695 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1697 version_ = (id) [NSNull null];
1701 + (NSArray *) _attributeKeys {
1702 return [NSArray arrayWithObjects:
1708 - (NSArray *) attributeKeys {
1709 return [[self class] _attributeKeys];
1712 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1713 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1716 - (NSString *) package {
1720 - (CydiaOperation *) version {
1726 /* CydiaRelation Class {{{ */
1727 @interface CydiaRelation : NSObject {
1728 _H<NSString> relationship_;
1729 _H<NSMutableArray> clauses_;
1732 - (NSString *) relationship;
1733 - (NSArray *) clauses;
1737 @implementation CydiaRelation
1739 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1740 if ((self = [super init]) != nil) {
1741 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1742 clauses_ = [NSMutableArray arrayWithCapacity:8];
1744 pkgCache::DepIterator start;
1745 pkgCache::DepIterator end;
1746 dep.GlobOr(start, end); // ++dep
1749 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1751 // yes, seriously. (wtf?)
1759 + (NSArray *) _attributeKeys {
1760 return [NSArray arrayWithObjects:
1766 - (NSArray *) attributeKeys {
1767 return [[self class] _attributeKeys];
1770 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1771 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1774 - (NSString *) relationship {
1775 return relationship_;
1778 - (NSArray *) clauses {
1782 - (void) addClause:(CydiaClause *)clause {
1783 [clauses_ addObject:clause];
1788 /* Package Class {{{ */
1789 struct ParsedPackage {
1794 CYString depiction_;
1804 @interface Package : NSObject {
1807 uint32_t essential_ : 1;
1808 uint32_t obsolete_ : 1;
1809 uint32_t ignored_ : 1;
1815 _transient Database *database_;
1817 pkgCache::VerIterator version_;
1818 pkgCache::PkgIterator iterator_;
1819 pkgCache::VerFileIterator file_;
1825 CYString installed_;
1827 const char *section_;
1828 _transient NSString *section$_;
1832 PackageValue *metadata_;
1833 ParsedPackage *parsed_;
1835 _H<NSMutableArray> tags_;
1838 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1839 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1841 - (pkgCache::PkgIterator) iterator;
1844 - (NSString *) section;
1845 - (NSString *) simpleSection;
1847 - (NSString *) longSection;
1848 - (NSString *) shortSection;
1852 - (MIMEAddress *) maintainer;
1854 - (NSString *) longDescription;
1855 - (NSString *) shortDescription;
1858 - (PackageValue *) metadata;
1861 - (bool) subscribed;
1862 - (bool) setSubscribed:(bool)subscribed;
1866 - (NSString *) latest;
1867 - (NSString *) installed;
1868 - (BOOL) uninstalled;
1871 - (BOOL) upgradableAndEssential:(BOOL)essential;
1874 - (BOOL) unfiltered;
1878 - (BOOL) halfConfigured;
1879 - (BOOL) halfInstalled;
1881 - (NSString *) mode;
1884 - (NSString *) name;
1886 - (NSString *) homepage;
1887 - (NSString *) depiction;
1888 - (MIMEAddress *) author;
1890 - (NSString *) support;
1892 - (NSArray *) files;
1893 - (NSArray *) warnings;
1894 - (NSArray *) applications;
1896 - (Source *) source;
1899 - (BOOL) matches:(NSArray *)query;
1901 - (bool) hasSupportingRole;
1902 - (BOOL) hasTag:(NSString *)tag;
1903 - (NSString *) primaryPurpose;
1904 - (NSArray *) purposes;
1905 - (bool) isCommercial;
1907 - (void) setIndex:(size_t)index;
1909 - (CYString &) cyname;
1911 - (uint32_t) compareBySection:(NSArray *)sections;
1916 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1917 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1918 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1919 - (bool) isVisibleInSection:(NSString *)section;
1920 - (bool) isVisibleInSource:(Source *)source;
1924 uint32_t PackageChangesRadix(Package *self, void *) {
1929 uint32_t timestamp : 30;
1930 uint32_t ignored : 1;
1931 uint32_t upgradable : 1;
1935 bool upgradable([self upgradableAndEssential:YES]);
1936 value.bits.upgradable = upgradable ? 1 : 0;
1939 value.bits.timestamp = 0;
1940 value.bits.ignored = [self ignored] ? 0 : 1;
1941 value.bits.upgradable = 1;
1943 value.bits.timestamp = [self seen] >> 2;
1944 value.bits.ignored = 0;
1945 value.bits.upgradable = 0;
1948 return _not(uint32_t) - value.key;
1951 uint32_t PackagePrefixRadix(Package *self, void *context) {
1952 size_t offset(reinterpret_cast<size_t>(context));
1953 CYString &name([self cyname]);
1955 size_t size(name.size());
1958 char *text(name.data());
1961 if (!isdigit(text[0]))
1965 while (size != digits && isdigit(text[digits]))
1973 if (offset == 0 && zeros != 0) {
1974 memset(data, '0', zeros);
1975 memcpy(data + zeros, text, 4 - zeros);
1977 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1978 if (size <= offset - zeros)
1981 text += offset - zeros;
1982 size -= offset - zeros;
1985 memcpy(data, text, 4);
1987 memcpy(data, text, size);
1988 memset(data + size, 0, 4 - size);
1991 for (size_t i(0); i != 4; ++i)
1992 if (isalpha(data[i]))
2000 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2002 /* XXX: ntohl may be more honest */
2003 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2006 CYString &(*PackageName)(Package *self, SEL sel);
2008 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2009 _profile(PackageNameCompare)
2010 CYString &lhi(PackageName(lhs, @selector(cyname)));
2011 CYString &rhi(PackageName(rhs, @selector(cyname)));
2012 CFStringRef lhn(lhi), rhn(rhi);
2015 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2016 else if (rhn == NULL)
2017 return NSOrderedDescending;
2019 _profile(PackageNameCompare$NumbersLast)
2020 if (!lhi.empty() && !rhi.empty()) {
2021 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2022 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2023 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2024 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2025 return lha ? NSOrderedAscending : NSOrderedDescending;
2029 CFIndex length = CFStringGetLength(lhn);
2031 _profile(PackageNameCompare$Compare)
2032 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2037 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2038 return PackageNameCompare(*lhs, *rhs, context);
2041 struct PackageNameOrdering :
2042 std::binary_function<Package *, Package *, bool>
2044 _finline bool operator ()(Package *lhs, Package *rhs) const {
2045 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2049 @implementation Package
2051 - (NSString *) description {
2052 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2056 if (parsed_ != NULL)
2061 + (NSString *) webScriptNameForSelector:(SEL)selector {
2063 else if (selector == @selector(clear))
2065 else if (selector == @selector(getField:))
2067 else if (selector == @selector(hasTag:))
2069 else if (selector == @selector(install))
2071 else if (selector == @selector(remove))
2077 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2078 return [self webScriptNameForSelector:selector] == nil;
2081 + (NSArray *) _attributeKeys {
2082 return [NSArray arrayWithObjects:
2101 @"shortDescription",
2114 - (NSArray *) attributeKeys {
2115 return [[self class] _attributeKeys];
2118 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2119 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2122 - (NSArray *) relations {
2123 @synchronized (database_) {
2124 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2125 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2126 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2130 - (NSString *) getField:(NSString *)name {
2131 @synchronized (database_) {
2132 if ([database_ era] != era_ || file_.end())
2135 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2137 const char *start, *end;
2138 if (!parser.Find([name UTF8String], start, end))
2139 return (NSString *) [NSNull null];
2141 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2145 if (parsed_ != NULL)
2147 @synchronized (database_) {
2148 if ([database_ era] != era_ || file_.end())
2151 ParsedPackage *parsed(new ParsedPackage);
2154 _profile(Package$parse)
2155 pkgRecords::Parser *parser;
2157 _profile(Package$parse$Lookup)
2158 parser = &[database_ records]->Lookup(file_);
2163 _profile(Package$parse$Find)
2168 {"icon", &parsed->icon_},
2169 {"depiction", &parsed->depiction_},
2170 {"homepage", &parsed->homepage_},
2171 {"website", &website},
2172 {"bugs", &parsed->bugs_},
2173 {"support", &parsed->support_},
2174 {"sponsor", &parsed->sponsor_},
2175 {"author", &parsed->author_},
2178 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2179 const char *start, *end;
2181 if (parser->Find(names[i].name_, start, end)) {
2182 CYString &value(*names[i].value_);
2183 _profile(Package$parse$Value)
2184 value.set(pool_, start, end - start);
2190 _profile(Package$parse$Tagline)
2191 const char *start, *end;
2192 if (parser->ShortDesc(start, end)) {
2193 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2196 while (stop != start && stop[-1] == '\r')
2198 parsed->tagline_.set(pool_, start, stop - start);
2202 _profile(Package$parse$Retain)
2203 if (parsed->homepage_.empty())
2204 parsed->homepage_ = website;
2205 if (parsed->homepage_ == parsed->depiction_)
2206 parsed->homepage_.clear();
2211 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2212 if ((self = [super init]) != nil) {
2213 _profile(Package$initWithVersion)
2216 database_ = database;
2217 era_ = [database era];
2221 pkgCache::PkgIterator iterator(version.ParentPkg());
2222 iterator_ = iterator;
2224 _profile(Package$initWithVersion$Version)
2225 if (!version_.end())
2226 file_ = version_.FileList();
2228 pkgCache &cache([database_ cache]);
2229 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2233 _profile(Package$initWithVersion$Cache)
2234 name_.set(NULL, iterator.Display());
2236 latest_.set(NULL, StripVersion_(version_.VerStr()));
2238 pkgCache::VerIterator current(iterator.CurrentVer());
2240 installed_.set(NULL, StripVersion_(current.VerStr()));
2243 _profile(Package$initWithVersion$Tags)
2244 pkgCache::TagIterator tag(iterator.TagList());
2246 tags_ = [NSMutableArray arrayWithCapacity:8];
2248 const char *name(tag.Name());
2249 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2251 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2252 if (strcmp(name + 6, "enduser") == 0)
2254 else if (strcmp(name + 6, "hacker") == 0)
2256 else if (strcmp(name + 6, "developer") == 0)
2258 else if (strcmp(name + 6, "cydia") == 0)
2264 if (strncmp(name, "cydia::", 7) == 0) {
2265 if (strcmp(name + 7, "essential") == 0)
2267 else if (strcmp(name + 7, "obsolete") == 0)
2272 } while (!tag.end());
2276 _profile(Package$initWithVersion$Metadata)
2277 const char *mixed(iterator.Name());
2278 size_t size(strlen(mixed));
2279 char lower[size + 1];
2281 for (size_t i(0); i != size; ++i)
2282 lower[i] = mixed[i] | 0x20;
2285 PackageValue *metadata(PackageFind(lower, size));
2286 metadata_ = metadata;
2288 id_.set(NULL, metadata->name_, size);
2290 const char *latest(version_.VerStr());
2291 size_t length(strlen(latest));
2293 uint16_t vhash(hashlittle(latest, length));
2295 size_t capped(std::min<size_t>(8, length));
2296 latest = latest + length - capped;
2298 if (metadata->first_ == 0)
2299 metadata->first_ = now_;
2301 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2302 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2303 metadata->vhash_ = vhash;
2304 metadata->last_ = now_;
2305 } else if (metadata->last_ == 0)
2306 metadata->last_ = metadata->first_;
2309 _profile(Package$initWithVersion$Section)
2310 section_ = iterator.Section();
2313 _profile(Package$initWithVersion$Flags)
2314 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2315 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2320 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2321 pkgCache::VerIterator version;
2323 _profile(Package$packageWithIterator$GetCandidateVer)
2324 version = [database policy]->GetCandidateVer(iterator);
2332 _profile(Package$packageWithIterator$Allocate)
2333 package = [Package allocWithZone:zone];
2336 _profile(Package$packageWithIterator$Initialize)
2338 initWithVersion:version
2345 _profile(Package$packageWithIterator$Autorelease)
2346 package = [package autorelease];
2352 - (pkgCache::PkgIterator) iterator {
2356 - (NSString *) section {
2357 if (section$_ == nil) {
2358 if (section_ == NULL)
2361 _profile(Package$section$mappedSectionForPointer)
2362 section$_ = [database_ mappedSectionForPointer:section_];
2367 - (NSString *) simpleSection {
2368 if (NSString *section = [self section])
2369 return Simplify(section);
2374 - (NSString *) longSection {
2375 return LocalizeSection([self section]);
2378 - (NSString *) shortSection {
2379 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2382 - (NSString *) uri {
2385 pkgIndexFile *index;
2386 pkgCache::PkgFileIterator file(file_.File());
2387 if (![database_ list].FindIndex(file, index))
2389 return [NSString stringWithUTF8String:iterator_->Path];
2390 //return [NSString stringWithUTF8String:file.Site()];
2391 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2395 - (MIMEAddress *) maintainer {
2396 @synchronized (database_) {
2397 if ([database_ era] != era_ || file_.end())
2400 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2401 const std::string &maintainer(parser->Maintainer());
2402 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2406 @synchronized (database_) {
2407 if ([database_ era] != era_ || version_.end())
2410 return version_->InstalledSize;
2413 - (NSString *) longDescription {
2414 @synchronized (database_) {
2415 if ([database_ era] != era_ || file_.end())
2418 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2419 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2421 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2422 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2423 if ([lines count] < 2)
2426 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2427 for (size_t i(1), e([lines count]); i != e; ++i) {
2428 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2429 [trimmed addObject:trim];
2432 return [trimmed componentsJoinedByString:@"\n"];
2435 - (NSString *) shortDescription {
2436 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2440 _profile(Package$index)
2441 CFStringRef name((CFStringRef) [self name]);
2442 if (CFStringGetLength(name) == 0)
2444 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2445 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2447 return toupper(character);
2451 - (PackageValue *) metadata {
2456 PackageValue *metadata([self metadata]);
2457 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2460 - (bool) subscribed {
2461 return [self metadata]->subscribed_;
2464 - (bool) setSubscribed:(bool)subscribed {
2465 PackageValue *metadata([self metadata]);
2466 if (metadata->subscribed_ == subscribed)
2468 metadata->subscribed_ = subscribed;
2476 - (NSString *) latest {
2480 - (NSString *) installed {
2484 - (BOOL) uninstalled {
2485 return installed_.empty();
2489 return !version_.end();
2492 - (BOOL) upgradableAndEssential:(BOOL)essential {
2493 _profile(Package$upgradableAndEssential)
2494 pkgCache::VerIterator current(iterator_.CurrentVer());
2496 return essential && essential_;
2498 return !version_.end() && version_ != current;
2502 - (BOOL) essential {
2507 return [database_ cache][iterator_].InstBroken();
2510 - (BOOL) unfiltered {
2511 _profile(Package$unfiltered$obsolete)
2512 if (_unlikely(obsolete_))
2516 _profile(Package$unfiltered$hasSupportingRole)
2517 if (_unlikely(![self hasSupportingRole]))
2525 if (![self unfiltered])
2530 _profile(Package$visible$section)
2531 section = [self section];
2534 _profile(Package$visible$isSectionVisible)
2535 if (!isSectionVisible(section))
2543 unsigned char current(iterator_->CurrentState);
2544 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2547 - (BOOL) halfConfigured {
2548 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2551 - (BOOL) halfInstalled {
2552 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2556 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2557 return state.Mode != pkgDepCache::ModeKeep;
2560 - (NSString *) mode {
2561 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2563 switch (state.Mode) {
2564 case pkgDepCache::ModeDelete:
2565 if ((state.iFlags & pkgDepCache::Purge) != 0)
2569 case pkgDepCache::ModeKeep:
2570 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2571 return @"REINSTALL";
2572 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2576 case pkgDepCache::ModeInstall:
2577 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2578 return @"REINSTALL";
2579 else*/ switch (state.Status) {
2581 return @"DOWNGRADE";
2587 return @"NEW_INSTALL";
2598 - (NSString *) name {
2599 return name_.empty() ? id_ : name_;
2602 - (UIImage *) icon {
2603 NSString *section = [self simpleSection];
2606 if (parsed_ != NULL)
2607 if (NSString *href = parsed_->icon_)
2608 if ([href hasPrefix:@"file:///"])
2609 // XXX: correct escaping
2610 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2611 if (icon == nil) if (section != nil)
2612 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2613 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2614 if ([dicon hasPrefix:@"file:///"])
2615 // XXX: correct escaping
2616 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2618 icon = [UIImage applicationImageNamed:@"unknown.png"];
2622 - (NSString *) homepage {
2623 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2626 - (NSString *) depiction {
2627 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2630 - (MIMEAddress *) sponsor {
2631 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2634 - (MIMEAddress *) author {
2635 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2638 - (NSString *) support {
2639 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2642 - (NSArray *) files {
2643 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2644 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2647 fin.open([path UTF8String]);
2652 while (std::getline(fin, line))
2653 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2658 - (NSString *) state {
2659 @synchronized (database_) {
2660 if ([database_ era] != era_ || file_.end())
2663 switch (iterator_->CurrentState) {
2664 case pkgCache::State::NotInstalled:
2665 return @"NotInstalled";
2666 case pkgCache::State::UnPacked:
2668 case pkgCache::State::HalfConfigured:
2669 return @"HalfConfigured";
2670 case pkgCache::State::HalfInstalled:
2671 return @"HalfInstalled";
2672 case pkgCache::State::ConfigFiles:
2673 return @"ConfigFiles";
2674 case pkgCache::State::Installed:
2675 return @"Installed";
2676 case pkgCache::State::TriggersAwaited:
2677 return @"TriggersAwaited";
2678 case pkgCache::State::TriggersPending:
2679 return @"TriggersPending";
2682 return (NSString *) [NSNull null];
2685 - (NSString *) selection {
2686 @synchronized (database_) {
2687 if ([database_ era] != era_ || file_.end())
2690 switch (iterator_->SelectedState) {
2691 case pkgCache::State::Unknown:
2693 case pkgCache::State::Install:
2695 case pkgCache::State::Hold:
2697 case pkgCache::State::DeInstall:
2698 return @"DeInstall";
2699 case pkgCache::State::Purge:
2703 return (NSString *) [NSNull null];
2706 - (NSArray *) warnings {
2707 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2708 const char *name(iterator_.Name());
2710 size_t length(strlen(name));
2711 if (length < 2) invalid:
2712 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2713 else for (size_t i(0); i != length; ++i)
2715 /* XXX: technically this is not allowed */
2716 (name[i] < 'A' || name[i] > 'Z') &&
2717 (name[i] < 'a' || name[i] > 'z') &&
2718 (name[i] < '0' || name[i] > '9') &&
2719 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2722 if (strcmp(name, "cydia") != 0) {
2725 bool _private = false;
2728 bool repository = [[self section] isEqualToString:@"Repositories"];
2730 if (NSArray *files = [self files])
2731 for (NSString *file in files)
2732 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2734 else if (!user && [file isEqualToString:@"/User"])
2736 else if (!_private && [file isEqualToString:@"/private"])
2738 else if (!stash && [file isEqualToString:@"/var/stash"])
2741 /* XXX: this is not sensitive enough. only some folders are valid. */
2742 if (cydia && !repository)
2743 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2745 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2747 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2749 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2752 return [warnings count] == 0 ? nil : warnings;
2755 - (NSArray *) applications {
2756 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2758 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2760 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2761 if (NSArray *files = [self files])
2762 for (NSString *file in files)
2763 if (application_r(file)) {
2764 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2765 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2766 if ([id isEqualToString:me])
2769 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2771 display = application_r[1];
2773 NSString *bundle([file stringByDeletingLastPathComponent]);
2774 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2775 if (icon == nil || [icon length] == 0)
2777 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2779 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2780 [applications addObject:application];
2782 [application addObject:id];
2783 [application addObject:display];
2784 [application addObject:url];
2787 return [applications count] == 0 ? nil : applications;
2790 - (Source *) source {
2791 if (source_ == nil) {
2792 @synchronized (database_) {
2793 if ([database_ era] != era_ || file_.end())
2794 source_ = (Source *) [NSNull null];
2796 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2800 return source_ == (Source *) [NSNull null] ? nil : source_;
2807 - (BOOL) matches:(NSArray *)query {
2808 if (query == nil || [query count] == 0)
2819 string = [self name];
2820 length = [string length];
2822 for (NSString *term in query) {
2823 range = [string rangeOfString:term options:MatchCompareOptions_];
2824 if (range.location != NSNotFound)
2825 rank_ -= 6 * 1000000 / length;
2830 length = [string length];
2832 for (NSString *term in query) {
2833 range = [string rangeOfString:term options:MatchCompareOptions_];
2834 if (range.location != NSNotFound)
2835 rank_ -= 6 * 1000000 / length;
2839 string = [self shortDescription];
2840 length = [string length];
2841 NSUInteger stop(std::min<NSUInteger>(length, 100));
2843 for (NSString *term in query) {
2844 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2845 if (range.location != NSNotFound)
2846 rank_ -= 2 * 100000;
2852 - (bool) hasSupportingRole {
2857 if ([Role_ isEqualToString:@"User"])
2861 if ([Role_ isEqualToString:@"Hacker"])
2865 if ([Role_ isEqualToString:@"Developer"])
2870 - (NSArray *) tags {
2874 - (BOOL) hasTag:(NSString *)tag {
2875 return tags_ == nil ? NO : [tags_ containsObject:tag];
2878 - (NSString *) primaryPurpose {
2879 for (NSString *tag in (NSArray *) tags_)
2880 if ([tag hasPrefix:@"purpose::"])
2881 return [tag substringFromIndex:9];
2885 - (NSArray *) purposes {
2886 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2887 for (NSString *tag in (NSArray *) tags_)
2888 if ([tag hasPrefix:@"purpose::"])
2889 [purposes addObject:[tag substringFromIndex:9]];
2890 return [purposes count] == 0 ? nil : purposes;
2893 - (bool) isCommercial {
2894 return [self hasTag:@"cydia::commercial"];
2897 - (void) setIndex:(size_t)index {
2898 if (metadata_->index_ != index)
2899 metadata_->index_ = index;
2902 - (CYString &) cyname {
2903 return name_.empty() ? id_ : name_;
2906 - (uint32_t) compareBySection:(NSArray *)sections {
2907 NSString *section([self section]);
2908 for (size_t i(0), e([sections count]); i != e; ++i) {
2909 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2913 return _not(uint32_t);
2917 @synchronized (database_) {
2918 pkgProblemResolver *resolver = [database_ resolver];
2919 resolver->Clear(iterator_);
2921 pkgCacheFile &cache([database_ cache]);
2922 cache->SetReInstall(iterator_, false);
2923 cache->MarkKeep(iterator_, false);
2927 @synchronized (database_) {
2928 pkgProblemResolver *resolver = [database_ resolver];
2929 resolver->Clear(iterator_);
2930 resolver->Protect(iterator_);
2932 pkgCacheFile &cache([database_ cache]);
2933 cache->SetReInstall(iterator_, false);
2934 cache->MarkInstall(iterator_, false);
2936 pkgDepCache::StateCache &state((*cache)[iterator_]);
2937 if (!state.Install())
2938 cache->SetReInstall(iterator_, true);
2942 @synchronized (database_) {
2943 pkgProblemResolver *resolver = [database_ resolver];
2944 resolver->Clear(iterator_);
2945 resolver->Remove(iterator_);
2946 resolver->Protect(iterator_);
2948 pkgCacheFile &cache([database_ cache]);
2949 cache->SetReInstall(iterator_, false);
2950 cache->MarkDelete(iterator_, true);
2953 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2954 _profile(Package$isUnfilteredAndSearchedForBy)
2957 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2958 value &= [self unfiltered];
2961 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2962 value &= [self matches:query];
2969 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2970 if ([search length] == 0)
2973 _profile(Package$isUnfilteredAndSelectedForBy)
2976 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2977 value &= [self unfiltered];
2980 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2981 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2988 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2989 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2992 - (bool) isVisibleInSection:(NSString *)name {
2993 NSString *section([self section]);
2997 section == nil && [name length] == 0 ||
2998 [name isEqualToString:section]
2999 ) && [self visible];
3002 - (bool) isVisibleInSource:(Source *)source {
3003 return [self source] == source && [self visible];
3008 /* Section Class {{{ */
3009 @interface Section : NSObject {
3014 _H<NSString> localized_;
3017 - (NSComparisonResult) compareByLocalized:(Section *)section;
3018 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3019 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3020 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3021 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3022 - (NSString *) name;
3029 - (void) addToCount;
3031 - (void) setCount:(size_t)count;
3032 - (NSString *) localized;
3036 @implementation Section
3038 - (NSComparisonResult) compareByLocalized:(Section *)section {
3039 NSString *lhs(localized_);
3040 NSString *rhs([section localized]);
3042 /*if ([lhs length] != 0 && [rhs length] != 0) {
3043 unichar lhc = [lhs characterAtIndex:0];
3044 unichar rhc = [rhs characterAtIndex:0];
3046 if (isalpha(lhc) && !isalpha(rhc))
3047 return NSOrderedAscending;
3048 else if (!isalpha(lhc) && isalpha(rhc))
3049 return NSOrderedDescending;
3052 return [lhs compare:rhs options:LaxCompareOptions_];
3055 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3056 if ((self = [self initWithName:name localize:NO]) != nil) {
3057 if (localized != nil)
3058 localized_ = localized;
3062 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3063 return [self initWithName:name row:0 localize:localize];
3066 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3067 if ((self = [super init]) != nil) {
3072 localized_ = LocalizeSection(name_);
3076 /* XXX: localize the index thingees */
3077 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3078 if ((self = [super init]) != nil) {
3079 name_ = [NSString stringWithCharacters:&index length:1];
3085 - (NSString *) name {
3105 - (void) addToCount {
3109 - (void) setCount:(size_t)count {
3113 - (NSString *) localized {
3120 static NSString *Colon_;
3122 static NSString *Error_;
3123 static NSString *Warning_;
3125 class CydiaLogCleaner :
3126 public pkgArchiveCleaner
3129 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3134 /* Database Implementation {{{ */
3135 @implementation Database
3137 + (Database *) sharedInstance {
3138 static _H<Database> instance;
3139 if (instance == nil)
3140 instance = [[[Database alloc] init] autorelease];
3148 - (void) releasePackages {
3149 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3150 CFArrayRemoveAllValues(packages_);
3154 // XXX: actually implement this thing
3156 [self releasePackages];
3157 apr_pool_destroy(pool_);
3158 NSRecycleZone(zone_);
3162 - (void) _readCydia:(NSNumber *)fd {
3163 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3164 std::istream is(&ib);
3167 static Pcre finish_r("^finish:([^:]*)$");
3169 while (std::getline(is, line)) {
3170 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3172 const char *data(line.c_str());
3173 size_t size = line.size();
3174 lprintf("C:%s\n", data);
3176 if (finish_r(data, size)) {
3177 NSString *finish = finish_r[1];
3178 int index = [Finishes_ indexOfObject:finish];
3179 if (index != INT_MAX && index > Finish_)
3189 - (void) _readStatus:(NSNumber *)fd {
3190 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3191 std::istream is(&ib);
3194 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3195 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
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("S:%s\n", data);
3204 if (conffile_r(data, size)) {
3205 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3206 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3207 } else if (strncmp(data, "status: ", 8) == 0) {
3208 // status: <package>: {unpacked,half-configured,installed}
3209 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3210 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3211 } else if (strncmp(data, "processing: ", 12) == 0) {
3212 // processing: configure: config-test
3213 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3214 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3215 } else if (pmstatus_r(data, size)) {
3216 std::string type([pmstatus_r[1] UTF8String]);
3218 NSString *package = pmstatus_r[2];
3219 if ([package isEqualToString:@"dpkg-exec"])
3222 float percent([pmstatus_r[3] floatValue]);
3223 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3225 NSString *string = pmstatus_r[4];
3227 if (type == "pmerror") {
3228 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3229 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3230 } else if (type == "pmstatus") {
3231 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3232 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3233 } else if (type == "pmconffile")
3234 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3236 lprintf("E:unknown pmstatus\n");
3238 lprintf("E:unknown status\n");
3246 - (void) _readOutput:(NSNumber *)fd {
3247 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3248 std::istream is(&ib);
3251 while (std::getline(is, line)) {
3252 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3254 lprintf("O:%s\n", line.c_str());
3256 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3257 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3269 - (Package *) packageWithName:(NSString *)name {
3270 @synchronized (self) {
3271 if (static_cast<pkgDepCache *>(cache_) == NULL)
3273 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3274 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3278 if ((self = [super init]) != nil) {
3285 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3286 apr_pool_create(&pool_, NULL);
3288 size_t capacity(MetaFile_->active_);
3294 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3295 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3299 _assert(pipe(fds) != -1);
3302 _config->Set("APT::Keep-Fds::", cydiafd_);
3303 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3306 detachNewThreadSelector:@selector(_readCydia:)
3308 withObject:[NSNumber numberWithInt:fds[0]]
3311 _assert(pipe(fds) != -1);
3315 detachNewThreadSelector:@selector(_readStatus:)
3317 withObject:[NSNumber numberWithInt:fds[0]]
3320 _assert(pipe(fds) != -1);
3321 _assert(dup2(fds[0], 0) != -1);
3322 _assert(close(fds[0]) != -1);
3324 input_ = fdopen(fds[1], "a");
3326 _assert(pipe(fds) != -1);
3327 _assert(dup2(fds[1], 1) != -1);
3328 _assert(close(fds[1]) != -1);
3331 detachNewThreadSelector:@selector(_readOutput:)
3333 withObject:[NSNumber numberWithInt:fds[0]]
3338 - (pkgCacheFile &) cache {
3342 - (pkgDepCache::Policy *) policy {
3346 - (pkgRecords *) records {
3350 - (pkgProblemResolver *) resolver {
3354 - (pkgAcquire &) fetcher {
3358 - (pkgSourceList &) list {
3362 - (NSArray *) packages {
3363 return (NSArray *) packages_;
3366 - (NSArray *) sources {
3370 - (Source *) sourceWithKey:(NSString *)key {
3371 for (Source *source in [self sources]) {
3372 if ([[source key] isEqualToString:key])
3377 - (bool) popErrorWithTitle:(NSString *)title {
3380 while (!_error->empty()) {
3382 bool warning(!_error->PopMessage(error));
3387 size_t size(error.size());
3388 if (size == 0 || error[size - 1] != '\n')
3390 error.resize(size - 1);
3393 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3395 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3401 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3402 return [self popErrorWithTitle:title] || !success;
3405 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3406 @synchronized (self) {
3409 [self releasePackages];
3412 [sourceList_ removeAllObjects];
3432 apr_pool_clear(pool_);
3434 NSRecycleZone(zone_);
3435 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3437 int chk(creat("/tmp/cydia.chk", 0644));
3441 if (invocation != nil)
3442 [invocation invoke];
3444 NSString *title(UCLocalize("DATABASE"));
3447 OpProgress progress;
3448 while (!cache_.Open(progress, true)) { pop:
3450 bool warning(!_error->PopMessage(error));
3451 lprintf("cache_.Open():[%s]\n", error.c_str());
3453 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3454 [delegate_ repairWithSelector:@selector(configure)];
3455 else if (error == "The package lists or status file could not be parsed or opened.")
3456 [delegate_ repairWithSelector:@selector(update)];
3457 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3458 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3459 // else if (error == "Malformed Status line")
3460 // else if (error == "The list of sources could not be read.")
3462 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3472 unlink("/tmp/cydia.chk");
3474 now_ = [[NSDate date] timeIntervalSince1970];
3476 policy_ = new pkgDepCache::Policy();
3477 records_ = new pkgRecords(cache_);
3478 resolver_ = new pkgProblemResolver(cache_);
3479 fetcher_ = new pkgAcquire(&status_);
3482 list_ = new pkgSourceList();
3483 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3486 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3487 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3491 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3494 if (cache_->BrokenCount() != 0) {
3495 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3498 if (cache_->BrokenCount() != 0) {
3499 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3503 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3507 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3508 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3509 [sourceList_ addObject:object];
3511 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3512 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3513 // XXX: this could be more intelligent
3514 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3515 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3517 sourceMap_[cached->ID] = object;
3522 /*std::vector<Package *> packages;
3523 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3528 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3529 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3530 //packages.push_back(package);
3531 CFArrayAppendValue(packages_, CFRetain(package));
3535 /*if (packages.empty())
3536 packages_ = [[NSArray alloc] init];
3538 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3541 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3542 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3543 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3551 /*if (!packages.empty())
3552 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3553 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3555 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3557 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3559 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3563 size_t count(CFArrayGetCount(packages_));
3564 MetaFile_->active_ = count;
3566 for (size_t index(0); index != count; ++index)
3567 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3574 @synchronized (self) {
3576 resolver_ = new pkgProblemResolver(cache_);
3578 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3579 if (!cache_[iterator].Keep())
3580 cache_->MarkKeep(iterator, false);
3581 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3582 cache_->SetReInstall(iterator, false);
3585 - (void) configure {
3586 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3588 system([dpkg UTF8String]);
3593 // XXX: I don't remember this condition
3598 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3600 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3602 if ([self popErrorWithTitle:title])
3606 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3608 CydiaLogCleaner cleaner;
3609 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3616 fetcher_->Shutdown();
3618 pkgRecords records(cache_);
3620 lock_ = new FileFd();
3621 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3623 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3625 if ([self popErrorWithTitle:title])
3629 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3632 manager_ = (_system->CreatePM(cache_));
3633 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3640 bool substrate(RestartSubstrate_);
3641 RestartSubstrate_ = false;
3643 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3645 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3647 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3649 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3650 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3653 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3655 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3657 [self popErrorWithTitle:title];
3661 bool failed = false;
3662 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3663 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3665 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3671 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3679 RestartSubstrate_ = true;
3682 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3684 if (_error->PendingError()) {
3689 if (result == pkgPackageManager::Failed) {
3694 if (result != pkgPackageManager::Completed) {
3699 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3701 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3703 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3704 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3707 if (![before isEqualToArray:after])
3712 NSString *title(UCLocalize("UPGRADE"));
3713 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3719 [self updateWithStatus:status_];
3722 - (void) updateWithStatus:(Status &)status {
3723 NSString *title(UCLocalize("REFRESHING_DATA"));
3726 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3730 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3731 if ([self popErrorWithTitle:title])
3734 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3736 bool success(ListUpdate(status, list, PulseInterval_));
3737 if (status.WasCancelled())
3740 [self popErrorWithTitle:title forOperation:success];
3741 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3745 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3748 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3749 delegate_ = delegate;
3752 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3753 progress_ = delegate;
3754 status_.setDelegate(delegate);
3757 - (NSObject<ProgressDelegate> *) progressDelegate {
3761 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3762 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3763 return i == sourceMap_.end() ? nil : i->second;
3766 - (NSString *) mappedSectionForPointer:(const char *)section {
3767 _H<NSString> *mapped;
3769 _profile(Database$mappedSectionForPointer$Cache)
3770 mapped = §ions_[section];
3773 if (*mapped == NULL) {
3774 size_t length(strlen(section));
3775 char spaced[length + 1];
3777 _profile(Database$mappedSectionForPointer$Replace)
3778 for (size_t index(0); index != length; ++index)
3779 spaced[index] = section[index] == '_' ? ' ' : section[index];
3780 spaced[length] = '\0';
3785 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3786 string = [NSString stringWithUTF8String:spaced];
3789 _profile(Database$mappedSectionForPointer$Map)
3790 string = [SectionMap_ objectForKey:string] ?: string;
3800 static _H<NSMutableSet> Diversions_;
3802 @interface Diversion : NSObject {
3805 _H<NSString> format_;
3810 @implementation Diversion
3812 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3813 if ((self = [super init]) != nil) {
3814 pattern_ = [from UTF8String];
3820 - (NSString *) divert:(NSString *)url {
3821 return !pattern_(url) ? nil : pattern_->*format_;
3824 + (NSURL *) divertURL:(NSURL *)url {
3826 NSString *href([url absoluteString]);
3828 for (Diversion *diversion in (id) Diversions_)
3829 if (NSString *diverted = [diversion divert:href]) {
3831 NSLog(@"div: %@", diverted);
3833 url = [NSURL URLWithString:diverted];
3840 - (NSString *) key {
3844 - (NSUInteger) hash {
3848 - (BOOL) isEqual:(Diversion *)object {
3849 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3854 @interface CydiaObject : NSObject {
3855 _H<IndirectDelegate> indirect_;
3856 _transient id delegate_;
3859 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3863 @interface CydiaWebViewController : CyteWebViewController {
3864 _H<CydiaObject> cydia_;
3867 + (void) addDiversion:(Diversion *)diversion;
3871 /* Web Scripting {{{ */
3872 @implementation CydiaObject
3874 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3875 if ((self = [super init]) != nil) {
3876 indirect_ = indirect;
3880 - (void) setDelegate:(id)delegate {
3881 delegate_ = delegate;
3884 + (NSArray *) _attributeKeys {
3885 return [NSArray arrayWithObjects:
3902 - (NSArray *) attributeKeys {
3903 return [[self class] _attributeKeys];
3906 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3907 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3910 - (NSString *) version {
3914 - (NSString *) device {
3915 return [[UIDevice currentDevice] uniqueIdentifier];
3918 - (NSString *) firmware {
3919 return [[UIDevice currentDevice] systemVersion];
3922 - (NSString *) hostname {
3923 return [[UIDevice currentDevice] name];
3926 - (NSString *) idiom {
3927 return (id) Idiom_ ?: [NSNull null];
3930 - (NSString *) plmn {
3931 return (id) PLMN_ ?: [NSNull null];
3934 - (NSString *) bbsnum {
3935 return (id) BBSNum_ ?: [NSNull null];
3938 - (NSString *) ecid {
3939 return (id) ChipID_ ?: [NSNull null];
3942 - (NSString *) serial {
3943 return SerialNumber_;
3946 - (NSString *) role {
3947 return (id) Role_ ?: [NSNull null];
3950 - (NSString *) model {
3951 return [NSString stringWithUTF8String:Machine_];
3954 - (NSString *) token {
3955 return (id) Token_ ?: [NSNull null];
3958 + (NSString *) webScriptNameForSelector:(SEL)selector {
3960 else if (selector == @selector(addBridgedHost:))
3961 return @"addBridgedHost";
3962 else if (selector == @selector(addInsecureHost:))
3963 return @"addInsecureHost";
3964 else if (selector == @selector(addInternalRedirect::))
3965 return @"addInternalRedirect";
3966 else if (selector == @selector(addPipelinedHost:scheme:))
3967 return @"addPipelinedHost";
3968 else if (selector == @selector(addSource:::))
3969 return @"addSource";
3970 else if (selector == @selector(addTokenHost:))
3971 return @"addTokenHost";
3972 else if (selector == @selector(addTrivialSource:))
3973 return @"addTrivialSource";
3974 else if (selector == @selector(close))
3976 else if (selector == @selector(du:))
3978 else if (selector == @selector(stringWithFormat:arguments:))
3980 else if (selector == @selector(getAllSources))
3981 return @"getAllSourcs";
3982 else if (selector == @selector(getKernelNumber:))
3983 return @"getKernelNumber";
3984 else if (selector == @selector(getKernelString:))
3985 return @"getKernelString";
3986 else if (selector == @selector(getInstalledPackages))
3987 return @"getInstalledPackages";
3988 else if (selector == @selector(getIORegistryEntry::))
3989 return @"getIORegistryEntry";
3990 else if (selector == @selector(getLocaleIdentifier))
3991 return @"getLocaleIdentifier";
3992 else if (selector == @selector(getPreferredLanguages))
3993 return @"getPreferredLanguages";
3994 else if (selector == @selector(getPackageById:))
3995 return @"getPackageById";
3996 else if (selector == @selector(getMetadataValue:))
3997 return @"getMetadataValue";
3998 else if (selector == @selector(getSessionValue:))
3999 return @"getSessionValue";
4000 else if (selector == @selector(installPackages:))
4001 return @"installPackages";
4002 else if (selector == @selector(localizedStringForKey:value:table:))
4004 else if (selector == @selector(popViewController:))
4005 return @"popViewController";
4006 else if (selector == @selector(refreshSources))
4007 return @"refreshSources";
4008 else if (selector == @selector(removeButton))
4009 return @"removeButton";
4010 else if (selector == @selector(saveConfig))
4011 return @"saveConfig";
4012 else if (selector == @selector(setCydiaSource:))
4013 return @"setCydiaSource";
4014 else if (selector == @selector(setMetadataValue::))
4015 return @"setMetadataValue";
4016 else if (selector == @selector(setSessionValue::))
4017 return @"setSessionValue";
4018 else if (selector == @selector(substitutePackageNames:))
4019 return @"substitutePackageNames";
4020 else if (selector == @selector(scrollToBottom:))
4021 return @"scrollToBottom";
4022 else if (selector == @selector(setAllowsNavigationAction:))
4023 return @"setAllowsNavigationAction";
4024 else if (selector == @selector(setBadgeValue:))
4025 return @"setBadgeValue";
4026 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4027 return @"setButtonImage";
4028 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4029 return @"setButtonTitle";
4030 else if (selector == @selector(setHidesBackButton:))
4031 return @"setHidesBackButton";
4032 else if (selector == @selector(setHidesNavigationBar:))
4033 return @"setHidesNavigationBar";
4034 else if (selector == @selector(setNavigationBarStyle:))
4035 return @"setNavigationBarStyle";
4036 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4037 return @"setNavigationBarTintColor";
4038 else if (selector == @selector(setPasteboardString:))
4039 return @"setPasteboardString";
4040 else if (selector == @selector(setPasteboardURL:))
4041 return @"setPasteboardURL";
4042 else if (selector == @selector(setToken:))
4044 else if (selector == @selector(setViewportWidth:))
4045 return @"setViewportWidth";
4046 else if (selector == @selector(statfs:))
4048 else if (selector == @selector(supports:))
4050 else if (selector == @selector(unload))
4056 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4057 return [self webScriptNameForSelector:selector] == nil;
4060 - (BOOL) supports:(NSString *)feature {
4061 return [feature isEqualToString:@"window.open"];
4065 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4068 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4069 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4072 - (NSNumber *) getKernelNumber:(NSString *)name {
4073 const char *string([name UTF8String]);
4076 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4077 return (id) [NSNull null];
4079 if (size != sizeof(int))
4080 return (id) [NSNull null];
4083 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4084 return (id) [NSNull null];
4086 return [NSNumber numberWithInt:value];
4089 - (NSString *) getKernelString:(NSString *)name {
4090 const char *string([name UTF8String]);
4093 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4094 return (id) [NSNull null];
4096 char value[size + 1];
4097 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4098 return (id) [NSNull null];
4100 // XXX: just in case you request something ludicrous
4103 return [NSString stringWithCString:value];
4106 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4107 NSObject *value(CYIOGetValue([path UTF8String], entry));
4110 if ([value isKindOfClass:[NSData class]])
4111 value = CYHex((NSData *) value);
4116 - (void) _setCydiaSource:(NSString *)source {
4117 @synchronized (HostConfig_) {
4118 CydiaSource_ = source;
4119 [Metadata_ setObject:source forKey:@"CydiaSource"];
4125 - (void) setCydiaSource:(NSString *)source {
4126 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4129 - (NSString *) cydiaSource {
4130 @synchronized (HostConfig_) {
4131 return (id) CydiaSource_ ?: [NSNull null];
4135 - (id) getMetadataValue:(NSString *)key {
4136 @synchronized (Values_) {
4137 return [Values_ objectForKey:key];
4140 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4141 @synchronized (Values_) {
4142 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4143 [Values_ removeObjectForKey:key];
4145 [Values_ setObject:value forKey:key];
4147 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4150 - (id) getSessionValue:(NSString *)key {
4151 @synchronized (SessionData_) {
4152 return [SessionData_ objectForKey:key];
4155 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4156 @synchronized (SessionData_) {
4157 if (value == (id) [WebUndefined undefined])
4158 [SessionData_ removeObjectForKey:key];
4160 [SessionData_ setObject:value forKey:key];
4163 - (void) addBridgedHost:(NSString *)host {
4164 @synchronized (HostConfig_) {
4165 [BridgedHosts_ addObject:host];
4168 - (void) addInsecureHost:(NSString *)host {
4169 @synchronized (HostConfig_) {
4170 [InsecureHosts_ addObject:host];
4173 - (void) addTokenHost:(NSString *)host {
4174 @synchronized (HostConfig_) {
4175 [TokenHosts_ addObject:host];
4178 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4179 @synchronized (HostConfig_) {
4180 if (scheme != (id) [WebUndefined undefined])
4181 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4183 [PipelinedHosts_ addObject:host];
4186 - (void) popViewController:(NSNumber *)value {
4187 if (value == (id) [WebUndefined undefined])
4188 value = [NSNumber numberWithBool:YES];
4189 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4192 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4193 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4195 for (NSString *section in sections)
4196 [array addObject:section];
4198 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4201 distribution, @"Distribution",
4203 nil] waitUntilDone:NO];
4206 - (void) addTrivialSource:(NSString *)href {
4207 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4210 - (void) refreshSources {
4211 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4214 - (void) saveConfig {
4215 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4218 - (NSArray *) getAllSources {
4219 return [[Database sharedInstance] sources];
4222 - (NSArray *) getInstalledPackages {
4223 Database *database([Database sharedInstance]);
4224 @synchronized (database) {
4225 NSArray *packages([database packages]);
4226 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4227 for (Package *package in packages)
4228 if (![package uninstalled])
4229 [installed addObject:package];
4233 - (Package *) getPackageById:(NSString *)id {
4234 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4238 return (Package *) [NSNull null];
4241 - (NSString *) getLocaleIdentifier {
4242 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4245 - (NSArray *) getPreferredLanguages {
4249 - (NSArray *) statfs:(NSString *)path {
4252 if (path == nil || statfs([path UTF8String], &stat) == -1)
4255 return [NSArray arrayWithObjects:
4256 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4257 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4258 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4262 - (NSNumber *) du:(NSString *)path {
4263 NSNumber *value(nil);
4266 _assert(pipe(fds) != -1);
4268 pid_t pid(ExecFork());
4270 _assert(dup2(fds[1], 1) != -1);
4271 _assert(close(fds[0]) != -1);
4272 _assert(close(fds[1]) != -1);
4273 /* XXX: this should probably not use du */
4274 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4279 _assert(close(fds[1]) != -1);
4281 if (FILE *du = fdopen(fds[0], "r")) {
4283 while (fgets(line, sizeof(line), du) != NULL) {
4284 size_t length(strlen(line));
4285 while (length != 0 && line[length - 1] == '\n')
4286 line[--length] = '\0';
4287 if (char *tab = strchr(line, '\t')) {
4289 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4294 } else _assert(close(fds[0]));
4298 if (waitpid(pid, &status, 0) == -1)
4301 else _assert(false);
4307 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4310 - (void) installPackages:(NSArray *)packages {
4311 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4314 - (NSString *) substitutePackageNames:(NSString *)message {
4315 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4316 for (size_t i(0), e([words count]); i != e; ++i) {
4317 NSString *word([words objectAtIndex:i]);
4318 if (Package *package = [[Database sharedInstance] packageWithName:word])
4319 [words replaceObjectAtIndex:i withObject:[package name]];
4322 return [words componentsJoinedByString:@" "];
4325 - (void) removeButton {
4326 [indirect_ removeButton];
4329 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4330 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4333 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4334 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4337 - (void) setBadgeValue:(id)value {
4338 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4341 - (void) setAllowsNavigationAction:(NSString *)value {
4342 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4345 - (void) setHidesBackButton:(NSString *)value {
4346 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4349 - (void) setHidesNavigationBar:(NSString *)value {
4350 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4353 - (void) setNavigationBarStyle:(NSString *)value {
4354 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4357 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4358 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4359 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4360 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4363 - (void) setPasteboardString:(NSString *)value {
4364 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4367 - (void) setPasteboardURL:(NSString *)value {
4368 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4371 - (void) _setToken:(NSString *)token {
4375 [Metadata_ removeObjectForKey:@"Token"];
4377 [Metadata_ setObject:Token_ forKey:@"Token"];
4382 - (void) setToken:(NSString *)token {
4383 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4386 - (void) scrollToBottom:(NSNumber *)animated {
4387 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4390 - (void) setViewportWidth:(float)width {
4391 [indirect_ setViewportWidthOnMainThread:width];
4394 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4395 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4396 unsigned count([arguments count]);
4398 for (unsigned i(0); i != count; ++i)
4399 values[i] = [arguments objectAtIndex:i];
4400 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4403 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4404 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4406 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4408 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4414 @interface NSURL (CydiaSecure)
4417 @implementation NSURL (CydiaSecure)
4419 - (bool) isCydiaSecure {
4420 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4423 @synchronized (HostConfig_) {
4424 if ([InsecureHosts_ containsObject:[self host]])
4433 /* Cydia Browser Controller {{{ */
4434 @implementation CydiaWebViewController
4436 - (NSURL *) navigationURL {
4437 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4440 + (void) initialize {
4441 Diversions_ = [NSMutableSet setWithCapacity:0];
4444 + (void) addDiversion:(Diversion *)diversion {
4445 [Diversions_ addObject:diversion];
4448 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4449 [super webView:view didClearWindowObject:window forFrame:frame];
4451 WebDataSource *source([frame dataSource]);
4452 NSURLResponse *response([source response]);
4453 NSURL *url([response URL]);
4454 NSString *scheme([[url scheme] lowercaseString]);
4456 bool bridged(false);
4458 @synchronized (HostConfig_) {
4459 if ([scheme isEqualToString:@"file"])
4461 else if ([scheme isEqualToString:@"https"])
4462 if ([BridgedHosts_ containsObject:[url host]])
4467 [window setValue:cydia_ forKey:@"cydia"];
4470 - (void) _setupMail:(MFMailComposeViewController *)controller {
4471 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4473 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4474 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4477 - (NSURL *) URLWithURL:(NSURL *)url {
4478 return [Diversion divertURL:url];
4481 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4482 NSURL *url([request URL]);
4483 NSString *host([url host]);
4485 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4487 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4488 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4489 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4490 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4493 @synchronized (HostConfig_) {
4494 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4497 if ([url isCydiaSecure] && token) {
4498 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4499 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4505 - (void) setDelegate:(id)delegate {
4506 [super setDelegate:delegate];
4507 [cydia_ setDelegate:delegate];
4510 - (NSString *) applicationNameForUserAgent {
4511 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4514 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4516 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4517 if (Product_ != nil)
4518 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4524 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4525 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4533 @interface NSObject (CydiaScript)
4534 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4537 @implementation NSObject (CydiaScript)
4539 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4545 @implementation NSArray (CydiaScript)
4547 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4548 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4549 for (size_t i(0), e([self count]); i != e; ++i)
4550 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4556 @implementation NSDictionary (CydiaScript)
4558 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4559 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4561 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4568 /* Confirmation Controller {{{ */
4569 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4570 if (!iterator.end())
4571 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4572 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4574 pkgCache::PkgIterator package(dep.TargetPkg());
4577 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4584 @protocol ConfirmationControllerDelegate
4585 - (void) cancelAndClear:(bool)clear;
4586 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4590 @interface ConfirmationController : CydiaWebViewController {
4591 _transient Database *database_;
4593 _H<UIAlertView> essential_;
4595 _H<NSDictionary> changes_;
4596 _H<NSMutableArray> issues_;
4597 _H<NSDictionary> sizes_;
4602 - (id) initWithDatabase:(Database *)database;
4606 @implementation ConfirmationController
4610 RestartSubstrate_ = true;
4611 [delegate_ confirmWithNavigationController:[self navigationController]];
4614 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4615 NSString *context([alert context]);
4617 if ([context isEqualToString:@"remove"]) {
4618 if (button == [alert cancelButtonIndex])
4619 [self dismissModalViewControllerAnimated:YES];
4620 else if (button == [alert firstOtherButtonIndex]) {
4624 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4625 } else if ([context isEqualToString:@"unable"]) {
4626 [self dismissModalViewControllerAnimated:YES];
4627 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4629 [super alertView:alert clickedButtonAtIndex:button];
4633 - (void) _doContinue {
4634 [self dismissModalViewControllerAnimated:YES];
4635 [delegate_ cancelAndClear:NO];
4638 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4639 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4643 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4644 [super webView:view didClearWindowObject:window forFrame:frame];
4646 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4647 (id) changes_, @"changes",
4648 (id) issues_, @"issues",
4649 (id) sizes_, @"sizes",
4651 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4654 - (id) initWithDatabase:(Database *)database {
4655 if ((self = [super init]) != nil) {
4656 database_ = database;
4658 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4659 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4660 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4661 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4662 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4666 pkgCacheFile &cache([database_ cache]);
4667 NSArray *packages([database_ packages]);
4668 pkgDepCache::Policy *policy([database_ policy]);
4670 issues_ = [NSMutableArray arrayWithCapacity:4];
4672 for (Package *package in packages) {
4673 pkgCache::PkgIterator iterator([package iterator]);
4674 NSString *name([package id]);
4676 if ([package broken]) {
4677 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4679 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4681 reasons, @"reasons",
4684 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4688 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4689 pkgCache::DepIterator start;
4690 pkgCache::DepIterator end;
4691 dep.GlobOr(start, end); // ++dep
4693 if (!cache->IsImportantDep(end))
4695 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4698 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4700 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4701 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4702 clauses, @"clauses",
4706 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4708 pkgCache::PkgIterator target(start.TargetPkg());
4709 if (target->ProvidesList != 0)
4710 reason = @"missing";
4712 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4714 reason = @"installed";
4715 installed = [NSString stringWithUTF8String:ver.VerStr()];
4716 } else if (!cache[target].CandidateVerIter(cache).end())
4717 reason = @"uninstalled";
4718 else if (target->ProvidesList == 0)
4719 reason = @"uninstallable";
4721 reason = @"virtual";
4724 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4725 [NSString stringWithUTF8String:start.CompType()], @"operator",
4726 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4729 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4730 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4731 version, @"version",
4733 installed, @"installed",
4736 // yes, seriously. (wtf?)
4744 pkgDepCache::StateCache &state(cache[iterator]);
4746 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4748 if (state.NewInstall())
4749 [installs addObject:name];
4750 // XXX: else if (state.Install())
4751 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4752 [reinstalls addObject:name];
4753 // XXX: move before previous if
4754 else if (state.Upgrade())
4755 [upgrades addObject:name];
4756 else if (state.Downgrade())
4757 [downgrades addObject:name];
4758 else if (!state.Delete())
4759 // XXX: _assert(state.Keep());
4761 else if (special_r(name))
4762 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4763 [NSNull null], @"package",
4764 [NSArray arrayWithObjects:
4765 [NSDictionary dictionaryWithObjectsAndKeys:
4766 @"Conflicts", @"relationship",
4767 [NSArray arrayWithObjects:
4768 [NSDictionary dictionaryWithObjectsAndKeys:
4770 [NSNull null], @"version",
4771 @"installed", @"reason",
4778 if ([package essential])
4780 [removes addObject:name];
4783 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4784 substrate_ |= DepSubstrate(iterator.CurrentVer());
4789 else if (Advanced_) {
4790 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4792 essential_ = [[[UIAlertView alloc]
4793 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4794 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4796 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4798 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4802 [essential_ setContext:@"remove"];
4804 essential_ = [[[UIAlertView alloc]
4805 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4806 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4808 cancelButtonTitle:UCLocalize("OKAY")
4809 otherButtonTitles:nil
4812 [essential_ setContext:@"unable"];
4815 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4816 installs, @"installs",
4817 reinstalls, @"reinstalls",
4818 upgrades, @"upgrades",
4819 downgrades, @"downgrades",
4820 removes, @"removes",
4823 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4824 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4825 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4828 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4832 - (UIBarButtonItem *) leftButton {
4833 return [[[UIBarButtonItem alloc]
4834 initWithTitle:UCLocalize("CANCEL")
4835 style:UIBarButtonItemStylePlain
4837 action:@selector(cancelButtonClicked)
4842 - (void) applyRightButton {
4843 if ([issues_ count] == 0 && ![self isLoading])
4844 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4845 initWithTitle:UCLocalize("CONFIRM")
4846 style:UIBarButtonItemStyleDone
4848 action:@selector(confirmButtonClicked)
4851 [[self navigationItem] setRightBarButtonItem:nil];
4855 - (void) cancelButtonClicked {
4856 [self dismissModalViewControllerAnimated:YES];
4857 [delegate_ cancelAndClear:YES];
4861 - (void) confirmButtonClicked {
4862 if (essential_ != nil)
4872 /* Progress Data {{{ */
4873 @interface CydiaProgressData : NSObject {
4874 _transient id delegate_;
4883 _H<NSMutableArray> events_;
4884 _H<NSString> title_;
4886 _H<NSString> status_;
4887 _H<NSString> finish_;
4892 @implementation CydiaProgressData
4894 + (NSArray *) _attributeKeys {
4895 return [NSArray arrayWithObjects:
4907 - (NSArray *) attributeKeys {
4908 return [[self class] _attributeKeys];
4911 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4912 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4916 if ((self = [super init]) != nil) {
4917 events_ = [NSMutableArray arrayWithCapacity:32];
4921 - (void) setDelegate:(id)delegate {
4922 delegate_ = delegate;
4925 - (void) setPercent:(float)value {
4929 - (NSNumber *) percent {
4930 return [NSNumber numberWithFloat:percent_];
4933 - (void) setCurrent:(float)value {
4937 - (NSNumber *) current {
4938 return [NSNumber numberWithFloat:current_];
4941 - (void) setTotal:(float)value {
4945 - (NSNumber *) total {
4946 return [NSNumber numberWithFloat:total_];
4949 - (void) setSpeed:(float)value {
4953 - (NSNumber *) speed {
4954 return [NSNumber numberWithFloat:speed_];
4957 - (NSArray *) events {
4961 - (void) removeAllEvents {
4962 [events_ removeAllObjects];
4965 - (void) addEvent:(CydiaProgressEvent *)event {
4966 [events_ addObject:event];
4969 - (void) setTitle:(NSString *)text {
4973 - (NSString *) title {
4977 - (void) setFinish:(NSString *)text {
4981 - (NSString *) finish {
4982 return (id) finish_ ?: [NSNull null];
4985 - (void) setRunning:(bool)running {
4989 - (NSNumber *) running {
4990 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
4995 /* Progress Controller {{{ */
4996 @interface ProgressController : CydiaWebViewController <
4999 _transient Database *database_;
5000 _H<CydiaProgressData, 1> progress_;
5004 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5006 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5008 - (void) setTitle:(NSString *)title;
5009 - (void) setCancellable:(bool)cancellable;
5013 @implementation ProgressController
5016 [database_ setProgressDelegate:nil];
5020 - (UIBarButtonItem *) leftButton {
5021 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5022 initWithTitle:UCLocalize("CANCEL")
5023 style:UIBarButtonItemStylePlain
5025 action:@selector(cancel)
5026 ] autorelease] : nil;
5029 - (void) updateCancel {
5030 [super applyLeftButton];
5033 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5034 if ((self = [super init]) != nil) {
5035 database_ = database;
5036 delegate_ = delegate;
5038 [database_ setProgressDelegate:self];
5040 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5041 [progress_ setDelegate:self];
5043 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5045 [scroller_ setBackgroundColor:[UIColor blackColor]];
5047 [[self navigationItem] setHidesBackButton:YES];
5049 [self updateCancel];
5053 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5054 [super webView:view didClearWindowObject:window forFrame:frame];
5055 [window setValue:progress_ forKey:@"cydiaProgress"];
5058 - (void) updateProgress {
5059 [self dispatchEvent:@"CydiaProgressUpdate"];
5062 - (void) viewWillAppear:(BOOL)animated {
5063 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5064 [super viewWillAppear:animated];
5068 UpdateExternalStatus(0);
5075 [delegate_ terminateWithSuccess];
5076 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5077 [delegate_ suspendWithAnimation:YES];
5079 [delegate_ suspend];*/
5091 system("/usr/bin/sbreload");
5097 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5098 SBReboot(SBSSpringBoardServerPort());
5100 reboot2(RB_AUTOBOOT);
5107 - (void) setTitle:(NSString *)title {
5108 [progress_ setTitle:title];
5109 [self updateProgress];
5112 - (UIBarButtonItem *) rightButton {
5113 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5114 initWithTitle:UCLocalize("CLOSE")
5115 style:UIBarButtonItemStylePlain
5117 action:@selector(close)
5121 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5122 UpdateExternalStatus(1);
5124 [progress_ setRunning:true];
5125 [self setTitle:title];
5126 // implicit updateProgress
5128 SHA1SumValue notifyconf; {
5130 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5133 MMap mmap(file, MMap::ReadOnly);
5135 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5136 notifyconf = sha1.Result();
5140 SHA1SumValue springlist; {
5142 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5145 MMap mmap(file, MMap::ReadOnly);
5147 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5148 springlist = sha1.Result();
5152 if (invocation != nil) {
5153 [invocation yieldToSelector:@selector(invoke)];
5154 [self setTitle:@"COMPLETE"];
5159 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5162 MMap mmap(file, MMap::ReadOnly);
5164 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5165 if (!(notifyconf == sha1.Result()))
5172 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5175 MMap mmap(file, MMap::ReadOnly);
5177 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5178 if (!(springlist == sha1.Result()))
5184 if (RestartSubstrate_)
5188 RestartSubstrate_ = false;
5191 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5192 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5193 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5194 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5195 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5199 system("su -c /usr/bin/uicache mobile");
5202 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5204 [progress_ setRunning:false];
5205 [self updateProgress];
5207 [self applyRightButton];
5210 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5211 [progress_ addEvent:event];
5212 [self updateProgress];
5215 - (bool) isProgressCancelled {
5216 return cancel_ == 2;
5221 [self updateCancel];
5224 - (void) setCancellable:(bool)cancellable {
5225 unsigned cancel(cancel_);
5229 else if (cancel_ == 0)
5232 if (cancel != cancel_)
5233 [self updateCancel];
5236 - (void) setProgressCancellable:(NSNumber *)cancellable {
5237 [self setCancellable:[cancellable boolValue]];
5240 - (void) setProgressPercent:(NSNumber *)percent {
5241 [progress_ setPercent:[percent floatValue]];
5242 [self updateProgress];
5245 - (void) setProgressStatus:(NSDictionary *)status {
5246 if (status == nil) {
5247 [progress_ setCurrent:0];
5248 [progress_ setTotal:0];
5249 [progress_ setSpeed:0];
5251 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5253 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5254 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5255 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5258 [self updateProgress];
5264 /* Package Cell {{{ */
5265 @interface PackageCell : CyteTableViewCell <
5266 CyteTableViewCellDelegate
5270 _H<NSString> description_;
5272 _H<NSString> source_;
5274 _H<Package> package_;
5275 _H<UIImage> placard_;
5279 - (PackageCell *) init;
5280 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5282 - (void) drawContentRect:(CGRect)rect;
5286 @implementation PackageCell
5288 - (PackageCell *) init {
5289 CGRect frame(CGRectMake(0, 0, 320, 74));
5290 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5291 UIView *content([self contentView]);
5292 CGRect bounds([content bounds]);
5294 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5295 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5296 [content addSubview:content_];
5298 [content_ setDelegate:self];
5299 [content_ setOpaque:YES];
5303 - (NSString *) accessibilityLabel {
5304 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5307 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5308 summarized_ = summary;
5320 Source *source = [package source];
5322 icon_ = [package icon];
5324 if (NSString *name = [package name])
5325 name_ = [NSString stringWithString:name];
5327 NSString *description(nil);
5329 if (description == nil && IsWildcat_)
5330 description = [package longDescription];
5331 if (description == nil)
5332 description = [package shortDescription];
5334 if (description != nil)
5335 description_ = [NSString stringWithString:description];
5337 commercial_ = [package isCommercial];
5341 NSString *label = nil;
5342 bool trusted = false;
5344 if (source != nil) {
5345 label = [source label];
5346 trusted = [source trusted];
5347 } else if ([[package id] isEqualToString:@"firmware"])
5348 label = UCLocalize("APPLE");
5350 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5352 NSString *from(label);
5354 NSString *section = [package simpleSection];
5355 if (section != nil && ![section isEqualToString:label]) {
5356 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5357 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5360 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5362 if (NSString *purpose = [package primaryPurpose])
5363 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5368 if (NSString *mode = [package_ mode]) {
5369 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5370 color = RemovingColor_;
5371 //placard = @"removing";
5373 color = InstallingColor_;
5374 //placard = @"installing";
5377 // XXX: the removing/installing placards are not @2x
5380 color = [UIColor whiteColor];
5382 if ([package installed] != nil)
5383 placard = @"installed";
5388 [content_ setBackgroundColor:color];
5391 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5393 [self setNeedsDisplay];
5394 [content_ setNeedsDisplay];
5397 - (void) drawSummaryContentRect:(CGRect)rect {
5398 bool highlighted(highlighted_);
5399 float width([self bounds].size.width);
5403 rect.size = [(UIImage *) icon_ size];
5405 rect.size.width /= 4;
5406 rect.size.height /= 4;
5408 rect.origin.x = 14 - rect.size.width / 4;
5409 rect.origin.y = 14 - rect.size.height / 4;
5411 [icon_ drawInRect:rect];
5414 if (badge_ != nil) {
5416 rect.size = [(UIImage *) badge_ size];
5418 rect.size.width /= 4;
5419 rect.size.height /= 4;
5421 rect.origin.x = 20 - rect.size.width / 4;
5422 rect.origin.y = 20 - rect.size.height / 4;
5424 [badge_ drawInRect:rect];
5431 UISetColor(commercial_ ? Purple_ : Black_);
5432 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5434 if (placard_ != nil)
5435 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5438 - (void) drawNormalContentRect:(CGRect)rect {
5439 bool highlighted(highlighted_);
5440 float width([self bounds].size.width);
5444 rect.size = [(UIImage *) icon_ size];
5446 rect.size.width /= 2;
5447 rect.size.height /= 2;
5449 rect.origin.x = 25 - rect.size.width / 2;
5450 rect.origin.y = 25 - rect.size.height / 2;
5452 [icon_ drawInRect:rect];
5455 if (badge_ != nil) {
5457 rect.size = [(UIImage *) badge_ size];
5459 rect.size.width /= 2;
5460 rect.size.height /= 2;
5462 rect.origin.x = 36 - rect.size.width / 2;
5463 rect.origin.y = 36 - rect.size.height / 2;
5465 [badge_ drawInRect:rect];
5472 UISetColor(commercial_ ? Purple_ : Black_);
5473 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5474 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5477 UISetColor(commercial_ ? Purplish_ : Gray_);
5478 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5480 if (placard_ != nil)
5481 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5484 - (void) drawContentRect:(CGRect)rect {
5486 [self drawSummaryContentRect:rect];
5488 [self drawNormalContentRect:rect];
5493 /* Section Cell {{{ */
5494 @interface SectionCell : CyteTableViewCell <
5495 CyteTableViewCellDelegate
5497 _H<NSString> basic_;
5498 _H<NSString> section_;
5500 _H<NSString> count_;
5502 _H<UISwitch> switch_;
5506 - (void) setSection:(Section *)section editing:(BOOL)editing;
5510 @implementation SectionCell
5512 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5513 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5514 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5515 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5516 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5518 UIView *content([self contentView]);
5519 CGRect bounds([content bounds]);
5521 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5522 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5523 [content addSubview:content_];
5524 [content_ setBackgroundColor:[UIColor whiteColor]];
5526 [content_ setDelegate:self];
5530 - (void) onSwitch:(id)sender {
5531 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5532 if (metadata == nil) {
5533 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5534 [Sections_ setObject:metadata forKey:basic_];
5537 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5541 - (void) setSection:(Section *)section editing:(BOOL)editing {
5542 if (editing != editing_) {
5544 [switch_ removeFromSuperview];
5546 [self addSubview:switch_];
5555 if (section == nil) {
5556 name_ = UCLocalize("ALL_PACKAGES");
5559 basic_ = [section name];
5560 section_ = [section localized];
5562 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5563 count_ = [NSString stringWithFormat:@"%d", [section count]];
5566 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5569 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5570 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5572 [content_ setNeedsDisplay];
5575 - (void) setFrame:(CGRect)frame {
5576 [super setFrame:frame];
5578 CGRect rect([switch_ frame]);
5579 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5582 - (NSString *) accessibilityLabel {
5586 - (void) drawContentRect:(CGRect)rect {
5587 bool highlighted(highlighted_ && !editing_);
5589 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5594 float width(rect.size.width);
5600 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5602 CGSize size = [count_ sizeWithFont:Font14_];
5606 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5612 /* File Table {{{ */
5613 @interface FileTable : CyteViewController <
5614 UITableViewDataSource,
5617 _transient Database *database_;
5618 _H<Package> package_;
5620 _H<NSMutableArray> files_;
5621 _H<UITableView, 2> list_;
5624 - (id) initWithDatabase:(Database *)database;
5625 - (void) setPackage:(Package *)package;
5629 @implementation FileTable
5631 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5632 return files_ == nil ? 0 : [files_ count];
5635 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5639 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5640 static NSString *reuseIdentifier = @"Cell";
5642 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5644 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5645 [cell setFont:[UIFont systemFontOfSize:16]];
5647 [cell setText:[files_ objectAtIndex:indexPath.row]];
5648 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5653 - (NSURL *) navigationURL {
5654 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5658 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5660 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5661 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5662 [list_ setRowHeight:24.0f];
5663 [(UITableView *) list_ setDataSource:self];
5664 [list_ setDelegate:self];
5665 [[self view] addSubview:list_];
5668 - (void) viewDidLoad {
5669 [super viewDidLoad];
5671 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5674 - (void) releaseSubviews {
5677 [super releaseSubviews];
5680 - (id) initWithDatabase:(Database *)database {
5681 if ((self = [super init]) != nil) {
5682 database_ = database;
5684 files_ = [NSMutableArray arrayWithCapacity:32];
5688 - (void) setPackage:(Package *)package {
5692 [files_ removeAllObjects];
5694 if (package != nil) {
5696 name_ = [package id];
5698 if (NSArray *files = [package files])
5699 [files_ addObjectsFromArray:files];
5701 if ([files_ count] != 0) {
5702 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5703 [files_ removeObjectAtIndex:0];
5704 [files_ sortUsingSelector:@selector(compareByPath:)];
5706 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5707 [stack addObject:@"/"];
5709 for (int i(0), e([files_ count]); i != e; ++i) {
5710 NSString *file = [files_ objectAtIndex:i];
5711 while (![file hasPrefix:[stack lastObject]])
5712 [stack removeLastObject];
5713 NSString *directory = [stack lastObject];
5714 [stack addObject:[file stringByAppendingString:@"/"]];
5715 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5716 ([stack count] - 2) * 3, "",
5717 [file substringFromIndex:[directory length]]
5726 - (void) reloadData {
5729 [self setPackage:[database_ packageWithName:name_]];
5734 /* Package Controller {{{ */
5735 @interface CYPackageController : CydiaWebViewController <
5736 UIActionSheetDelegate
5738 _transient Database *database_;
5739 _H<Package> package_;
5742 _H<NSMutableArray> buttons_;
5743 _H<UIBarButtonItem> button_;
5746 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5750 @implementation CYPackageController
5752 - (NSURL *) navigationURL {
5753 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5756 /* XXX: this is not safe at all... localization of /fail/ */
5757 - (void) _clickButtonWithName:(NSString *)name {
5758 if ([name isEqualToString:UCLocalize("CLEAR")])
5759 [delegate_ clearPackage:package_];
5760 else if ([name isEqualToString:UCLocalize("INSTALL")])
5761 [delegate_ installPackage:package_];
5762 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5763 [delegate_ installPackage:package_];
5764 else if ([name isEqualToString:UCLocalize("REMOVE")])
5765 [delegate_ removePackage:package_];
5766 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5767 [delegate_ installPackage:package_];
5768 else _assert(false);
5771 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5772 NSString *context([sheet context]);
5774 if ([context isEqualToString:@"modify"]) {
5775 if (button != [sheet cancelButtonIndex]) {
5776 NSString *buttonName = [buttons_ objectAtIndex:button];
5777 [self _clickButtonWithName:buttonName];
5780 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5784 - (bool) _allowJavaScriptPanel {
5789 - (void) _customButtonClicked {
5790 int count([buttons_ count]);
5795 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5797 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5798 [buttons addObjectsFromArray:buttons_];
5800 UIActionSheet *sheet = [[[UIActionSheet alloc]
5803 cancelButtonTitle:nil
5804 destructiveButtonTitle:nil
5805 otherButtonTitles:nil
5808 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5810 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5811 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5813 [sheet setContext:@"modify"];
5815 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5819 // We don't want to allow non-commercial packages to do custom things to the install button,
5820 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5821 - (void) customButtonClicked {
5823 [super customButtonClicked];
5825 [self _customButtonClicked];
5828 - (void) reloadButtonClicked {
5829 // Don't reload a commerical package by tapping the loading button,
5830 // but if it's not an Install button, we should forward it on.
5831 if (![package_ uninstalled])
5832 [self _customButtonClicked];
5835 - (void) applyLoadingTitle {
5836 // Don't show "Loading" as the title. Ever.
5839 - (UIBarButtonItem *) rightButton {
5844 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5845 if ((self = [super init]) != nil) {
5846 database_ = database;
5847 buttons_ = [NSMutableArray arrayWithCapacity:4];
5848 name_ = [NSString stringWithString:name];
5849 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5853 - (void) reloadData {
5856 package_ = [database_ packageWithName:name_];
5858 [buttons_ removeAllObjects];
5860 if (package_ != nil) {
5861 [(Package *) package_ parse];
5863 commercial_ = [package_ isCommercial];
5865 if ([package_ mode] != nil)
5866 [buttons_ addObject:UCLocalize("CLEAR")];
5867 if ([package_ source] == nil);
5868 else if ([package_ upgradableAndEssential:NO])
5869 [buttons_ addObject:UCLocalize("UPGRADE")];
5870 else if ([package_ uninstalled])
5871 [buttons_ addObject:UCLocalize("INSTALL")];
5873 [buttons_ addObject:UCLocalize("REINSTALL")];
5874 if (![package_ uninstalled])
5875 [buttons_ addObject:UCLocalize("REMOVE")];
5879 switch ([buttons_ count]) {
5880 case 0: title = nil; break;
5881 case 1: title = [buttons_ objectAtIndex:0]; break;
5882 default: title = UCLocalize("MODIFY"); break;
5885 button_ = [[[UIBarButtonItem alloc]
5887 style:UIBarButtonItemStylePlain
5889 action:@selector(customButtonClicked)
5893 - (bool) isLoading {
5894 return commercial_ ? [super isLoading] : false;
5900 /* Package List Controller {{{ */
5901 @interface PackageListController : CyteViewController <
5902 UITableViewDataSource,
5905 _transient Database *database_;
5907 _H<NSArray> packages_;
5908 _H<NSMutableArray> sections_;
5909 _H<UITableView, 2> list_;
5910 _H<NSMutableArray> index_;
5911 _H<NSMutableDictionary> indices_;
5912 _H<NSString> title_;
5913 unsigned reloading_;
5916 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5917 - (void) setDelegate:(id)delegate;
5918 - (void) resetCursor;
5923 @implementation PackageListController
5925 - (bool) isSummarized {
5929 - (bool) showsSections {
5933 - (void) deselectWithAnimation:(BOOL)animated {
5934 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5937 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5938 CGRect base = [[self view] bounds];
5939 base.size.height -= bounds.size.height;
5940 base.origin = [list_ frame].origin;
5942 [UIView beginAnimations:nil context:NULL];
5943 [UIView setAnimationBeginsFromCurrentState:YES];
5944 [UIView setAnimationCurve:curve];
5945 [UIView setAnimationDuration:duration];
5946 [list_ setFrame:base];
5947 [UIView commitAnimations];
5950 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5951 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5954 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5955 [self resizeForKeyboardBounds:bounds duration:0];
5958 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5959 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5960 *curve = UIViewAnimationCurveEaseInOut;
5962 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5964 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5967 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5970 - (void) keyboardWillShow:(NSNotification *)notification {
5973 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5974 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5976 NSTimeInterval duration;
5977 UIViewAnimationCurve curve;
5978 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5980 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);
5981 UIViewController *base = self;
5982 while ([base parentViewController] != nil)
5983 base = [base parentViewController];
5984 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5985 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5987 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5988 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5990 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5993 - (void) keyboardWillHide:(NSNotification *)notification {
5994 NSTimeInterval duration;
5995 UIViewAnimationCurve curve;
5996 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5998 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6001 - (void) viewWillAppear:(BOOL)animated {
6002 [super viewWillAppear:animated];
6004 [self resizeForKeyboardBounds:CGRectZero];
6005 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6006 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6009 - (void) viewWillDisappear:(BOOL)animated {
6010 [super viewWillDisappear:animated];
6012 [self resizeForKeyboardBounds:CGRectZero];
6013 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6014 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6017 - (void) viewDidAppear:(BOOL)animated {
6018 [super viewDidAppear:animated];
6019 [self deselectWithAnimation:animated];
6022 - (void) didSelectPackage:(Package *)package {
6023 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6024 [view setDelegate:delegate_];
6025 [[self navigationController] pushViewController:view animated:YES];
6028 #if TryIndexedCollation
6029 + (BOOL) hasIndexedCollation {
6030 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6034 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6035 NSInteger count([sections_ count]);
6036 return count == 0 ? 1 : count;
6039 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6040 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6042 return [[sections_ objectAtIndex:section] name];
6045 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6046 if ([sections_ count] == 0)
6048 return [[sections_ objectAtIndex:section] count];
6051 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6052 @synchronized (database_) {
6053 if ([database_ era] != era_)
6056 Section *section([sections_ objectAtIndex:[path section]]);
6057 NSInteger row([path row]);
6058 Package *package([packages_ objectAtIndex:([section row] + row)]);
6059 return [[package retain] autorelease];
6062 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6063 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6065 cell = [[[PackageCell alloc] init] autorelease];
6066 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
6070 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6071 Package *package([self packageAtIndexPath:path]);
6072 package = [database_ packageWithName:[package id]];
6073 [self didSelectPackage:package];
6076 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6077 if (![self showsSections])
6083 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6084 #if TryIndexedCollation
6085 if ([[self class] hasIndexedCollation]) {
6086 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6093 - (void) updateHeight {
6094 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6097 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6098 if ((self = [super init]) != nil) {
6099 database_ = database;
6100 title_ = [title copy];
6101 [[self navigationItem] setTitle:title_];
6103 #if TryIndexedCollation
6104 if ([[self class] hasIndexedCollation])
6105 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6108 index_ = [NSMutableArray arrayWithCapacity:32];
6110 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6112 packages_ = [NSArray array];
6113 sections_ = [NSMutableArray arrayWithCapacity:16];
6118 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6120 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6121 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6122 [[self view] addSubview:list_];
6124 // XXX: is 20 the most optimal number here?
6125 [list_ setSectionIndexMinimumDisplayRowCount:20];
6127 [(UITableView *) list_ setDataSource:self];
6128 [list_ setDelegate:self];
6130 [self updateHeight];
6133 - (void) releaseSubviews {
6136 [super releaseSubviews];
6139 - (void) setDelegate:(id)delegate {
6140 delegate_ = delegate;
6143 - (bool) shouldYield {
6147 - (bool) shouldBlock {
6151 - (NSMutableArray *) _reloadPackages {
6152 @synchronized (database_) {
6153 era_ = [database_ era];
6154 NSArray *packages([database_ packages]);
6156 return [NSMutableArray arrayWithArray:packages];
6159 - (void) _reloadData {
6160 if (reloading_ != 0) {
6167 if ([self shouldYield]) {
6171 if (![self shouldBlock])
6174 hud = [delegate_ addProgressHUD];
6175 [hud setText:UCLocalize("LOADING")];
6179 packages = [self yieldToSelector:@selector(_reloadPackages)];
6182 [delegate_ removeProgressHUD:hud];
6183 } while (reloading_ == 2);
6187 packages = [self _reloadPackages];
6190 packages_ = packages;
6192 [indices_ removeAllObjects];
6193 [sections_ removeAllObjects];
6195 Section *section = nil;
6197 #if TryIndexedCollation
6198 if ([[self class] hasIndexedCollation]) {
6199 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6200 NSArray *titles = [collation sectionIndexTitles];
6203 _profile(PackageTable$reloadData$Section)
6204 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6208 _profile(PackageTable$reloadData$Section$Package)
6209 package = [packages_ objectAtIndex:offset];
6210 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6213 while (secidx < index) {
6216 _profile(PackageTable$reloadData$Section$Allocate)
6217 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6220 _profile(PackageTable$reloadData$Section$Add)
6221 [sections_ addObject:section];
6225 [section addToCount];
6231 [index_ removeAllObjects];
6233 bool sectioned([self showsSections]);
6235 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6236 [sections_ addObject:section];
6239 _profile(PackageTable$reloadData$Section)
6240 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6244 _profile(PackageTable$reloadData$Section$Package)
6245 package = [packages_ objectAtIndex:offset];
6246 index = [package index];
6249 if (sectioned && (section == nil || [section index] != index)) {
6250 _profile(PackageTable$reloadData$Section$Allocate)
6251 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6254 [index_ addObject:[section name]];
6255 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6257 _profile(PackageTable$reloadData$Section$Add)
6258 [sections_ addObject:section];
6262 [section addToCount];
6267 [self updateHeight];
6269 _profile(PackageTable$reloadData$List)
6270 [(UITableView *) list_ setDataSource:self];
6275 - (void) reloadData {
6277 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6280 - (void) resetCursor {
6281 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6284 - (void) clearData {
6285 [self updateHeight];
6287 [list_ setDataSource:nil];
6295 /* Filtered Package List Controller {{{ */
6296 @interface FilteredPackageListController : PackageListController {
6299 _H<NSObject> object_;
6302 - (void) setObject:(id)object;
6303 - (void) setObject:(id)object forFilter:(SEL)filter;
6306 - (void) setFilter:(SEL)filter;
6308 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6312 @implementation FilteredPackageListController
6318 - (void) setFilter:(SEL)filter {
6319 @synchronized (self) {
6322 /* XXX: this is an unsafe optimization of doomy hell */
6323 Method method(class_getInstanceMethod([Package class], filter));
6324 _assert(method != NULL);
6325 imp_ = method_getImplementation(method);
6326 _assert(imp_ != NULL);
6329 - (void) setObject:(id)object {
6330 @synchronized (self) {
6334 - (void) setObject:(id)object forFilter:(SEL)filter {
6335 @synchronized (self) {
6336 [self setFilter:filter];
6337 [self setObject:object];
6340 - (NSMutableArray *) _reloadPackages {
6341 @synchronized (database_) {
6342 era_ = [database_ era];
6343 NSArray *packages([database_ packages]);
6345 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6349 _H<NSObject> object;
6351 @synchronized (self) {
6357 _profile(PackageTable$reloadData$Filter)
6358 for (Package *package in packages)
6359 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6360 [filtered addObject:package];
6366 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6367 if ((self = [super initWithDatabase:database title:title]) != nil) {
6368 [self setFilter:filter];
6369 [self setObject:object];
6376 /* Home Controller {{{ */
6377 @interface HomeController : CydiaWebViewController {
6382 @implementation HomeController
6385 if ((self = [super init]) != nil) {
6386 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6391 - (NSURL *) navigationURL {
6392 return [NSURL URLWithString:@"cydia://home"];
6395 - (void) aboutButtonClicked {
6396 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6398 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6399 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6400 [alert setCancelButtonIndex:0];
6403 @"Copyright \u00a9 2008-2011\n"
6406 "Jay Freeman (saurik)\n"
6407 "saurik@saurik.com\n"
6408 "http://www.saurik.com/"
6414 - (UIBarButtonItem *) leftButton {
6415 return [[[UIBarButtonItem alloc]
6416 initWithTitle:UCLocalize("ABOUT")
6417 style:UIBarButtonItemStylePlain
6419 action:@selector(aboutButtonClicked)
6425 /* Manage Controller {{{ */
6426 @interface ManageController : CydiaWebViewController {
6429 - (void) queueStatusDidChange;
6433 @implementation ManageController
6436 if ((self = [super init]) != nil) {
6437 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6441 - (NSURL *) navigationURL {
6442 return [NSURL URLWithString:@"cydia://manage"];
6445 - (UIBarButtonItem *) leftButton {
6446 return [[[UIBarButtonItem alloc]
6447 initWithTitle:UCLocalize("SETTINGS")
6448 style:UIBarButtonItemStylePlain
6450 action:@selector(settingsButtonClicked)
6454 - (void) settingsButtonClicked {
6455 [delegate_ showSettings];
6458 - (void) queueButtonClicked {
6462 - (UIBarButtonItem *) customButton {
6463 return Queuing_ ? [[[UIBarButtonItem alloc]
6464 initWithTitle:UCLocalize("QUEUE")
6465 style:UIBarButtonItemStyleDone
6467 action:@selector(queueButtonClicked)
6468 ] autorelease] : [super customButton];
6471 - (void) queueStatusDidChange {
6472 [self applyRightButton];
6475 - (bool) isLoading {
6476 return !Queuing_ && [super isLoading];
6482 /* Refresh Bar {{{ */
6483 @interface RefreshBar : UINavigationBar {
6484 _H<UIProgressIndicator> indicator_;
6485 _H<UITextLabel> prompt_;
6486 _H<UIProgressBar> progress_;
6487 _H<UINavigationButton> cancel_;
6492 @implementation RefreshBar
6494 - (void) positionViews {
6495 CGRect frame = [cancel_ frame];
6496 frame.size = [cancel_ sizeThatFits:frame.size];
6497 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6498 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6499 [cancel_ setFrame:frame];
6501 CGSize prgsize = {75, 100};
6503 [self frame].size.width - prgsize.width - 10,
6504 ([self frame].size.height - prgsize.height) / 2
6506 [progress_ setFrame:prgrect];
6508 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6509 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6510 CGRect indrect = {{indoffset, indoffset}, indsize};
6511 [indicator_ setFrame:indrect];
6513 CGSize prmsize = {215, indsize.height + 4};
6515 indoffset * 2 + indsize.width,
6516 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6518 [prompt_ setFrame:prmrect];
6521 - (void) setFrame:(CGRect)frame {
6522 [super setFrame:frame];
6523 [self positionViews];
6526 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6527 if ((self = [super initWithFrame:frame]) != nil) {
6528 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6530 [self setBarStyle:UIBarStyleBlack];
6532 UIBarStyle barstyle([self _barStyle:NO]);
6533 bool ugly(barstyle == UIBarStyleDefault);
6535 UIProgressIndicatorStyle style = ugly ?
6536 UIProgressIndicatorStyleMediumBrown :
6537 UIProgressIndicatorStyleMediumWhite;
6539 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6540 [(UIProgressIndicator *) indicator_ setStyle:style];
6541 [indicator_ startAnimation];
6542 [self addSubview:indicator_];
6544 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6545 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6546 [prompt_ setBackgroundColor:[UIColor clearColor]];
6547 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6548 [self addSubview:prompt_];
6550 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6551 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6552 [(UIProgressBar *) progress_ setStyle:0];
6553 [self addSubview:progress_];
6555 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6556 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6557 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6558 [cancel_ setBarStyle:barstyle];
6560 [self positionViews];
6564 - (void) setCancellable:(bool)cancellable {
6566 [self addSubview:cancel_];
6568 [cancel_ removeFromSuperview];
6572 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6573 [progress_ setProgress:0];
6577 [self setCancellable:NO];
6580 - (void) setPrompt:(NSString *)prompt {
6581 [prompt_ setText:prompt];
6584 - (void) setProgress:(float)progress {
6585 [progress_ setProgress:progress];
6591 /* Cydia Navigation Controller Interface {{{ */
6592 @interface UINavigationController (Cydia)
6594 - (NSArray *) navigationURLCollection;
6595 - (void) unloadData;
6600 /* Cydia Tab Bar Controller {{{ */
6601 @interface CYTabBarController : UITabBarController <
6602 UITabBarControllerDelegate,
6605 _transient Database *database_;
6606 _H<RefreshBar, 1> refreshbar_;
6610 // XXX: ok, "updatedelegate_"?...
6611 _transient NSObject<CydiaDelegate> *updatedelegate_;
6613 _H<UIViewController> remembered_;
6614 _transient UIViewController *transient_;
6617 - (NSArray *) navigationURLCollection;
6618 - (void) dropBar:(BOOL)animated;
6619 - (void) beginUpdate;
6620 - (void) raiseBar:(BOOL)animated;
6622 - (void) unloadData;
6626 @implementation CYTabBarController
6628 - (void) setUnselectedViewController:(UIViewController *)transient {
6629 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6630 if (transient != nil) {
6631 if (transient_ == nil)
6632 remembered_ = [controllers objectAtIndex:0];
6633 transient_ = transient;
6634 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6635 [controllers replaceObjectAtIndex:0 withObject:transient_];
6636 [self setSelectedIndex:0];
6637 [self setViewControllers:controllers];
6638 [self concealTabBarSelection];
6639 } else if (remembered_ != nil) {
6640 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6641 transient_ = transient;
6642 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6644 [self setViewControllers:controllers];
6645 [self revealTabBarSelection];
6649 - (UIViewController *) unselectedViewController {
6653 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6654 if ([self unselectedViewController])
6655 [self setUnselectedViewController:nil];
6658 - (NSArray *) navigationURLCollection {
6659 NSMutableArray *items([NSMutableArray array]);
6661 // XXX: Should this deal with transient view controllers?
6662 for (id navigation in [self viewControllers]) {
6663 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6665 [items addObject:stack];
6671 - (void) unloadData {
6674 for (UINavigationController *controller in [self viewControllers])
6675 [controller unloadData];
6677 if (UIViewController *selected = [self selectedViewController])
6678 [selected reloadData];
6680 if (UIViewController *unselected = [self unselectedViewController]) {
6681 [unselected unloadData];
6682 [unselected reloadData];
6687 [[NSNotificationCenter defaultCenter] removeObserver:self];
6692 - (id) initWithDatabase:(Database *)database {
6693 if ((self = [super init]) != nil) {
6694 database_ = database;
6695 [self setDelegate:self];
6697 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6698 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6700 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6704 - (void) setUpdate:(NSDate *)date {
6708 - (void) beginUpdate {
6709 [(RefreshBar *) refreshbar_ start];
6712 [updatedelegate_ retainNetworkActivityIndicator];
6716 detachNewThreadSelector:@selector(performUpdate)
6722 - (void) performUpdate {
6723 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6726 status.setDelegate(self);
6727 [database_ updateWithStatus:status];
6730 performSelectorOnMainThread:@selector(completeUpdate)
6738 - (void) stopUpdateWithSelector:(SEL)selector {
6740 [updatedelegate_ releaseNetworkActivityIndicator];
6742 [self raiseBar:YES];
6745 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6748 - (void) completeUpdate {
6751 [self stopUpdateWithSelector:@selector(reloadData)];
6754 - (void) cancelUpdate {
6755 [self stopUpdateWithSelector:@selector(updateData)];
6758 - (void) cancelPressed {
6759 [self cancelUpdate];
6766 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6767 [refreshbar_ setPrompt:[event compoundMessage]];
6770 - (bool) isProgressCancelled {
6774 - (void) setProgressCancellable:(NSNumber *)cancellable {
6775 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6778 - (void) setProgressPercent:(NSNumber *)percent {
6779 [refreshbar_ setProgress:[percent floatValue]];
6782 - (void) setProgressStatus:(NSDictionary *)status {
6784 [self setProgressPercent:[status objectForKey:@"Percent"]];
6787 - (void) setUpdateDelegate:(id)delegate {
6788 updatedelegate_ = delegate;
6791 - (UIView *) transitionView {
6792 if ([self respondsToSelector:@selector(_transitionView)])
6793 return [self _transitionView];
6795 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6798 - (void) dropBar:(BOOL)animated {
6803 UIView *transition([self transitionView]);
6804 [[self view] addSubview:refreshbar_];
6806 CGRect barframe([refreshbar_ frame]);
6808 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6809 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6811 barframe.origin.y = 0;
6813 [refreshbar_ setFrame:barframe];
6816 [UIView beginAnimations:nil context:NULL];
6818 CGRect viewframe = [transition frame];
6819 viewframe.origin.y += barframe.size.height;
6820 viewframe.size.height -= barframe.size.height;
6821 [transition setFrame:viewframe];
6824 [UIView commitAnimations];
6826 // Ensure bar has the proper width for our view, it might have changed
6827 barframe.size.width = viewframe.size.width;
6828 [refreshbar_ setFrame:barframe];
6831 - (void) raiseBar:(BOOL)animated {
6836 UIView *transition([self transitionView]);
6837 [refreshbar_ removeFromSuperview];
6839 CGRect barframe([refreshbar_ frame]);
6842 [UIView beginAnimations:nil context:NULL];
6844 CGRect viewframe = [transition frame];
6845 viewframe.origin.y -= barframe.size.height;
6846 viewframe.size.height += barframe.size.height;
6847 [transition setFrame:viewframe];
6850 [UIView commitAnimations];
6853 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6854 bool dropped(dropped_);
6859 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6865 - (void) statusBarFrameChanged:(NSNotification *)notification {
6875 /* Cydia Navigation Controller Implementation {{{ */
6876 @implementation UINavigationController (Cydia)
6878 - (NSArray *) navigationURLCollection {
6879 NSMutableArray *stack([NSMutableArray array]);
6881 for (CyteViewController *controller in [self viewControllers]) {
6882 NSString *url = [[controller navigationURL] absoluteString];
6884 [stack addObject:url];
6890 - (void) reloadData {
6893 if (UIViewController *visible = [self visibleViewController])
6894 [visible reloadData];
6897 - (void) unloadData {
6898 for (CyteViewController *page in [self viewControllers])
6907 /* Cydia:// Protocol {{{ */
6908 @interface CydiaURLProtocol : NSURLProtocol {
6913 @implementation CydiaURLProtocol
6915 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6916 NSURL *url([request URL]);
6920 NSString *scheme([[url scheme] lowercaseString]);
6921 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6923 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6929 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6933 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6934 id<NSURLProtocolClient> client([self client]);
6936 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6938 NSData *data(UIImagePNGRepresentation(icon));
6940 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6941 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6942 [client URLProtocol:self didLoadData:data];
6943 [client URLProtocolDidFinishLoading:self];
6947 - (void) startLoading {
6948 id<NSURLProtocolClient> client([self client]);
6949 NSURLRequest *request([self request]);
6951 NSURL *url([request URL]);
6952 NSString *href([url absoluteString]);
6953 NSString *scheme([[url scheme] lowercaseString]);
6957 if ([scheme isEqualToString:@"cydia"])
6958 path = [href substringFromIndex:8];
6959 else if ([scheme isEqualToString:@"about"])
6960 path = [href substringFromIndex:12];
6961 else _assert(false);
6963 NSRange slash([path rangeOfString:@"/"]);
6966 if (slash.location == NSNotFound) {
6970 command = [path substringToIndex:slash.location];
6971 path = [path substringFromIndex:(slash.location + 1)];
6974 Database *database([Database sharedInstance]);
6976 if ([command isEqualToString:@"package-icon"]) {
6979 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6980 Package *package([database packageWithName:path]);
6984 UIImage *icon([package icon]);
6985 [self _returnPNGWithImage:icon forRequest:request];
6986 } else if ([command isEqualToString:@"source-icon"]) {
6989 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6990 NSString *source(Simplify(path));
6991 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6993 icon = [UIImage applicationImageNamed:@"unknown.png"];
6994 [self _returnPNGWithImage:icon forRequest:request];
6995 } else if ([command isEqualToString:@"uikit-image"]) {
6998 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6999 UIImage *icon(_UIImageWithName(path));
7000 [self _returnPNGWithImage:icon forRequest:request];
7001 } else if ([command isEqualToString:@"section-icon"]) {
7004 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7005 NSString *section(Simplify(path));
7006 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7008 icon = [UIImage applicationImageNamed:@"unknown.png"];
7009 [self _returnPNGWithImage:icon forRequest:request];
7011 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7015 - (void) stopLoading {
7021 /* Section Controller {{{ */
7022 @interface SectionController : FilteredPackageListController {
7023 _H<NSString> section_;
7026 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7030 @implementation SectionController
7032 - (NSURL *) navigationURL {
7033 NSString *name = section_;
7037 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7040 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7043 title = UCLocalize("ALL_PACKAGES");
7044 else if (![name isEqual:@""])
7045 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7047 title = UCLocalize("NO_SECTION");
7049 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7056 /* Sections Controller {{{ */
7057 @interface SectionsController : CyteViewController <
7058 UITableViewDataSource,
7061 _transient Database *database_;
7062 _H<NSMutableArray> sections_;
7063 _H<NSMutableArray> filtered_;
7064 _H<UITableView, 2> list_;
7067 - (id) initWithDatabase:(Database *)database;
7068 - (void) editButtonClicked;
7072 @implementation SectionsController
7074 - (NSURL *) navigationURL {
7075 return [NSURL URLWithString:@"cydia://sections"];
7078 - (void) updateNavigationItem {
7079 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7080 if ([sections_ count] == 0) {
7081 [[self navigationItem] setRightBarButtonItem:nil];
7083 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7084 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7086 action:@selector(editButtonClicked)
7087 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7091 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7092 [super setEditing:editing animated:animated];
7097 [delegate_ updateData];
7099 [self updateNavigationItem];
7102 - (void) viewDidAppear:(BOOL)animated {
7103 [super viewDidAppear:animated];
7104 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7107 - (void) viewWillDisappear:(BOOL)animated {
7108 [super viewWillDisappear:animated];
7109 if ([self isEditing]) [self setEditing:NO];
7112 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7113 Section *section = nil;
7114 int index = [indexPath row];
7115 if (![self isEditing]) {
7118 section = [filtered_ objectAtIndex:index];
7120 section = [sections_ objectAtIndex:index];
7125 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7126 if ([self isEditing])
7127 return [sections_ count];
7129 return [filtered_ count] + 1;
7132 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7136 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7137 static NSString *reuseIdentifier = @"SectionCell";
7139 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7141 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7143 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7148 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7149 if ([self isEditing])
7152 Section *section = [self sectionAtIndexPath:indexPath];
7154 SectionController *controller = [[[SectionController alloc]
7155 initWithDatabase:database_
7156 section:[section name]
7158 [controller setDelegate:delegate_];
7160 [[self navigationController] pushViewController:controller animated:YES];
7164 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7166 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7167 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7168 [list_ setRowHeight:45.0f];
7169 [(UITableView *) list_ setDataSource:self];
7170 [list_ setDelegate:self];
7171 [[self view] addSubview:list_];
7174 - (void) viewDidLoad {
7175 [super viewDidLoad];
7177 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7180 - (void) releaseSubviews {
7183 [super releaseSubviews];
7186 - (id) initWithDatabase:(Database *)database {
7187 if ((self = [super init]) != nil) {
7188 database_ = database;
7190 sections_ = [NSMutableArray arrayWithCapacity:16];
7191 filtered_ = [NSMutableArray arrayWithCapacity:16];
7195 - (void) reloadData {
7198 NSArray *packages = [database_ packages];
7200 [sections_ removeAllObjects];
7201 [filtered_ removeAllObjects];
7203 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7206 for (Package *package in packages) {
7207 NSString *name([package section]);
7208 NSString *key(name == nil ? @"" : name);
7212 _profile(SectionsView$reloadData$Section)
7213 section = [sections objectForKey:key];
7214 if (section == nil) {
7215 _profile(SectionsView$reloadData$Section$Allocate)
7216 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7217 [sections setObject:section forKey:key];
7222 [section addToCount];
7224 _profile(SectionsView$reloadData$Filter)
7225 if (![package valid] || ![package visible])
7233 [sections_ addObjectsFromArray:[sections allValues]];
7235 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7237 for (Section *section in (id) sections_) {
7238 size_t count([section row]);
7242 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7243 [section setCount:count];
7244 [filtered_ addObject:section];
7247 [self updateNavigationItem];
7252 - (void) editButtonClicked {
7253 [self setEditing:![self isEditing] animated:YES];
7259 /* Changes Controller {{{ */
7260 @interface ChangesController : CyteViewController <
7261 UITableViewDataSource,
7264 _transient Database *database_;
7266 _H<NSArray> packages_;
7267 _H<NSMutableArray> sections_;
7268 _H<UITableView, 2> list_;
7272 - (id) initWithDatabase:(Database *)database;
7276 @implementation ChangesController
7278 - (NSURL *) navigationURL {
7279 return [NSURL URLWithString:@"cydia://changes"];
7282 - (void) viewDidAppear:(BOOL)animated {
7283 [super viewDidAppear:animated];
7284 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7287 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7288 NSInteger count([sections_ count]);
7289 return count == 0 ? 1 : count;
7292 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7293 if ([sections_ count] == 0)
7295 return [[sections_ objectAtIndex:section] name];
7298 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7299 if ([sections_ count] == 0)
7301 return [[sections_ objectAtIndex:section] count];
7304 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7305 @synchronized (database_) {
7306 if ([database_ era] != era_)
7309 NSUInteger sectionIndex([path section]);
7310 if (sectionIndex >= [sections_ count])
7312 Section *section([sections_ objectAtIndex:sectionIndex]);
7313 NSInteger row([path row]);
7314 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7317 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7318 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7320 cell = [[[PackageCell alloc] init] autorelease];
7321 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7325 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7326 Package *package([self packageAtIndexPath:path]);
7327 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7328 [view setDelegate:delegate_];
7329 [[self navigationController] pushViewController:view animated:YES];
7333 - (void) refreshButtonClicked {
7334 [delegate_ beginUpdate];
7335 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7338 - (void) upgradeButtonClicked {
7339 [delegate_ distUpgrade];
7340 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7344 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7346 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7347 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7348 [list_ setRowHeight:73];
7349 [(UITableView *) list_ setDataSource:self];
7350 [list_ setDelegate:self];
7351 [[self view] addSubview:list_];
7354 - (void) viewDidLoad {
7355 [super viewDidLoad];
7357 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7360 - (void) releaseSubviews {
7363 [super releaseSubviews];
7366 - (id) initWithDatabase:(Database *)database {
7367 if ((self = [super init]) != nil) {
7368 database_ = database;
7370 packages_ = [NSArray array];
7371 sections_ = [NSMutableArray arrayWithCapacity:16];
7375 - (NSMutableArray *) _reloadPackages {
7376 @synchronized (database_) {
7377 era_ = [database_ era];
7378 NSArray *packages([database_ packages]);
7380 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7383 _profile(ChangesController$_reloadPackages$Filter)
7384 for (Package *package in packages)
7385 if ([package upgradableAndEssential:YES] || [package visible])
7386 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7389 _profile(ChangesController$_reloadPackages$radixSort)
7390 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7397 - (void) _reloadData {
7402 UIProgressHUD *hud([delegate_ addProgressHUD]);
7403 [hud setText:UCLocalize("LOADING")];
7404 //NSLog(@"HUD:%@::%@", delegate_, hud);
7405 packages = [self yieldToSelector:@selector(_reloadPackages)];
7406 [delegate_ removeProgressHUD:hud];
7408 packages = [self _reloadPackages];
7411 @synchronized (database_) {
7412 if (era_ != [database_ era])
7415 packages_ = packages;
7416 [sections_ removeAllObjects];
7418 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7419 Section *ignored = nil;
7420 Section *section = nil;
7424 bool unseens = false;
7426 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7428 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7429 Package *package = [packages_ objectAtIndex:offset];
7431 BOOL uae = [package upgradableAndEssential:YES];
7435 time_t seen([package seen]);
7437 if (section == nil || last != seen) {
7441 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7444 _profile(ChangesController$reloadData$Allocate)
7445 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7446 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7447 [sections_ addObject:section];
7451 [section addToCount];
7452 } else if ([package ignored]) {
7453 if (ignored == nil) {
7454 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7456 [ignored addToCount];
7459 [upgradable addToCount];
7464 CFRelease(formatter);
7467 Section *last = [sections_ lastObject];
7468 size_t count = [last count];
7469 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7470 [sections_ removeLastObject];
7473 if ([ignored count] != 0)
7474 [sections_ insertObject:ignored atIndex:0];
7476 [sections_ insertObject:upgradable atIndex:0];
7480 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7481 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7482 style:UIBarButtonItemStylePlain
7484 action:@selector(upgradeButtonClicked)
7485 ] autorelease]) animated:YES];
7487 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7488 initWithTitle:UCLocalize("REFRESH")
7489 style:UIBarButtonItemStylePlain
7491 action:@selector(refreshButtonClicked)
7492 ] autorelease]) animated:YES];
7497 - (void) reloadData {
7499 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7504 /* Search Controller {{{ */
7505 @interface SearchController : FilteredPackageListController <
7508 _H<UISearchBar, 1> search_;
7512 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7513 - (void) reloadData;
7517 @implementation SearchController
7519 - (NSURL *) navigationURL {
7520 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7521 return [NSURL URLWithString:@"cydia://search"];
7523 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7526 - (void) useSearch {
7527 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7532 - (void) viewWillAppear:(BOOL)animated {
7533 [super viewWillAppear:animated];
7535 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7539 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7540 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7545 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7546 [search_ resignFirstResponder];
7550 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7551 [search_ setText:@""];
7552 [self searchBarButtonClicked:searchBar];
7555 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7556 [self searchBarButtonClicked:searchBar];
7559 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7560 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7564 - (bool) shouldYield {
7568 - (bool) shouldBlock {
7569 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7572 - (bool) isSummarized {
7573 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7576 - (bool) showsSections {
7580 - (NSMutableArray *) _reloadPackages {
7581 NSMutableArray *packages([super _reloadPackages]);
7582 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7583 [packages radixSortUsingSelector:@selector(rank)];
7587 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7588 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7589 search_ = [[[UISearchBar alloc] init] autorelease];
7590 [search_ setDelegate:self];
7593 [search_ setText:query];
7597 - (void) viewDidAppear:(BOOL)animated {
7598 [super viewDidAppear:animated];
7600 if (!searchloaded_) {
7601 searchloaded_ = YES;
7602 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7603 [search_ layoutSubviews];
7604 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7606 UITextField *textField;
7607 if ([search_ respondsToSelector:@selector(searchField)])
7608 textField = [search_ searchField];
7610 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7612 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7613 [textField setEnablesReturnKeyAutomatically:NO];
7614 [[self navigationItem] setTitleView:textField];
7618 - (void) reloadData {
7619 id object([search_ text]);
7620 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7621 object = [object componentsSeparatedByString:@" "];
7623 [self setObject:object];
7629 - (void) didSelectPackage:(Package *)package {
7630 [search_ resignFirstResponder];
7631 [super didSelectPackage:package];
7636 /* Package Settings Controller {{{ */
7637 @interface PackageSettingsController : CyteViewController <
7638 UITableViewDataSource,
7641 _transient Database *database_;
7643 _H<Package> package_;
7644 _H<UITableView, 2> table_;
7645 _H<UISwitch> subscribedSwitch_;
7646 _H<UISwitch> ignoredSwitch_;
7647 _H<UITableViewCell> subscribedCell_;
7648 _H<UITableViewCell> ignoredCell_;
7651 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7655 @implementation PackageSettingsController
7657 - (NSURL *) navigationURL {
7658 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7661 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7662 if (package_ == nil)
7665 if ([package_ installed] == nil)
7671 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7672 if (package_ == nil)
7675 // both sections contain just one item right now.
7679 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7683 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7685 return UCLocalize("SHOW_ALL_CHANGES_EX");
7687 return UCLocalize("IGNORE_UPGRADES_EX");
7690 - (void) onSubscribed:(id)control {
7691 bool value([control isOn]);
7692 if (package_ == nil)
7694 if ([package_ setSubscribed:value])
7695 [delegate_ updateData];
7698 - (void) _updateIgnored {
7699 const char *package([name_ UTF8String]);
7700 bool on([ignoredSwitch_ isOn]);
7702 pid_t pid(ExecFork());
7704 FILE *dpkg(popen("dpkg --set-selections", "w"));
7705 fwrite(package, strlen(package), 1, dpkg);
7708 fwrite(" hold\n", 6, 1, dpkg);
7710 fwrite(" install\n", 9, 1, dpkg);
7720 int result(waitpid(pid, &status, 0));
7723 _assert(result == pid);
7729 - (void) onIgnored:(id)control {
7730 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7731 [invocation setTarget:self];
7732 [invocation setSelector:@selector(_updateIgnored)];
7734 [delegate_ reloadDataWithInvocation:invocation];
7737 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7738 if (package_ == nil)
7741 switch ([indexPath section]) {
7742 case 0: return subscribedCell_;
7743 case 1: return ignoredCell_;
7752 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7754 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7755 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7756 [(UITableView *) table_ setDataSource:self];
7757 [table_ setDelegate:self];
7758 [[self view] addSubview:table_];
7760 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7761 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7762 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7764 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7765 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7766 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7768 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7769 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7770 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7771 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7773 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7774 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7775 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7776 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7779 - (void) viewDidLoad {
7780 [super viewDidLoad];
7782 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7785 - (void) releaseSubviews {
7787 subscribedCell_ = nil;
7789 ignoredSwitch_ = nil;
7790 subscribedSwitch_ = nil;
7792 [super releaseSubviews];
7795 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7796 if ((self = [super init]) != nil) {
7797 database_ = database;
7802 - (void) reloadData {
7805 package_ = [database_ packageWithName:name_];
7807 if (package_ != nil) {
7808 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7809 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7810 } // XXX: what now, G?
7812 [table_ reloadData];
7818 /* Installed Controller {{{ */
7819 @interface InstalledController : FilteredPackageListController {
7823 - (id) initWithDatabase:(Database *)database;
7825 - (void) updateRoleButton;
7826 - (void) queueStatusDidChange;
7830 @implementation InstalledController
7832 - (NSURL *) navigationURL {
7833 return [NSURL URLWithString:@"cydia://installed"];
7836 - (id) initWithDatabase:(Database *)database {
7837 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7838 [self updateRoleButton];
7839 [self queueStatusDidChange];
7844 - (void) queueButtonClicked {
7849 - (void) queueStatusDidChange {
7853 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7854 initWithTitle:UCLocalize("QUEUE")
7855 style:UIBarButtonItemStyleDone
7857 action:@selector(queueButtonClicked)
7860 [[self navigationItem] setLeftBarButtonItem:nil];
7866 - (void) updateRoleButton {
7867 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7868 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7869 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7870 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7872 action:@selector(roleButtonClicked)
7876 - (void) roleButtonClicked {
7877 [self setObject:[NSNumber numberWithBool:expert_]];
7881 [self updateRoleButton];
7887 /* Source Cell {{{ */
7888 @interface SourceCell : CyteTableViewCell <
7889 CyteTableViewCellDelegate
7892 _H<NSString> origin_;
7893 _H<NSString> label_;
7896 - (void) setSource:(Source *)source;
7900 @implementation SourceCell
7902 - (void) _setImage:(UIImage *)image {
7904 [content_ setNeedsDisplay];
7907 - (void) _setSource:(Source *)source {
7908 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7910 if (NSString *base = [source base])
7911 if ([base length] != 0) {
7912 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7914 if (NSData *data = [NSURLConnection
7915 sendSynchronousRequest:[NSURLRequest
7917 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7921 returningResponse:NULL
7924 if (UIImage *image = [UIImage imageWithData:data])
7925 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7931 - (void) setSource:(Source *)source {
7932 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7934 origin_ = [source name];
7935 label_ = [source uri];
7937 [content_ setNeedsDisplay];
7939 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7942 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7943 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7944 UIView *content([self contentView]);
7945 CGRect bounds([content bounds]);
7947 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7948 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7949 [content_ setBackgroundColor:[UIColor whiteColor]];
7950 [content addSubview:content_];
7952 [content_ setDelegate:self];
7953 [content_ setOpaque:YES];
7957 - (NSString *) accessibilityLabel {
7961 - (void) drawContentRect:(CGRect)rect {
7962 bool highlighted(highlighted_);
7963 float width(rect.size.width);
7966 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7973 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7977 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7982 /* Source Controller {{{ */
7983 @interface SourceController : FilteredPackageListController {
7984 _transient Source *source_;
7988 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7992 @implementation SourceController
7994 - (NSURL *) navigationURL {
7995 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7998 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7999 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8001 key_ = [source key];
8005 - (void) reloadData {
8006 source_ = [database_ sourceWithKey:key_];
8007 key_ = [source_ key];
8008 [self setObject:source_];
8010 [[self navigationItem] setTitle:[source_ label]];
8017 /* Sources Controller {{{ */
8018 @interface SourcesController : CyteViewController <
8019 UITableViewDataSource,
8022 _transient Database *database_;
8023 _H<UITableView, 2> list_;
8024 _H<NSMutableArray> sources_;
8028 _H<UIProgressHUD> hud_;
8031 //NSURLConnection *installer_;
8032 NSURLConnection *trivial_;
8033 NSURLConnection *trivial_bz2_;
8034 NSURLConnection *trivial_gz_;
8035 //NSURLConnection *automatic_;
8040 - (id) initWithDatabase:(Database *)database;
8041 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8045 @implementation SourcesController
8047 - (void) _releaseConnection:(NSURLConnection *)connection {
8048 if (connection != nil) {
8049 [connection cancel];
8050 //[connection setDelegate:nil];
8051 [connection release];
8056 //[self _releaseConnection:installer_];
8057 [self _releaseConnection:trivial_];
8058 [self _releaseConnection:trivial_gz_];
8059 [self _releaseConnection:trivial_bz2_];
8060 //[self _releaseConnection:automatic_];
8065 - (NSURL *) navigationURL {
8066 return [NSURL URLWithString:@"cydia://sources"];
8069 - (void) viewDidAppear:(BOOL)animated {
8070 [super viewDidAppear:animated];
8071 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8074 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8075 return offset_ == 0 ? 1 : 2;
8078 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8079 switch (section + (offset_ == 0 ? 1 : 0)) {
8080 case 0: return UCLocalize("ENTERED_BY_USER");
8081 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8087 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8088 int count = [sources_ count];
8090 case 0: return (offset_ == 0 ? count : offset_);
8091 case 1: return count - offset_;
8097 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8099 switch (indexPath.section) {
8100 case 0: idx = indexPath.row; break;
8101 case 1: idx = indexPath.row + offset_; break;
8105 return [sources_ objectAtIndex:idx];
8108 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8109 static NSString *cellIdentifier = @"SourceCell";
8111 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8112 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8113 [cell setSource:[self sourceAtIndexPath:indexPath]];
8114 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8119 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8120 Source *source = [self sourceAtIndexPath:indexPath];
8122 SourceController *controller = [[[SourceController alloc]
8123 initWithDatabase:database_
8127 [controller setDelegate:delegate_];
8129 [[self navigationController] pushViewController:controller animated:YES];
8132 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8133 Source *source = [self sourceAtIndexPath:indexPath];
8134 return [source record] != nil;
8137 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8138 if (editingStyle == UITableViewCellEditingStyleDelete) {
8139 Source *source = [self sourceAtIndexPath:indexPath];
8140 [Sources_ removeObjectForKey:[source key]];
8141 [delegate_ syncData];
8146 [delegate_ addTrivialSource:href_];
8147 [delegate_ syncData];
8150 - (NSString *) getWarning {
8151 NSString *href(href_);
8152 NSRange colon([href rangeOfString:@"://"]);
8153 if (colon.location != NSNotFound)
8154 href = [href substringFromIndex:(colon.location + 3)];
8155 href = [href stringByAddingPercentEscapes];
8156 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8157 href = [href stringByCachingURLWithCurrentCDN];
8159 NSURL *url([NSURL URLWithString:href]);
8161 NSStringEncoding encoding;
8162 NSError *error(nil);
8164 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8165 return [warning length] == 0 ? nil : warning;
8169 - (void) _endConnection:(NSURLConnection *)connection {
8170 // XXX: the memory management in this method is horribly awkward
8172 NSURLConnection **field = NULL;
8173 if (connection == trivial_)
8175 else if (connection == trivial_bz2_)
8176 field = &trivial_bz2_;
8177 else if (connection == trivial_gz_)
8178 field = &trivial_gz_;
8179 _assert(field != NULL);
8180 [connection release];
8185 trivial_bz2_ == nil &&
8188 [delegate_ releaseNetworkActivityIndicator];
8190 [delegate_ removeProgressHUD:hud_];
8196 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8199 UIAlertView *alert = [[[UIAlertView alloc]
8200 initWithTitle:UCLocalize("SOURCE_WARNING")
8203 cancelButtonTitle:UCLocalize("CANCEL")
8205 UCLocalize("ADD_ANYWAY"),
8209 [alert setContext:@"warning"];
8210 [alert setNumberOfRows:1];
8214 } else if (error_ != nil) {
8215 UIAlertView *alert = [[[UIAlertView alloc]
8216 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8217 message:[error_ localizedDescription]
8219 cancelButtonTitle:UCLocalize("OK")
8220 otherButtonTitles:nil
8223 [alert setContext:@"urlerror"];
8226 UIAlertView *alert = [[[UIAlertView alloc]
8227 initWithTitle:UCLocalize("NOT_REPOSITORY")
8228 message:UCLocalize("NOT_REPOSITORY_EX")
8230 cancelButtonTitle:UCLocalize("OK")
8231 otherButtonTitles:nil
8234 [alert setContext:@"trivial"];
8243 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8244 switch ([response statusCode]) {
8250 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8251 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8253 [self _endConnection:connection];
8256 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8257 [self _endConnection:connection];
8260 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8261 NSURL *url([NSURL URLWithString:href]);
8263 NSMutableURLRequest *request = [NSMutableURLRequest
8265 cachePolicy:NSURLRequestUseProtocolCachePolicy
8266 timeoutInterval:120.0
8269 [request setHTTPMethod:method];
8271 if (Machine_ != NULL)
8272 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8274 if ([url isCydiaSecure]) {
8275 if (UniqueID_ != nil)
8276 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8279 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8282 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8283 NSString *context([alert context]);
8285 if ([context isEqualToString:@"source"]) {
8288 NSString *href = [[alert textField] text];
8290 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8292 if (![href hasSuffix:@"/"])
8293 href_ = [href stringByAppendingString:@"/"];
8297 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8298 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8299 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8300 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8304 // XXX: this is stupid
8305 hud_ = [delegate_ addProgressHUD];
8306 [hud_ setText:UCLocalize("VERIFYING_URL")];
8307 [delegate_ retainNetworkActivityIndicator];
8316 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8317 } else if ([context isEqualToString:@"trivial"])
8318 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8319 else if ([context isEqualToString:@"urlerror"])
8320 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8321 else if ([context isEqualToString:@"warning"]) {
8335 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8340 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8342 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8343 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8344 [list_ setRowHeight:56];
8345 [(UITableView *) list_ setDataSource:self];
8346 [list_ setDelegate:self];
8347 [[self view] addSubview:list_];
8350 - (void) viewDidLoad {
8351 [super viewDidLoad];
8353 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8354 [self updateButtonsForEditingStatus:NO animated:NO];
8357 - (void) releaseSubviews {
8360 [super releaseSubviews];
8363 - (id) initWithDatabase:(Database *)database {
8364 if ((self = [super init]) != nil) {
8365 database_ = database;
8366 sources_ = [NSMutableArray arrayWithCapacity:16];
8370 - (void) reloadData {
8374 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8377 [sources_ removeAllObjects];
8378 [sources_ addObjectsFromArray:[database_ sources]];
8380 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8383 int count([sources_ count]);
8385 for (int i = 0; i != count; i++) {
8386 if ([[sources_ objectAtIndex:i] record] == nil)
8391 [list_ setEditing:NO];
8392 [self updateButtonsForEditingStatus:NO animated:NO];
8396 - (void) showAddSourcePrompt {
8397 UIAlertView *alert = [[[UIAlertView alloc]
8398 initWithTitle:UCLocalize("ENTER_APT_URL")
8401 cancelButtonTitle:UCLocalize("CANCEL")
8403 UCLocalize("ADD_SOURCE"),
8407 [alert setContext:@"source"];
8409 [alert setNumberOfRows:1];
8410 [alert addTextFieldWithValue:@"http://" label:@""];
8412 UITextInputTraits *traits = [[alert textField] textInputTraits];
8413 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8414 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8415 [traits setKeyboardType:UIKeyboardTypeURL];
8416 // XXX: UIReturnKeyDone
8417 [traits setReturnKeyType:UIReturnKeyNext];
8422 - (void) addButtonClicked {
8423 [self showAddSourcePrompt];
8426 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8427 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8428 initWithTitle:UCLocalize("ADD")
8429 style:UIBarButtonItemStylePlain
8431 action:@selector(addButtonClicked)
8432 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8434 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8435 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8436 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8438 action:@selector(editButtonClicked)
8439 ] autorelease] animated:animated];
8441 if (IsWildcat_ && !editing)
8442 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8443 initWithTitle:UCLocalize("SETTINGS")
8444 style:UIBarButtonItemStylePlain
8446 action:@selector(settingsButtonClicked)
8450 - (void) settingsButtonClicked {
8451 [delegate_ showSettings];
8454 - (void) editButtonClicked {
8455 [list_ setEditing:![list_ isEditing] animated:YES];
8457 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8463 /* Settings Controller {{{ */
8464 @interface SettingsController : CyteViewController <
8465 UITableViewDataSource,
8468 _transient Database *database_;
8469 // XXX: ok, "roledelegate_"?...
8470 _transient id roledelegate_;
8471 _H<UITableView, 2> table_;
8472 _H<UISegmentedControl> segment_;
8473 _H<UIView> container_;
8476 - (void) showDoneButton;
8477 - (void) resizeSegmentedControl;
8481 @implementation SettingsController
8484 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8486 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8487 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8488 [table_ setDelegate:self];
8489 [(UITableView *) table_ setDataSource:self];
8490 [[self view] addSubview:table_];
8492 NSArray *items = [NSArray arrayWithObjects:
8494 UCLocalize("HACKER"),
8495 UCLocalize("DEVELOPER"),
8497 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8498 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8499 [container_ addSubview:segment_];
8502 - (void) viewDidLoad {
8503 [super viewDidLoad];
8505 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8508 if ([Role_ isEqualToString:@"User"]) index = 0;
8509 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8510 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8512 [segment_ setSelectedSegmentIndex:index];
8513 [self showDoneButton];
8516 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8517 [self resizeSegmentedControl];
8520 - (void) releaseSubviews {
8525 [super releaseSubviews];
8528 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8529 if ((self = [super init]) != nil) {
8530 database_ = database;
8531 roledelegate_ = delegate;
8535 - (void) resizeSegmentedControl {
8536 CGFloat width = [[self view] frame].size.width;
8537 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8540 - (void) viewWillAppear:(BOOL)animated {
8541 [super viewWillAppear:animated];
8543 [self resizeSegmentedControl];
8546 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8547 [self resizeSegmentedControl];
8550 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8551 [self resizeSegmentedControl];
8555 NSString *role(nil);
8557 switch ([segment_ selectedSegmentIndex]) {
8558 case 0: role = @"User"; break;
8559 case 1: role = @"Hacker"; break;
8560 case 2: role = @"Developer"; break;
8565 if (![role isEqualToString:Role_]) {
8566 bool rolling(Role_ == nil);
8569 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8573 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8577 [roledelegate_ loadData];
8579 [roledelegate_ updateData];
8583 - (void) segmentChanged:(UISegmentedControl *)control {
8584 [self showDoneButton];
8587 - (void) saveAndClose {
8590 [[self navigationItem] setRightBarButtonItem:nil];
8591 [[self navigationController] dismissModalViewControllerAnimated:YES];
8594 - (void) doneButtonClicked {
8595 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8596 [spinner startAnimating];
8597 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8598 [[self navigationItem] setRightBarButtonItem:spinItem];
8600 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8603 - (void) showDoneButton {
8604 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8605 initWithTitle:UCLocalize("DONE")
8606 style:UIBarButtonItemStyleDone
8608 action:@selector(doneButtonClicked)
8609 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8612 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8613 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8617 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8621 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8622 return nil; // This method is required by the protocol.
8625 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8627 return UCLocalize("ROLE_EX");
8629 return [NSString stringWithFormat:
8630 @"%@: %@\n%@: %@\n%@: %@",
8631 UCLocalize("USER"), UCLocalize("USER_EX"),
8632 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8633 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8638 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8639 return section == 3 ? 44.0f : 0;
8642 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8643 return section == 3 ? container_ : nil;
8646 - (void) reloadData {
8649 [table_ reloadData];
8654 /* Stash Controller {{{ */
8655 @interface StashController : CyteViewController {
8656 _H<UIActivityIndicatorView> spinner_;
8657 _H<UILabel> status_;
8658 _H<UILabel> caption_;
8663 @implementation StashController
8666 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8667 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8669 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8670 CGRect spinrect = [spinner_ frame];
8671 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8672 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8673 [spinner_ setFrame:spinrect];
8674 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8675 [[self view] addSubview:spinner_];
8676 [spinner_ startAnimating];
8679 captrect.size.width = [[self view] frame].size.width;
8680 captrect.size.height = 40.0f;
8681 captrect.origin.x = 0;
8682 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8683 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8684 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8685 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8686 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8687 [caption_ setTextColor:[UIColor whiteColor]];
8688 [caption_ setBackgroundColor:[UIColor clearColor]];
8689 [caption_ setShadowColor:[UIColor blackColor]];
8690 [caption_ setTextAlignment:UITextAlignmentCenter];
8691 [[self view] addSubview:caption_];
8694 statusrect.size.width = [[self view] frame].size.width;
8695 statusrect.size.height = 30.0f;
8696 statusrect.origin.x = 0;
8697 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8698 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8699 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8700 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8701 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8702 [status_ setTextColor:[UIColor whiteColor]];
8703 [status_ setBackgroundColor:[UIColor clearColor]];
8704 [status_ setShadowColor:[UIColor blackColor]];
8705 [status_ setTextAlignment:UITextAlignmentCenter];
8706 [[self view] addSubview:status_];
8709 - (void) releaseSubviews {
8714 [super releaseSubviews];
8720 @interface CYURLCache : SDURLCache {
8725 @implementation CYURLCache
8727 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8730 else if ([event isEqualToString:@"no-cache"])
8732 else if ([event isEqualToString:@"store"])
8734 else if ([event isEqualToString:@"invalid"])
8736 else if ([event isEqualToString:@"memory"])
8738 else if ([event isEqualToString:@"disk"])
8740 else if ([event isEqualToString:@"miss"])
8743 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8747 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8748 if (NSURLResponse *response = [cached response])
8749 if (NSString *mime = [response MIMEType])
8750 if ([mime isEqualToString:@"text/cache-manifest"]) {
8751 NSURL *url([response URL]);
8754 NSLog(@"###: %@", [url absoluteString]);
8757 @synchronized (HostConfig_) {
8758 [CachedURLs_ addObject:url];
8762 [super storeCachedResponse:cached forRequest:request];
8767 @interface Cydia : UIApplication <
8768 ConfirmationControllerDelegate,
8771 UINavigationControllerDelegate,
8772 UITabBarControllerDelegate
8774 _H<UIWindow> window_;
8775 _H<CYTabBarController> tabbar_;
8776 _H<CydiaLoadingViewController> emulated_;
8778 _H<NSMutableArray> essential_;
8779 _H<NSMutableArray> broken_;
8781 Database *database_;
8783 _H<NSURL> starturl_;
8788 _H<StashController> stash_;
8797 @implementation Cydia
8799 - (void) beginUpdate {
8800 [tabbar_ beginUpdate];
8804 return [tabbar_ updating];
8808 if ([broken_ count] != 0) {
8809 int count = [broken_ count];
8811 UIAlertView *alert = [[[UIAlertView alloc]
8812 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8813 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8815 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8817 UCLocalize("TEMPORARY_IGNORE"),
8821 [alert setContext:@"fixhalf"];
8822 [alert setNumberOfRows:2];
8824 } else if (!Ignored_ && [essential_ count] != 0) {
8825 int count = [essential_ count];
8827 UIAlertView *alert = [[[UIAlertView alloc]
8828 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8829 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8831 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8833 UCLocalize("UPGRADE_ESSENTIAL"),
8834 UCLocalize("COMPLETE_UPGRADE"),
8838 [alert setContext:@"upgrade"];
8843 - (void) _saveConfig {
8849 NSString *error(nil);
8851 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8853 NSError *error(nil);
8854 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8855 NSLog(@"failure to save metadata data: %@", error);
8860 NSLog(@"failure to serialize metadata: %@", error);
8867 // Navigation controller for the queuing badge.
8868 - (UINavigationController *) queueNavigationController {
8869 NSArray *controllers = [tabbar_ viewControllers];
8870 return [controllers objectAtIndex:3];
8873 - (void) unloadData {
8874 [tabbar_ unloadData];
8877 - (void) _updateData {
8881 UINavigationController *navigation = [self queueNavigationController];
8883 id queuedelegate = nil;
8884 if ([[navigation viewControllers] count] > 0)
8885 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8887 [queuedelegate queueStatusDidChange];
8888 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8891 - (void) _refreshIfPossible:(NSDate *)update {
8892 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8894 bool recently = false;
8895 if (update != nil) {
8896 NSTimeInterval interval([update timeIntervalSinceNow]);
8897 if (interval <= 0 && interval > -(15*60))
8901 // Don't automatic refresh if:
8902 // - We already refreshed recently.
8903 // - We already auto-refreshed this launch.
8904 // - Auto-refresh is disabled.
8905 if (recently || loaded_ || ManualRefresh) {
8906 // If we are cancelling, we need to make sure it knows it's already loaded.
8909 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8911 // We are going to load, so remember that.
8914 SCNetworkReachabilityFlags flags; {
8915 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8916 SCNetworkReachabilityGetFlags(reachability, &flags);
8917 CFRelease(reachability);
8920 // XXX: this elaborate mess is what Apple is using to determine this? :(
8921 // XXX: do we care if the user has to intervene? maybe that's ok?
8923 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8924 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8925 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8926 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8927 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8928 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8932 // If we can reach the server, auto-refresh!
8934 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8940 - (void) refreshIfPossible {
8941 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8944 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8945 @synchronized (self) {
8946 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8947 [hud setText:UCLocalize("RELOADING_DATA")];
8949 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8952 [self removeProgressHUD:hud];
8956 [essential_ removeAllObjects];
8957 [broken_ removeAllObjects];
8959 NSArray *packages([database_ packages]);
8960 for (Package *package in packages) {
8962 [broken_ addObject:package];
8963 if ([package upgradableAndEssential:NO]) {
8964 if ([package essential])
8965 [essential_ addObject:package];
8970 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8973 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8974 [changesItem setBadgeValue:badge];
8975 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8976 [self setApplicationIconBadgeNumber:changes];
8979 [changesItem setBadgeValue:nil];
8980 [changesItem setAnimatedBadge:NO];
8981 [self setApplicationIconBadgeNumber:0];
8986 [self refreshIfPossible];
8989 - (void) updateData {
8995 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8998 - (void) disemulate {
8999 if (emulated_ == nil)
9002 [window_ addSubview:[tabbar_ view]];
9003 [[emulated_ view] removeFromSuperview];
9005 [window_ setUserInteractionEnabled:YES];
9008 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9009 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9011 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9013 UIViewController *parent;
9014 if (emulated_ == nil)
9023 [parent presentModalViewController:navigation animated:YES];
9026 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9027 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9029 if (navigation != nil)
9030 [navigation pushViewController:progress animated:YES];
9032 [self presentModalViewController:progress force:YES];
9034 [progress invoke:invocation withTitle:title];
9038 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9039 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9042 - (void) repairWithInvocation:(NSInvocation *)invocation {
9044 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9048 - (void) repairWithSelector:(SEL)selector {
9049 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9052 - (void) reloadData {
9053 [self reloadDataWithInvocation:nil];
9058 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9061 - (void) addSource:(NSDictionary *) source {
9065 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9066 AddSource(href, distribution, sections);
9069 - (void) addTrivialSource:(NSString *)href {
9070 AddSource(href, @"./");
9073 - (void) updateValues {
9078 pkgProblemResolver *resolver = [database_ resolver];
9080 resolver->InstallProtect();
9081 if (!resolver->Resolve(true))
9086 // XXX: this is a really crappy way of doing this.
9087 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9088 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9089 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9090 if ([tabbar_ updating])
9091 [tabbar_ cancelUpdate];
9093 if (![database_ prepare])
9096 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9097 [page setDelegate:self];
9098 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9101 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9102 [tabbar_ presentModalViewController:confirm_ animated:YES];
9108 @synchronized (self) {
9113 - (void) clearPackage:(Package *)package {
9114 @synchronized (self) {
9121 - (void) installPackages:(NSArray *)packages {
9122 @synchronized (self) {
9123 for (Package *package in packages)
9130 - (void) installPackage:(Package *)package {
9131 @synchronized (self) {
9138 - (void) removePackage:(Package *)package {
9139 @synchronized (self) {
9146 - (void) distUpgrade {
9147 @synchronized (self) {
9148 if (![database_ upgrade])
9155 [database_ perform];
9156 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9159 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9162 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9166 - (void) showSettings {
9167 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9170 - (void) retainNetworkActivityIndicator {
9171 if (activity_++ == 0)
9172 [self setNetworkActivityIndicatorVisible:YES];
9175 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9179 - (void) releaseNetworkActivityIndicator {
9180 if (--activity_ == 0)
9181 [self setNetworkActivityIndicatorVisible:NO];
9184 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9189 - (void) cancelAndClear:(bool)clear {
9190 @synchronized (self) {
9202 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9203 NSString *context([alert context]);
9205 if ([context isEqualToString:@"conffile"]) {
9206 FILE *input = [database_ input];
9207 if (button == [alert cancelButtonIndex])
9208 fprintf(input, "N\n");
9209 else if (button == [alert firstOtherButtonIndex])
9210 fprintf(input, "Y\n");
9213 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9214 } else if ([context isEqualToString:@"fixhalf"]) {
9215 if (button == [alert cancelButtonIndex]) {
9216 @synchronized (self) {
9217 for (Package *broken in (id) broken_) {
9220 NSString *id = [broken id];
9221 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9222 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9223 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9224 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9230 } else if (button == [alert firstOtherButtonIndex]) {
9231 [broken_ removeAllObjects];
9235 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9236 } else if ([context isEqualToString:@"upgrade"]) {
9237 if (button == [alert firstOtherButtonIndex]) {
9238 @synchronized (self) {
9239 for (Package *essential in (id) essential_)
9240 [essential install];
9245 } else if (button == [alert firstOtherButtonIndex] + 1) {
9247 } else if (button == [alert cancelButtonIndex]) {
9251 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9255 - (void) system:(NSString *)command {
9256 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9259 system([command UTF8String]);
9265 - (void) applicationWillSuspend {
9267 [super applicationWillSuspend];
9270 - (BOOL) isSafeToSuspend {
9273 NSLog(@"isSafeToSuspend: locked_ != 0");
9278 // Use external process status API internally.
9279 // This is probably a really bad idea.
9280 // XXX: what is the point of this? does this solve anything at all?
9281 uint64_t status = 0;
9283 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9284 notify_get_state(notify_token, &status);
9285 notify_cancel(notify_token);
9290 NSLog(@"isSafeToSuspend: status != 0");
9296 NSLog(@"isSafeToSuspend: -> true");
9301 - (void) applicationSuspend:(__GSEvent *)event {
9302 if ([self isSafeToSuspend])
9303 [super applicationSuspend:event];
9306 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9307 if ([self isSafeToSuspend])
9308 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9311 - (void) _setSuspended:(BOOL)value {
9312 if ([self isSafeToSuspend])
9313 [super _setSuspended:value];
9316 - (UIProgressHUD *) addProgressHUD {
9317 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9318 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9320 [window_ setUserInteractionEnabled:NO];
9322 UIViewController *target(tabbar_);
9323 if (UIViewController *modal = [target modalViewController])
9326 UIView *view([target view]);
9327 [view addSubview:hud];
9335 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9338 [hud removeFromSuperview];
9339 [window_ setUserInteractionEnabled:YES];
9342 - (CyteViewController *) pageForPackage:(NSString *)name {
9343 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9346 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9347 NSString *scheme([[url scheme] lowercaseString]);
9348 if ([[url absoluteString] length] <= [scheme length] + 3)
9350 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9351 NSArray *components([path pathComponents]);
9353 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9354 return [self pageForPackage:[components objectAtIndex:1]];
9356 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9359 NSString *base([components objectAtIndex:0]);
9361 CyteViewController *controller = nil;
9363 if ([base isEqualToString:@"url"]) {
9364 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9365 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9366 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9367 } else if (!external && [components count] == 1) {
9368 if ([base isEqualToString:@"manage"]) {
9369 controller = [[[ManageController alloc] init] autorelease];
9372 if ([base isEqualToString:@"sources"]) {
9373 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9376 if ([base isEqualToString:@"home"]) {
9377 controller = [[[HomeController alloc] init] autorelease];
9380 if ([base isEqualToString:@"sections"]) {
9381 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9384 if ([base isEqualToString:@"search"]) {
9385 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9388 if ([base isEqualToString:@"changes"]) {
9389 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9392 if ([base isEqualToString:@"installed"]) {
9393 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9395 } else if ([components count] == 2) {
9396 NSString *argument = [components objectAtIndex:1];
9398 if ([base isEqualToString:@"package"]) {
9399 controller = [self pageForPackage:argument];
9402 if (!external && [base isEqualToString:@"search"]) {
9403 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9406 if (!external && [base isEqualToString:@"sections"]) {
9407 if ([argument isEqualToString:@"all"])
9409 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9412 if (!external && [base isEqualToString:@"sources"]) {
9413 if ([argument isEqualToString:@"add"]) {
9414 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9415 [(SourcesController *)controller showAddSourcePrompt];
9417 Source *source = [database_ sourceWithKey:argument];
9418 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9422 if (!external && [base isEqualToString:@"launch"]) {
9423 [self launchApplicationWithIdentifier:argument suspended:NO];
9426 } else if (!external && [components count] == 3) {
9427 NSString *arg1 = [components objectAtIndex:1];
9428 NSString *arg2 = [components objectAtIndex:2];
9430 if ([base isEqualToString:@"package"]) {
9431 if ([arg2 isEqualToString:@"settings"]) {
9432 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9433 } else if ([arg2 isEqualToString:@"files"]) {
9434 if (Package *package = [database_ packageWithName:arg1]) {
9435 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9436 [(FileTable *)controller setPackage:package];
9442 [controller setDelegate:self];
9446 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9447 CyteViewController *page([self pageForURL:url forExternal:external]);
9450 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9451 [nav setViewControllers:[NSArray arrayWithObject:page]];
9452 [tabbar_ setUnselectedViewController:nav];
9458 - (void) applicationOpenURL:(NSURL *)url {
9459 [super applicationOpenURL:url];
9464 [self openCydiaURL:url forExternal:YES];
9467 - (void) applicationWillResignActive:(UIApplication *)application {
9468 // Stop refreshing if you get a phone call or lock the device.
9469 if ([tabbar_ updating])
9470 [tabbar_ cancelUpdate];
9472 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9473 [super applicationWillResignActive:application];
9476 - (void) applicationWillTerminate:(UIApplication *)application {
9478 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9479 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9480 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9485 - (void) setConfigurationData:(NSString *)data {
9486 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9488 if (!conffile_r(data)) {
9489 lprintf("E:invalid conffile\n");
9493 NSString *ofile = conffile_r[1];
9494 //NSString *nfile = conffile_r[2];
9496 UIAlertView *alert = [[[UIAlertView alloc]
9497 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9498 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9500 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9502 UCLocalize("ACCEPT_NEW_COPY"),
9503 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9507 [alert setContext:@"conffile"];
9508 [alert setNumberOfRows:2];
9512 - (void) addStashController {
9514 stash_ = [[[StashController alloc] init] autorelease];
9515 [window_ addSubview:[stash_ view]];
9518 - (void) removeStashController {
9519 [[stash_ view] removeFromSuperview];
9525 [self setIdleTimerDisabled:YES];
9527 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9528 UpdateExternalStatus(1);
9529 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9530 UpdateExternalStatus(0);
9532 [self removeStashController];
9534 if (ExecFork() == 0) {
9535 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9536 perror("launchctl stop");
9540 - (void) setupViewControllers {
9541 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9543 NSMutableArray *items([NSMutableArray arrayWithObjects:
9544 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9545 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9546 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9547 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9551 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9552 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9554 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9557 NSMutableArray *controllers([NSMutableArray array]);
9558 for (UITabBarItem *item in items) {
9559 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9560 [controller setTabBarItem:item];
9561 [controllers addObject:controller];
9563 [tabbar_ setViewControllers:controllers];
9565 [tabbar_ setUpdateDelegate:self];
9568 - (void) applicationDidFinishLaunching:(id)unused {
9570 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9571 [self setApplicationSupportsShakeToEdit:NO];
9573 @synchronized (HostConfig_) {
9574 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9577 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9578 initWithMemoryCapacity:524288
9579 diskCapacity:10485760
9580 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9583 [CydiaWebViewController _initialize];
9585 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9587 // this would disallow http{,s} URLs from accessing this data
9588 //[WebView registerURLSchemeAsLocal:@"cydia"];
9590 Font12_ = [UIFont systemFontOfSize:12];
9591 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9592 Font14_ = [UIFont systemFontOfSize:14];
9593 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9594 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9596 essential_ = [NSMutableArray arrayWithCapacity:4];
9597 broken_ = [NSMutableArray arrayWithCapacity:4];
9599 // XXX: I really need this thing... like, seriously... I'm sorry
9600 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9602 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9603 [window_ orderFront:self];
9604 [window_ makeKey:self];
9605 [window_ setHidden:NO];
9608 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9609 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9610 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9611 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9612 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9613 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9614 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9615 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9616 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9619 [self addStashController];
9620 // XXX: this would be much cleaner as a yieldToSelector:
9621 // that way the removeStashController could happen right here inline
9622 // we also could no longer require the useless stash_ field anymore
9623 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9627 database_ = [Database sharedInstance];
9628 [database_ setDelegate:self];
9630 [window_ setUserInteractionEnabled:NO];
9631 [self setupViewControllers];
9633 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9634 [window_ addSubview:[emulated_ view]];
9636 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9640 - (NSArray *) defaultStartPages {
9641 NSMutableArray *standard = [NSMutableArray array];
9642 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9643 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9644 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9646 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9648 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9649 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9651 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9658 [window_ setUserInteractionEnabled:YES];
9659 [self showSettings];
9662 if ([emulated_ modalViewController] != nil)
9663 [emulated_ dismissModalViewControllerAnimated:YES];
9664 [window_ setUserInteractionEnabled:NO];
9672 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9673 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9674 int standardIndex = 0;
9675 NSArray *standard = [self defaultStartPages];
9682 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9683 if (valid && closed != nil) {
9684 NSTimeInterval interval([closed timeIntervalSinceNow]);
9685 // XXX: Is 15 minutes the optimal time here?
9686 if (interval > 0 && interval <= -(15*60))
9690 if (valid && [saved count] != [standard count])
9694 for (unsigned int i = 0; i < [standard count]; i++) {
9695 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9696 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9697 // but it's good enough for now.
9698 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9705 NSArray *items = nil;
9707 [tabbar_ setSelectedIndex:savedIndex];
9710 [tabbar_ setSelectedIndex:standardIndex];
9714 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9715 NSArray *stack = [items objectAtIndex:tab];
9716 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9717 NSMutableArray *current = [NSMutableArray array];
9719 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9720 NSString *addr = [stack objectAtIndex:nav];
9721 NSURL *url = [NSURL URLWithString:addr];
9722 CyteViewController *page = [self pageForURL:url forExternal:NO];
9724 [current addObject:page];
9727 [navigation setViewControllers:current];
9730 // (Try to) show the startup URL.
9731 if (starturl_ != nil) {
9732 [self openCydiaURL:starturl_ forExternal:NO];
9737 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9738 if (item != nil && IsWildcat_) {
9739 [sheet showFromBarButtonItem:item animated:YES];
9741 [sheet showInView:window_];
9745 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9746 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9747 [progress setTitle:task];
9748 [progress addProgressEvent:event];
9751 - (void) addProgressEventForTask:(NSArray *)data {
9752 CydiaProgressEvent *event([data objectAtIndex:0]);
9753 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9754 [self addProgressEvent:event forTask:task];
9757 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9758 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9764 id Alloc_(id self, SEL selector) {
9765 id object = alloc_(self, selector);
9766 lprintf("[%s]A-%p\n", self->isa->name, object);
9771 id Dealloc_(id self, SEL selector) {
9772 id object = dealloc_(self, selector);
9773 lprintf("[%s]D-%p\n", self->isa->name, object);
9777 Class $WebDefaultUIKitDelegate;
9779 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9780 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9781 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9782 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9785 static NSSet *MobilizedFiles_;
9787 static NSURL *MobilizeURL(NSURL *url) {
9788 NSString *path([url path]);
9789 if ([path hasPrefix:@"/var/root/"]) {
9790 NSString *file([path substringFromIndex:10]);
9791 if ([MobilizedFiles_ containsObject:file])
9792 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9798 Class $CFXPreferencesPropertyListSource;
9799 @class CFXPreferencesPropertyListSource;
9801 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9802 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9803 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9804 url = MobilizeURL(url);
9805 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9806 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9812 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9813 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9814 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9815 url = MobilizeURL(url);
9816 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9817 //NSLog(@"%@ %@", [url absoluteString], value);
9823 Class $NSURLConnection;
9825 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9826 NSMutableURLRequest *copy([request mutableCopy]);
9828 NSURL *url([copy URL]);
9830 NSString *href([url absoluteString]);
9831 NSString *host([url host]);
9832 NSString *scheme([[url scheme] lowercaseString]);
9834 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9836 @synchronized (HostConfig_) {
9837 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9838 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9839 [copy setHTTPShouldUsePipelining:YES];
9841 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9842 if ([control isEqualToString:@"max-age=0"])
9843 if ([CachedURLs_ containsObject:href]) {
9845 NSLog(@"~~~: %@", href);
9848 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9850 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9851 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9852 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9856 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9860 int main(int argc, char *argv[]) {
9861 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9865 UpdateExternalStatus(0);
9867 if (Class $UIDevice = objc_getClass("UIDevice")) {
9868 UIDevice *device([$UIDevice currentDevice]);
9869 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9873 UIScreen *screen([UIScreen mainScreen]);
9874 if ([screen respondsToSelector:@selector(scale)])
9875 ScreenScale_ = [screen scale];
9879 UIDevice *device([UIDevice currentDevice]);
9880 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9883 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9884 if (idiom == UIUserInterfaceIdiomPhone)
9886 else if (idiom == UIUserInterfaceIdiomPad)
9889 NSLog(@"unknown UIUserInterfaceIdiom!");
9892 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9894 HostConfig_ = [[[NSObject alloc] init] autorelease];
9895 @synchronized (HostConfig_) {
9896 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9897 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9898 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9899 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9900 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9903 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9905 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9907 MobilizedFiles_ = [NSMutableSet setWithObjects:
9908 @"Library/Preferences/com.apple.Accessibility.plist",
9909 @"Library/Preferences/com.apple.preferences.sounds.plist",
9912 /* Library Hacks {{{ */
9913 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9915 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9917 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9918 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9919 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9920 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9923 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9924 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9925 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9926 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9929 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9930 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9931 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9932 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9933 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9936 $NSURLConnection = objc_getClass("NSURLConnection");
9937 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9938 if (NSURLConnection$init$ != NULL) {
9939 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9940 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9943 /* Set Locale {{{ */
9944 Locale_ = CFLocaleCopyCurrent();
9945 Languages_ = [NSLocale preferredLanguages];
9947 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9948 //NSLog(@"%@", [Languages_ description]);
9951 if (Locale_ != NULL)
9952 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9953 else if (Languages_ != nil && [Languages_ count] != 0)
9954 lang = [[Languages_ objectAtIndex:0] UTF8String];
9956 // XXX: consider just setting to C and then falling through?
9960 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9961 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9964 NSLog(@"Setting Language: %s", lang);
9967 setenv("LANG", lang, true);
9968 std::setlocale(LC_ALL, lang);
9972 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9974 /* Parse Arguments {{{ */
9975 bool substrate(false);
9981 for (int argi(1); argi != argc; ++argi)
9982 if (strcmp(argv[argi], "--") == 0) {
9984 argv[argi] = argv[0];
9990 for (int argi(1); argi != arge; ++argi)
9991 if (strcmp(args[argi], "--substrate") == 0)
9994 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9998 App_ = [[NSBundle mainBundle] bundlePath];
10004 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10005 alloc_ = alloc->method_imp;
10006 alloc->method_imp = (IMP) &Alloc_;*/
10008 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10009 dealloc_ = dealloc->method_imp;
10010 dealloc->method_imp = (IMP) &Dealloc_;*/
10012 /* System Information {{{ */
10016 size = sizeof(maxproc);
10017 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10018 perror("sysctlbyname(\"kern.maxproc\", ?)");
10019 else if (maxproc < 64) {
10021 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10022 perror("sysctlbyname(\"kern.maxproc\", #)");
10025 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10026 char *osversion = new char[size];
10027 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10028 perror("sysctlbyname(\"kern.osversion\", ?)");
10030 System_ = [NSString stringWithUTF8String:osversion];
10032 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10033 char *machine = new char[size];
10034 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10035 perror("sysctlbyname(\"hw.machine\", ?)");
10037 Machine_ = machine;
10039 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10040 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10041 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10043 UniqueID_ = [device uniqueIdentifier];
10045 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10046 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10047 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10049 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10050 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10051 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10053 if (mcc != NULL && mnc != NULL)
10054 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10061 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10062 Build_ = [system objectForKey:@"ProductBuildVersion"];
10063 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10064 Product_ = [info objectForKey:@"SafariProductVersion"];
10065 Safari_ = [info objectForKey:@"CFBundleVersion"];
10068 /* Load Database {{{ */
10070 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10072 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10074 if (Metadata_ == NULL)
10075 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10077 Settings_ = [Metadata_ objectForKey:@"Settings"];
10079 Packages_ = [Metadata_ objectForKey:@"Packages"];
10081 Values_ = [Metadata_ objectForKey:@"Values"];
10082 Sections_ = [Metadata_ objectForKey:@"Sections"];
10083 Sources_ = [Metadata_ objectForKey:@"Sources"];
10085 Token_ = [Metadata_ objectForKey:@"Token"];
10087 Version_ = [Metadata_ objectForKey:@"Version"];
10089 @synchronized (HostConfig_) {
10090 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10094 if (Settings_ != nil)
10095 Role_ = [Settings_ objectForKey:@"Role"];
10097 if (Values_ == nil) {
10098 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10099 [Metadata_ setObject:Values_ forKey:@"Values"];
10102 if (Sections_ == nil) {
10103 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10104 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10107 if (Sources_ == nil) {
10108 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10109 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10112 if (Version_ == nil) {
10113 Version_ = [NSNumber numberWithUnsignedInt:0];
10114 [Metadata_ setObject:Version_ forKey:@"Version"];
10117 @synchronized (HostConfig_) {
10118 if (CydiaSource_ == nil) {
10119 CydiaSource_ = @"apt.saurik.com";
10120 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10124 if ([Version_ unsignedIntValue] == 0) {
10125 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10126 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10127 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10128 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10130 Version_ = [NSNumber numberWithUnsignedInt:1];
10131 [Metadata_ setObject:Version_ forKey:@"Version"];
10140 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10143 if (Packages_ != nil) {
10145 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10149 [Metadata_ removeObjectForKey:@"Packages"];
10155 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10157 #define MobileSubstrate_(name) \
10158 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10159 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10160 if (handle == NULL) \
10161 NSLog(@"%s", dlerror()); \
10164 MobileSubstrate_(Activator)
10165 MobileSubstrate_(libstatusbar)
10166 MobileSubstrate_(SimulatedKeyEvents)
10167 MobileSubstrate_(WinterBoard)
10169 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10170 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10172 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10174 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10175 unlink("/tmp/.cydia.fw");
10177 } else if (access("/User", F_OK) != 0 || version < 4) {
10180 system("/usr/libexec/cydia/firmware.sh");
10184 _assert([[NSFileManager defaultManager]
10185 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10186 withIntermediateDirectories:YES
10191 if (access("/tmp/cydia.chk", F_OK) == 0) {
10192 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10193 _assert(errno == ENOENT);
10194 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10195 _assert(errno == ENOENT);
10198 /* APT Initialization {{{ */
10199 _assert(pkgInitConfig(*_config));
10200 _assert(pkgInitSystem(*_config, _system));
10203 _config->Set("APT::Acquire::Translation", lang);
10205 // XXX: this timeout might be important :(
10206 //_config->Set("Acquire::http::Timeout", 15);
10208 _config->Set("Acquire::http::MaxParallel", 3);
10210 /* Color Choices {{{ */
10211 space_ = CGColorSpaceCreateDeviceRGB();
10213 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10214 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10215 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10216 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10217 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10218 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10219 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10220 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10221 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10223 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10224 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10226 /* UIKit Configuration {{{ */
10227 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10228 if ($GSFontSetUseLegacyFontMetrics != NULL)
10229 $GSFontSetUseLegacyFontMetrics(YES);
10231 // XXX: I have a feeling this was important
10232 //UIKeyboardDisableAutomaticAppearance();
10235 Colon_ = UCLocalize("COLON_DELIMITED");
10236 Elision_ = UCLocalize("ELISION");
10237 Error_ = UCLocalize("ERROR");
10238 Warning_ = UCLocalize("WARNING");
10241 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10243 CGColorSpaceRelease(space_);
10244 CFRelease(Locale_);