1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
210 #define Cydia_ CYDIA_VERSION
212 #define lprintf(args...) fprintf(stderr, args)
215 #define TraceLogging (1 && !ForRelease)
216 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
217 #define ProfileTimes (0 && !ForRelease)
218 #define ForSaurik (0 && !ForRelease)
219 #define LogBrowser (0 && !ForRelease)
220 #define TrackResize (0 && !ForRelease)
221 #define ManualRefresh (1 && !ForRelease)
222 #define ShowInternals (0 && !ForRelease)
223 #define AlwaysReload (0 && !ForRelease)
224 #define TryIndexedCollation (0 && !ForRelease)
228 #define _trace(args...)
233 #define _profile(name) {
236 #define PrintTimes() do {} while (false)
239 // Hash Functions/Structures {{{
240 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
250 static _finline NSString *CydiaURL(NSString *path) {
252 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
253 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
254 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
255 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
256 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
258 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
261 static _finline void UpdateExternalStatus(uint64_t newStatus) {
263 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
264 notify_set_state(notify_token, newStatus);
265 notify_cancel(notify_token);
267 notify_post("com.saurik.Cydia.status");
270 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
271 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
272 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
275 /* NSForcedOrderingSearch doesn't work on the iPhone */
276 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
277 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
278 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
280 /* Insertion Sort {{{ */
282 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
283 const char *ptr = (const char *)list;
285 CFIndex half = count / 2;
286 const char *probe = ptr + elementSize * half;
287 CFComparisonResult cr = comparator(element, probe, context);
288 if (0 == cr) return (probe - (const char *)list) / elementSize;
289 ptr = (cr < 0) ? ptr : probe + elementSize;
290 count = (cr < 0) ? half : (half + (count & 1) - 1);
292 return (ptr - (const char *)list) / elementSize;
295 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
296 const char *ptr = (const char *)list;
298 CFIndex half = count / 2;
299 const char *probe = ptr + elementSize * half;
300 CFComparisonResult cr = comparator(element, probe, context);
301 if (0 == cr) return (probe - (const char *)list) / elementSize;
302 ptr = (cr < 0) ? ptr : probe + elementSize;
303 count = (cr < 0) ? half : (half + (count & 1) - 1);
305 return (ptr - (const char *)list) / elementSize;
308 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
309 if (range.length == 0)
311 const void **values(new const void *[range.length]);
312 CFArrayGetValues(array, range, values);
314 #if HistogramInsertionSort > 0
315 uint32_t total(0), *offsets(new uint32_t[range.length]);
318 for (CFIndex index(1); index != range.length; ++index) {
319 const void *value(values[index]);
320 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
321 CFIndex correct(index);
322 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
323 #if HistogramInsertionSort > 1
324 NSLog(@"%@ < %@", value, values[correct - 1]);
329 if (correct != index) {
330 size_t offset(index - correct);
331 #if HistogramInsertionSort
335 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
337 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
338 values[correct] = value;
342 CFArrayReplaceValues(array, range, values, range.length);
345 #if HistogramInsertionSort > 0
346 for (CFIndex index(0); index != range.length; ++index)
347 if (offsets[index] != 0)
348 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
349 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
356 /* Apple Bug Fixes {{{ */
357 @implementation UIWebDocumentView (Cydia)
359 - (void) _setScrollerOffset:(CGPoint)offset {
360 UIScroller *scroller([self _scroller]);
362 CGSize size([scroller contentSize]);
363 CGSize bounds([scroller bounds].size);
366 max.x = size.width - bounds.width;
367 max.y = size.height - bounds.height;
375 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
376 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
378 [scroller setOffset:offset];
384 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
385 size_t length([self length] - state->state);
388 else if (length > count)
390 for (size_t i(0); i != length; ++i)
391 objects[i] = [self item:state->state++];
392 state->itemsPtr = objects;
393 state->mutationsPtr = (unsigned long *) self;
397 /* Cydia NSString Additions {{{ */
398 @interface NSString (Cydia)
399 - (NSComparisonResult) compareByPath:(NSString *)other;
400 - (NSString *) stringByCachingURLWithCurrentCDN;
401 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
404 @implementation NSString (Cydia)
406 - (NSComparisonResult) compareByPath:(NSString *)other {
407 NSString *prefix = [self commonPrefixWithString:other options:0];
408 size_t length = [prefix length];
410 NSRange lrange = NSMakeRange(length, [self length] - length);
411 NSRange rrange = NSMakeRange(length, [other length] - length);
413 lrange = [self rangeOfString:@"/" options:0 range:lrange];
414 rrange = [other rangeOfString:@"/" options:0 range:rrange];
416 NSComparisonResult value;
418 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
419 value = NSOrderedSame;
420 else if (lrange.location == NSNotFound)
421 value = NSOrderedAscending;
422 else if (rrange.location == NSNotFound)
423 value = NSOrderedDescending;
425 value = NSOrderedSame;
427 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
428 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
429 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
430 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
432 NSComparisonResult result = [lpath compare:rpath];
433 return result == NSOrderedSame ? value : result;
436 - (NSString *) stringByCachingURLWithCurrentCDN {
438 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
439 withString:@"://cache.cydia.saurik.com/"
443 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
444 return [(id)CFURLCreateStringByAddingPercentEscapes(
449 kCFStringEncodingUTF8
456 /* C++ NSString Wrapper Cache {{{ */
457 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
458 return size == 0 ? NULL :
459 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
460 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
463 static _finline CFStringRef CYStringCreate(const char *data) {
464 return CYStringCreate(data, strlen(data));
473 _finline void clear_() {
474 if (cache_ != NULL) {
481 _finline bool empty() const {
485 _finline size_t size() const {
489 _finline char *data() const {
493 _finline void clear() {
498 _finline CYString() :
505 _finline ~CYString() {
509 void operator =(const CYString &rhs) {
513 if (rhs.cache_ == nil)
516 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
519 void copy(apr_pool_t *pool) {
520 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
521 memcpy(temp, data_, size_);
526 void set(apr_pool_t *pool, const char *data, size_t size) {
532 data_ = const_cast<char *>(data);
540 _finline void set(apr_pool_t *pool, const char *data) {
541 set(pool, data, data == NULL ? 0 : strlen(data));
544 _finline void set(apr_pool_t *pool, const std::string &rhs) {
545 set(pool, rhs.data(), rhs.size());
548 bool operator ==(const CYString &rhs) const {
549 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
552 _finline operator CFStringRef() {
554 cache_ = CYStringCreate(data_, size_);
558 _finline operator id() {
559 return (NSString *) static_cast<CFStringRef>(*this);
562 _finline operator const char *() {
563 return reinterpret_cast<const char *>(data_);
567 /* C++ NSString Algorithm Adapters {{{ */
569 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
572 struct NSStringMapHash :
573 std::unary_function<NSString *, size_t>
575 _finline size_t operator ()(NSString *value) const {
576 return CFStringHashNSString((CFStringRef) value);
580 struct NSStringMapLess :
581 std::binary_function<NSString *, NSString *, bool>
583 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
584 return [lhs compare:rhs] == NSOrderedAscending;
588 struct NSStringMapEqual :
589 std::binary_function<NSString *, NSString *, bool>
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
593 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
594 //[lhs isEqualToString:rhs];
599 /* CoreGraphics Primitives {{{ */
604 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
605 CGFloat color[] = {red, green, blue, alpha};
606 return CGColorCreate(space, color);
615 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
616 color_(Create_(space, red, green, blue, alpha))
618 Set(space, red, green, blue, alpha);
623 CGColorRelease(color_);
630 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
632 color_ = Create_(space, red, green, blue, alpha);
635 operator CGColorRef() {
641 /* Random Global Variables {{{ */
642 static const int PulseInterval_ = 50000;
644 static const NSString *UI_;
647 static bool RestartSubstrate_;
648 static NSArray *Finishes_;
650 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
651 #define NotifyConfig_ "/etc/notify.conf"
653 static bool Queuing_;
655 static CYColor Blue_;
656 static CYColor Blueish_;
657 static CYColor Black_;
659 static CYColor White_;
660 static CYColor Gray_;
661 static CYColor Green_;
662 static CYColor Purple_;
663 static CYColor Purplish_;
665 static UIColor *InstallingColor_;
666 static UIColor *RemovingColor_;
668 static NSString *App_;
670 static BOOL Advanced_;
671 static BOOL Ignored_;
673 static _H<UIFont> Font12_;
674 static _H<UIFont> Font12Bold_;
675 static _H<UIFont> Font14_;
676 static _H<UIFont> Font18Bold_;
677 static _H<UIFont> Font22Bold_;
679 static const char *Machine_ = NULL;
680 static NSString *System_ = nil;
681 static NSString *SerialNumber_ = nil;
682 static NSString *ChipID_ = nil;
683 static NSString *BBSNum_ = nil;
684 static _H<NSString> Token_;
685 static NSString *UniqueID_ = nil;
686 static NSString *PLMN_ = nil;
687 static NSString *Build_ = nil;
688 static NSString *Product_ = nil;
689 static NSString *Safari_ = nil;
691 static CFLocaleRef Locale_;
692 static NSArray *Languages_;
693 static CGColorSpaceRef space_;
695 static NSDictionary *SectionMap_;
696 static NSMutableDictionary *Metadata_;
697 static _transient NSMutableDictionary *Settings_;
698 static _transient NSString *Role_;
699 static _transient NSMutableDictionary *Packages_;
700 static _transient NSMutableDictionary *Values_;
701 static _transient NSMutableDictionary *Sections_;
702 static _transient NSMutableDictionary *Sources_;
703 static _transient NSNumber *Version_;
704 static _transient _H<NSString> CydiaSource_;
705 static bool Changed_;
709 static CGFloat ScreenScale_;
710 static NSString *Idiom_;
712 static _H<NSMutableDictionary> SessionData_;
713 static _H<NSObject> HostConfig_;
714 static _H<NSMutableSet> BridgedHosts_;
715 static _H<NSMutableSet> TokenHosts_;
716 static _H<NSMutableSet> InsecureHosts_;
717 static _H<NSMutableSet> PipelinedHosts_;
718 static _H<NSMutableSet> CachedURLs_;
720 static NSString *kCydiaProgressEventTypeError = @"Error";
721 static NSString *kCydiaProgressEventTypeInformation = @"Information";
722 static NSString *kCydiaProgressEventTypeStatus = @"Status";
723 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
726 static void AddSource(NSDictionary *source) {
727 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
731 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
732 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
735 distribution, @"Distribution",
736 sections ?: [NSMutableArray array], @"Sections",
740 static void WriteSources() {
741 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
742 _assert(file != NULL);
744 fprintf(file, "deb http://%s/ tangelo main\n",
745 [CydiaSource_ UTF8String]
748 for (NSString *key in [Sources_ allKeys]) {
749 NSDictionary *source([Sources_ objectForKey:key]);
751 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
753 fprintf(file, "%s %s %s%s%s\n",
754 [[source objectForKey:@"Type"] UTF8String],
755 [[source objectForKey:@"URI"] UTF8String],
756 [[source objectForKey:@"Distribution"] UTF8String],
757 [sections count] == 0 ? "" : " ",
758 [[sections componentsJoinedByString:@" "] UTF8String]
765 /* Display Helpers {{{ */
766 inline float Interpolate(float begin, float end, float fraction) {
767 return (end - begin) * fraction + begin;
770 static _finline const char *StripVersion_(const char *version) {
771 const char *colon(strchr(version, ':'));
772 return colon == NULL ? version : colon + 1;
775 NSString *LocalizeSection(NSString *section) {
776 static Pcre title_r("^(.*?) \\((.*)\\)$");
777 if (title_r(section)) {
778 NSString *parent(title_r[1]);
779 NSString *child(title_r[2]);
781 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
782 LocalizeSection(parent),
783 LocalizeSection(child)
787 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
790 NSString *Simplify(NSString *title) {
791 const char *data = [title UTF8String];
792 size_t size = [title length];
794 static Pcre square_r("^\\[(.*)\\]$");
795 if (square_r(data, size))
796 return Simplify(square_r[1]);
798 static Pcre paren_r("^\\((.*)\\)$");
799 if (paren_r(data, size))
800 return Simplify(paren_r[1]);
802 static Pcre title_r("^(.*?) \\((.*)\\)$");
803 if (title_r(data, size))
804 return Simplify(title_r[1]);
810 NSString *GetLastUpdate() {
811 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
814 return UCLocalize("NEVER_OR_UNKNOWN");
816 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
817 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
819 CFRelease(formatter);
821 return [(NSString *) formatted autorelease];
824 bool isSectionVisible(NSString *section) {
825 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
826 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
827 return hidden == nil || ![hidden boolValue];
830 static NSObject *CYIOGetValue(const char *path, NSString *property) {
831 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
832 if (entry == MACH_PORT_NULL)
835 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
836 IOObjectRelease(entry);
840 return [(id) value autorelease];
843 static NSString *CYHex(NSData *data, bool reverse = false) {
847 size_t length([data length]);
848 uint8_t bytes[length];
849 [data getBytes:bytes];
851 char string[length * 2 + 1];
852 for (size_t i(0); i != length; ++i)
853 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
855 return [NSString stringWithUTF8String:string];
860 /* Delegate Prototypes {{{ */
863 @class CydiaProgressEvent;
865 @protocol DatabaseDelegate
866 - (void) repairWithSelector:(SEL)selector;
867 - (void) setConfigurationData:(NSString *)data;
868 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
871 @class CYPackageController;
873 @protocol CydiaDelegate
875 - (void) retainNetworkActivityIndicator;
876 - (void) releaseNetworkActivityIndicator;
877 - (void) clearPackage:(Package *)package;
878 - (void) installPackage:(Package *)package;
879 - (void) installPackages:(NSArray *)packages;
880 - (void) removePackage:(Package *)package;
881 - (void) beginUpdate;
883 - (void) distUpgrade;
887 - (void) addSource:(NSDictionary *)source;
888 - (void) addTrivialSource:(NSString *)href;
889 - (void) showSettings;
890 - (UIProgressHUD *) addProgressHUD;
891 - (void) removeProgressHUD:(UIProgressHUD *)hud;
892 - (CyteViewController *) pageForPackage:(NSString *)name;
893 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
894 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
898 /* Status Delegation {{{ */
900 public pkgAcquireStatus
903 _transient NSObject<ProgressDelegate> *delegate_;
913 void setDelegate(NSObject<ProgressDelegate> *delegate) {
914 delegate_ = delegate;
917 NSObject<ProgressDelegate> *getDelegate() const {
921 virtual bool MediaChange(std::string media, std::string drive) {
925 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
928 virtual void Fetch(pkgAcquire::ItemDesc &item) {
929 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
930 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
931 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
934 virtual void Done(pkgAcquire::ItemDesc &item) {
937 virtual void Fail(pkgAcquire::ItemDesc &item) {
939 item.Owner->Status == pkgAcquire::Item::StatIdle ||
940 item.Owner->Status == pkgAcquire::Item::StatDone
944 std::string &error(item.Owner->ErrorText);
948 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
949 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
952 virtual bool Pulse(pkgAcquire *Owner) {
953 bool value = pkgAcquireStatus::Pulse(Owner);
956 double(CurrentBytes + CurrentItems) /
957 double(TotalBytes + TotalItems)
960 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
961 [NSNumber numberWithDouble:percent], @"Percent",
963 [NSNumber numberWithDouble:CurrentBytes], @"Current",
964 [NSNumber numberWithDouble:TotalBytes], @"Total",
965 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
966 nil] waitUntilDone:YES];
968 if (value && ![delegate_ isProgressCancelled])
976 _finline bool WasCancelled() const {
980 virtual void Start() {
981 pkgAcquireStatus::Start();
982 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
985 virtual void Stop() {
986 pkgAcquireStatus::Stop();
987 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
988 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
992 /* Database Interface {{{ */
993 typedef std::map< unsigned long, _H<Source> > SourceMap;
995 @interface Database : NSObject {
1001 pkgCacheFile cache_;
1002 pkgDepCache::Policy *policy_;
1003 pkgRecords *records_;
1004 pkgProblemResolver *resolver_;
1005 pkgAcquire *fetcher_;
1007 SPtr<pkgPackageManager> manager_;
1008 pkgSourceList *list_;
1010 SourceMap sourceMap_;
1011 _H<NSMutableArray> sourceList_;
1013 CFMutableArrayRef packages_;
1015 _transient NSObject<DatabaseDelegate> *delegate_;
1016 _transient NSObject<ProgressDelegate> *progress_;
1024 std::map<const char *, _H<NSString> > sections_;
1027 + (Database *) sharedInstance;
1030 - (void) _readCydia:(NSNumber *)fd;
1031 - (void) _readStatus:(NSNumber *)fd;
1032 - (void) _readOutput:(NSNumber *)fd;
1036 - (Package *) packageWithName:(NSString *)name;
1038 - (pkgCacheFile &) cache;
1039 - (pkgDepCache::Policy *) policy;
1040 - (pkgRecords *) records;
1041 - (pkgProblemResolver *) resolver;
1042 - (pkgAcquire &) fetcher;
1043 - (pkgSourceList &) list;
1044 - (NSArray *) packages;
1045 - (NSArray *) sources;
1046 - (Source *) sourceWithKey:(NSString *)key;
1047 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1055 - (void) updateWithStatus:(Status &)status;
1057 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1059 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1060 - (NSObject<ProgressDelegate> *) progressDelegate;
1062 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1064 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1068 /* ProgressEvent Implementation {{{ */
1069 @implementation CydiaProgressEvent
1071 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1072 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1075 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1076 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1077 [event setPackage:package];
1081 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1082 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1084 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1085 NSArray *fields([description componentsSeparatedByString:@" "]);
1086 [event setItem:fields];
1088 if ([fields count] > 3) {
1089 [event setPackage:[fields objectAtIndex:2]];
1090 [event setVersion:[fields objectAtIndex:3]];
1093 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1098 + (NSArray *) _attributeKeys {
1099 return [NSArray arrayWithObjects:
1109 - (NSArray *) attributeKeys {
1110 return [[self class] _attributeKeys];
1113 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1114 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1117 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1118 if ((self = [super init]) != nil) {
1124 - (NSString *) message {
1128 - (NSString *) type {
1132 - (NSArray *) item {
1133 return (id) item_ ?: [NSNull null];
1136 - (void) setItem:(NSArray *)item {
1140 - (NSString *) package {
1141 return (id) package_ ?: [NSNull null];
1144 - (void) setPackage:(NSString *)package {
1148 - (NSString *) url {
1149 return (id) url_ ?: [NSNull null];
1152 - (void) setURL:(NSString *)url {
1156 - (void) setVersion:(NSString *)version {
1160 - (NSString *) version {
1161 return (id) version_ ?: [NSNull null];
1164 - (NSString *) compound:(NSString *)value {
1166 NSString *mode(nil); {
1167 NSString *type([self type]);
1168 if ([type isEqualToString:kCydiaProgressEventTypeError])
1169 mode = UCLocalize("ERROR");
1170 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1171 mode = UCLocalize("WARNING");
1175 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1181 - (NSString *) compoundMessage {
1182 return [self compound:[self message]];
1185 - (NSString *) compoundTitle {
1188 if (package_ == nil)
1190 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1191 title = [package name];
1195 return [self compound:title];
1201 // Cytore Definitions {{{
1202 struct PackageValue :
1205 Cytore::Offset<PackageValue> next_;
1207 uint32_t index_ : 23;
1208 uint32_t subscribed_ : 1;
1225 Cytore::Offset<PackageValue> packages_[1 << 16];
1228 static Cytore::File<MetaValue> MetaFile_;
1230 // Cytore Helper Functions {{{
1231 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1232 SplitHash nhash = { hashlittle(name, length) };
1234 PackageValue *metadata;
1236 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1237 offset: if (offset->IsNull()) {
1238 *offset = MetaFile_.New<PackageValue>(length + 1);
1239 metadata = &MetaFile_.Get(*offset);
1241 if (metadata == NULL) {
1245 metadata = new PackageValue();
1246 memset(metadata, 0, sizeof(*metadata));
1249 memcpy(metadata->name_, name, length + 1);
1250 metadata->nhash_ = nhash.u16[1];
1252 metadata = &MetaFile_.Get(*offset);
1254 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1255 offset = &metadata->next_;
1263 static void PackageImport(const void *key, const void *value, void *context) {
1264 bool &fail(*reinterpret_cast<bool *>(context));
1267 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1268 NSLog(@"failed to import package %@", key);
1272 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1273 NSDictionary *package((NSDictionary *) value);
1275 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1276 if ([subscribed boolValue] && !metadata->subscribed_)
1277 metadata->subscribed_ = true;
1279 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1280 time_t time([date timeIntervalSince1970]);
1281 if (metadata->first_ > time || metadata->first_ == 0)
1282 metadata->first_ = time;
1285 NSDate *date([package objectForKey:@"LastSeen"]);
1286 NSString *version([package objectForKey:@"LastVersion"]);
1288 if (date != nil && version != nil) {
1289 time_t time([date timeIntervalSince1970]);
1290 if (metadata->last_ < time || metadata->last_ == 0)
1291 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1292 size_t length(strlen(buffer));
1293 uint16_t vhash(hashlittle(buffer, length));
1295 size_t capped(std::min<size_t>(8, length));
1296 char *latest(buffer + length - capped);
1298 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1299 metadata->vhash_ = vhash;
1301 metadata->last_ = time;
1307 /* Source Class {{{ */
1308 @interface Source : NSObject {
1309 CYString depiction_;
1310 CYString description_;
1316 CYString distribution_;
1322 _H<NSString> authority_;
1324 CYString defaultIcon_;
1326 _H<NSDictionary> record_;
1330 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1332 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1334 - (NSString *) depictionForPackage:(NSString *)package;
1335 - (NSString *) supportForPackage:(NSString *)package;
1337 - (NSDictionary *) record;
1341 - (NSString *) distribution;
1342 - (NSString *) type;
1344 - (NSString *) base;
1347 - (NSString *) host;
1349 - (NSString *) name;
1350 - (NSString *) shortDescription;
1351 - (NSString *) label;
1352 - (NSString *) origin;
1353 - (NSString *) version;
1355 - (NSString *) defaultIcon;
1359 @implementation Source
1363 distribution_.clear();
1368 description_.clear();
1374 defaultIcon_.clear();
1381 + (NSString *) webScriptNameForSelector:(SEL)selector {
1383 else if (selector == @selector(addSection:))
1384 return @"addSection";
1385 else if (selector == @selector(removeSection:))
1386 return @"removeSection";
1387 else if (selector == @selector(remove))
1393 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1394 return [self webScriptNameForSelector:selector] == nil;
1397 + (NSArray *) _attributeKeys {
1398 return [NSArray arrayWithObjects:
1406 @"shortDescription",
1414 - (NSArray *) attributeKeys {
1415 return [[self class] _attributeKeys];
1418 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1419 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1422 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1425 trusted_ = index->IsTrusted();
1427 uri_.set(pool, index->GetURI());
1428 distribution_.set(pool, index->GetDist());
1429 type_.set(pool, index->GetType());
1431 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1432 if (dindex != NULL) {
1433 base_.set(pool, dindex->MetaIndexURI(""));
1436 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1439 pkgTagFile tags(&fd);
1441 pkgTagSection section;
1448 {"default-icon", &defaultIcon_},
1449 {"depiction", &depiction_},
1450 {"description", &description_},
1452 {"origin", &origin_},
1453 {"support", &support_},
1454 {"version", &version_},
1457 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1458 const char *start, *end;
1460 if (section.Find(names[i].name_, start, end)) {
1461 CYString &value(*names[i].value_);
1462 value.set(pool, start, end - start);
1468 record_ = [Sources_ objectForKey:[self key]];
1470 NSURL *url([NSURL URLWithString:uri_]);
1474 host_ = [host_ lowercaseString];
1479 authority_ = [url path];
1482 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1483 if ((self = [super init]) != nil) {
1484 [self setMetaIndex:index inPool:pool];
1488 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1489 NSDictionary *lhr = [self record];
1490 NSDictionary *rhr = [source record];
1492 if ((lhr == nil) != (rhr == nil))
1493 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1495 NSString *lhs = [self name];
1496 NSString *rhs = [source name];
1498 if ([lhs length] != 0 && [rhs length] != 0) {
1499 unichar lhc = [lhs characterAtIndex:0];
1500 unichar rhc = [rhs characterAtIndex:0];
1502 if (isalpha(lhc) && !isalpha(rhc))
1503 return NSOrderedAscending;
1504 else if (!isalpha(lhc) && isalpha(rhc))
1505 return NSOrderedDescending;
1508 return [lhs compare:rhs options:LaxCompareOptions_];
1511 - (NSString *) depictionForPackage:(NSString *)package {
1512 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1515 - (NSString *) supportForPackage:(NSString *)package {
1516 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1519 - (NSArray *) sections {
1520 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1523 - (void) _addSection:(NSString *)section {
1526 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1527 if (![sections containsObject:section]) {
1528 [sections addObject:section];
1532 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1537 - (bool) addSection:(NSString *)section {
1541 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1545 - (void) _removeSection:(NSString *)section {
1549 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1550 if ([sections containsObject:section]) {
1551 [sections removeObject:section];
1556 - (bool) removeSection:(NSString *)section {
1560 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1565 [Sources_ removeObjectForKey:[self key]];
1570 bool value(record_ != nil);
1571 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1575 - (NSDictionary *) record {
1583 - (NSString *) uri {
1587 - (NSString *) distribution {
1588 return distribution_;
1591 - (NSString *) type {
1595 - (NSString *) base {
1599 - (NSString *) key {
1600 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1603 - (NSString *) host {
1607 - (NSString *) name {
1608 return origin_.empty() ? (id) authority_ : origin_;
1611 - (NSString *) shortDescription {
1612 return description_;
1615 - (NSString *) label {
1616 return label_.empty() ? (id) authority_ : label_;
1619 - (NSString *) origin {
1623 - (NSString *) version {
1627 - (NSString *) defaultIcon {
1628 return defaultIcon_;
1633 /* CydiaOperation Class {{{ */
1634 @interface CydiaOperation : NSObject {
1635 _H<NSString> operator_;
1636 _H<NSString> value_;
1639 - (NSString *) operator;
1640 - (NSString *) value;
1644 @implementation CydiaOperation
1646 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1647 if ((self = [super init]) != nil) {
1648 operator_ = [NSString stringWithUTF8String:_operator];
1649 value_ = [NSString stringWithUTF8String:value];
1653 + (NSArray *) _attributeKeys {
1654 return [NSArray arrayWithObjects:
1660 - (NSArray *) attributeKeys {
1661 return [[self class] _attributeKeys];
1664 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1665 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1668 - (NSString *) operator {
1672 - (NSString *) value {
1678 /* CydiaClause Class {{{ */
1679 @interface CydiaClause : NSObject {
1680 _H<NSString> package_;
1681 _H<CydiaOperation> version_;
1684 - (NSString *) package;
1685 - (CydiaOperation *) version;
1689 @implementation CydiaClause
1691 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1692 if ((self = [super init]) != nil) {
1693 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1695 if (const char *version = dep.TargetVer())
1696 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1698 version_ = (id) [NSNull null];
1702 + (NSArray *) _attributeKeys {
1703 return [NSArray arrayWithObjects:
1709 - (NSArray *) attributeKeys {
1710 return [[self class] _attributeKeys];
1713 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1714 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1717 - (NSString *) package {
1721 - (CydiaOperation *) version {
1727 /* CydiaRelation Class {{{ */
1728 @interface CydiaRelation : NSObject {
1729 _H<NSString> relationship_;
1730 _H<NSMutableArray> clauses_;
1733 - (NSString *) relationship;
1734 - (NSArray *) clauses;
1738 @implementation CydiaRelation
1740 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1741 if ((self = [super init]) != nil) {
1742 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1743 clauses_ = [NSMutableArray arrayWithCapacity:8];
1745 pkgCache::DepIterator start;
1746 pkgCache::DepIterator end;
1747 dep.GlobOr(start, end); // ++dep
1750 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1752 // yes, seriously. (wtf?)
1760 + (NSArray *) _attributeKeys {
1761 return [NSArray arrayWithObjects:
1767 - (NSArray *) attributeKeys {
1768 return [[self class] _attributeKeys];
1771 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1772 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1775 - (NSString *) relationship {
1776 return relationship_;
1779 - (NSArray *) clauses {
1783 - (void) addClause:(CydiaClause *)clause {
1784 [clauses_ addObject:clause];
1789 /* Package Class {{{ */
1790 struct ParsedPackage {
1793 CYString architecture_;
1796 CYString depiction_;
1806 @interface Package : NSObject {
1809 uint32_t essential_ : 1;
1810 uint32_t obsolete_ : 1;
1811 uint32_t ignored_ : 1;
1817 _transient Database *database_;
1819 pkgCache::VerIterator version_;
1820 pkgCache::PkgIterator iterator_;
1821 pkgCache::VerFileIterator file_;
1827 CYString installed_;
1829 const char *section_;
1830 _transient NSString *section$_;
1834 PackageValue *metadata_;
1835 ParsedPackage *parsed_;
1837 _H<NSMutableArray> tags_;
1840 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1841 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1843 - (pkgCache::PkgIterator) iterator;
1846 - (NSString *) section;
1847 - (NSString *) simpleSection;
1849 - (NSString *) longSection;
1850 - (NSString *) shortSection;
1854 - (MIMEAddress *) maintainer;
1856 - (NSString *) longDescription;
1857 - (NSString *) shortDescription;
1860 - (PackageValue *) metadata;
1863 - (bool) subscribed;
1864 - (bool) setSubscribed:(bool)subscribed;
1868 - (NSString *) latest;
1869 - (NSString *) installed;
1870 - (BOOL) uninstalled;
1873 - (BOOL) upgradableAndEssential:(BOOL)essential;
1876 - (BOOL) unfiltered;
1880 - (BOOL) halfConfigured;
1881 - (BOOL) halfInstalled;
1883 - (NSString *) mode;
1886 - (NSString *) name;
1888 - (NSString *) homepage;
1889 - (NSString *) depiction;
1890 - (MIMEAddress *) author;
1892 - (NSString *) support;
1894 - (NSArray *) files;
1895 - (NSArray *) warnings;
1896 - (NSArray *) applications;
1898 - (Source *) source;
1901 - (BOOL) matches:(NSArray *)query;
1903 - (bool) hasSupportingRole;
1904 - (BOOL) hasTag:(NSString *)tag;
1905 - (NSString *) primaryPurpose;
1906 - (NSArray *) purposes;
1907 - (bool) isCommercial;
1909 - (void) setIndex:(size_t)index;
1911 - (CYString &) cyname;
1913 - (uint32_t) compareBySection:(NSArray *)sections;
1918 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1919 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1920 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1921 - (bool) isVisibleInSection:(NSString *)section;
1922 - (bool) isVisibleInSource:(Source *)source;
1926 uint32_t PackageChangesRadix(Package *self, void *) {
1931 uint32_t timestamp : 30;
1932 uint32_t ignored : 1;
1933 uint32_t upgradable : 1;
1937 bool upgradable([self upgradableAndEssential:YES]);
1938 value.bits.upgradable = upgradable ? 1 : 0;
1941 value.bits.timestamp = 0;
1942 value.bits.ignored = [self ignored] ? 0 : 1;
1943 value.bits.upgradable = 1;
1945 value.bits.timestamp = [self seen] >> 2;
1946 value.bits.ignored = 0;
1947 value.bits.upgradable = 0;
1950 return _not(uint32_t) - value.key;
1953 uint32_t PackagePrefixRadix(Package *self, void *context) {
1954 size_t offset(reinterpret_cast<size_t>(context));
1955 CYString &name([self cyname]);
1957 size_t size(name.size());
1960 char *text(name.data());
1963 if (!isdigit(text[0]))
1967 while (size != digits && isdigit(text[digits]))
1975 if (offset == 0 && zeros != 0) {
1976 memset(data, '0', zeros);
1977 memcpy(data + zeros, text, 4 - zeros);
1979 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1980 if (size <= offset - zeros)
1983 text += offset - zeros;
1984 size -= offset - zeros;
1987 memcpy(data, text, 4);
1989 memcpy(data, text, size);
1990 memset(data + size, 0, 4 - size);
1993 for (size_t i(0); i != 4; ++i)
1994 if (isalpha(data[i]))
2002 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2004 /* XXX: ntohl may be more honest */
2005 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2008 CYString &(*PackageName)(Package *self, SEL sel);
2010 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2011 _profile(PackageNameCompare)
2012 CYString &lhi(PackageName(lhs, @selector(cyname)));
2013 CYString &rhi(PackageName(rhs, @selector(cyname)));
2014 CFStringRef lhn(lhi), rhn(rhi);
2017 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2018 else if (rhn == NULL)
2019 return NSOrderedDescending;
2021 _profile(PackageNameCompare$NumbersLast)
2022 if (!lhi.empty() && !rhi.empty()) {
2023 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2024 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2025 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2026 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2027 return lha ? NSOrderedAscending : NSOrderedDescending;
2031 CFIndex length = CFStringGetLength(lhn);
2033 _profile(PackageNameCompare$Compare)
2034 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2039 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2040 return PackageNameCompare(*lhs, *rhs, context);
2043 struct PackageNameOrdering :
2044 std::binary_function<Package *, Package *, bool>
2046 _finline bool operator ()(Package *lhs, Package *rhs) const {
2047 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2051 @implementation Package
2053 - (NSString *) description {
2054 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2058 if (parsed_ != NULL)
2063 + (NSString *) webScriptNameForSelector:(SEL)selector {
2065 else if (selector == @selector(clear))
2067 else if (selector == @selector(getField:))
2069 else if (selector == @selector(hasTag:))
2071 else if (selector == @selector(install))
2073 else if (selector == @selector(remove))
2079 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2080 return [self webScriptNameForSelector:selector] == nil;
2083 + (NSArray *) _attributeKeys {
2084 return [NSArray arrayWithObjects:
2104 @"shortDescription",
2117 - (NSArray *) attributeKeys {
2118 return [[self class] _attributeKeys];
2121 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2122 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2125 - (NSArray *) relations {
2126 @synchronized (database_) {
2127 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2128 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2129 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2133 - (NSString *) architecture {
2135 @synchronized (database_) {
2136 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2139 - (NSString *) getField:(NSString *)name {
2140 @synchronized (database_) {
2141 if ([database_ era] != era_ || file_.end())
2144 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2146 const char *start, *end;
2147 if (!parser.Find([name UTF8String], start, end))
2148 return (NSString *) [NSNull null];
2150 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2154 if (parsed_ != NULL)
2156 @synchronized (database_) {
2157 if ([database_ era] != era_ || file_.end())
2160 ParsedPackage *parsed(new ParsedPackage);
2163 _profile(Package$parse)
2164 pkgRecords::Parser *parser;
2166 _profile(Package$parse$Lookup)
2167 parser = &[database_ records]->Lookup(file_);
2172 _profile(Package$parse$Find)
2177 {"architecture", &parsed->architecture_},
2178 {"icon", &parsed->icon_},
2179 {"depiction", &parsed->depiction_},
2180 {"homepage", &parsed->homepage_},
2181 {"website", &website},
2182 {"bugs", &parsed->bugs_},
2183 {"support", &parsed->support_},
2184 {"sponsor", &parsed->sponsor_},
2185 {"author", &parsed->author_},
2188 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2189 const char *start, *end;
2191 if (parser->Find(names[i].name_, start, end)) {
2192 CYString &value(*names[i].value_);
2193 _profile(Package$parse$Value)
2194 value.set(pool_, start, end - start);
2200 _profile(Package$parse$Tagline)
2201 const char *start, *end;
2202 if (parser->ShortDesc(start, end)) {
2203 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2206 while (stop != start && stop[-1] == '\r')
2208 parsed->tagline_.set(pool_, start, stop - start);
2212 _profile(Package$parse$Retain)
2213 if (parsed->homepage_.empty())
2214 parsed->homepage_ = website;
2215 if (parsed->homepage_ == parsed->depiction_)
2216 parsed->homepage_.clear();
2221 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2222 if ((self = [super init]) != nil) {
2223 _profile(Package$initWithVersion)
2226 database_ = database;
2227 era_ = [database era];
2231 pkgCache::PkgIterator iterator(version.ParentPkg());
2232 iterator_ = iterator;
2234 _profile(Package$initWithVersion$Version)
2235 if (!version_.end())
2236 file_ = version_.FileList();
2238 pkgCache &cache([database_ cache]);
2239 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2243 _profile(Package$initWithVersion$Cache)
2244 name_.set(NULL, iterator.Display());
2246 latest_.set(NULL, StripVersion_(version_.VerStr()));
2248 pkgCache::VerIterator current(iterator.CurrentVer());
2250 installed_.set(NULL, StripVersion_(current.VerStr()));
2253 _profile(Package$initWithVersion$Tags)
2254 pkgCache::TagIterator tag(iterator.TagList());
2256 tags_ = [NSMutableArray arrayWithCapacity:8];
2258 const char *name(tag.Name());
2259 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2261 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2262 if (strcmp(name + 6, "enduser") == 0)
2264 else if (strcmp(name + 6, "hacker") == 0)
2266 else if (strcmp(name + 6, "developer") == 0)
2268 else if (strcmp(name + 6, "cydia") == 0)
2274 if (strncmp(name, "cydia::", 7) == 0) {
2275 if (strcmp(name + 7, "essential") == 0)
2277 else if (strcmp(name + 7, "obsolete") == 0)
2282 } while (!tag.end());
2286 _profile(Package$initWithVersion$Metadata)
2287 const char *mixed(iterator.Name());
2288 size_t size(strlen(mixed));
2289 char lower[size + 1];
2291 for (size_t i(0); i != size; ++i)
2292 lower[i] = mixed[i] | 0x20;
2295 PackageValue *metadata(PackageFind(lower, size));
2296 metadata_ = metadata;
2298 id_.set(NULL, metadata->name_, size);
2300 const char *latest(version_.VerStr());
2301 size_t length(strlen(latest));
2303 uint16_t vhash(hashlittle(latest, length));
2305 size_t capped(std::min<size_t>(8, length));
2306 latest = latest + length - capped;
2308 if (metadata->first_ == 0)
2309 metadata->first_ = now_;
2311 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2312 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2313 metadata->vhash_ = vhash;
2314 metadata->last_ = now_;
2315 } else if (metadata->last_ == 0)
2316 metadata->last_ = metadata->first_;
2319 _profile(Package$initWithVersion$Section)
2320 section_ = iterator.Section();
2323 _profile(Package$initWithVersion$Flags)
2324 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2325 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2330 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2331 pkgCache::VerIterator version;
2333 _profile(Package$packageWithIterator$GetCandidateVer)
2334 version = [database policy]->GetCandidateVer(iterator);
2342 _profile(Package$packageWithIterator$Allocate)
2343 package = [Package allocWithZone:zone];
2346 _profile(Package$packageWithIterator$Initialize)
2348 initWithVersion:version
2355 _profile(Package$packageWithIterator$Autorelease)
2356 package = [package autorelease];
2362 - (pkgCache::PkgIterator) iterator {
2366 - (NSString *) section {
2367 if (section$_ == nil) {
2368 if (section_ == NULL)
2371 _profile(Package$section$mappedSectionForPointer)
2372 section$_ = [database_ mappedSectionForPointer:section_];
2377 - (NSString *) simpleSection {
2378 if (NSString *section = [self section])
2379 return Simplify(section);
2384 - (NSString *) longSection {
2385 return LocalizeSection([self section]);
2388 - (NSString *) shortSection {
2389 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2392 - (NSString *) uri {
2395 pkgIndexFile *index;
2396 pkgCache::PkgFileIterator file(file_.File());
2397 if (![database_ list].FindIndex(file, index))
2399 return [NSString stringWithUTF8String:iterator_->Path];
2400 //return [NSString stringWithUTF8String:file.Site()];
2401 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2405 - (MIMEAddress *) maintainer {
2406 @synchronized (database_) {
2407 if ([database_ era] != era_ || file_.end())
2410 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2411 const std::string &maintainer(parser->Maintainer());
2412 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2416 @synchronized (database_) {
2417 if ([database_ era] != era_ || version_.end())
2420 return version_->InstalledSize;
2423 - (NSString *) longDescription {
2424 @synchronized (database_) {
2425 if ([database_ era] != era_ || file_.end())
2428 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2429 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2431 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2432 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2433 if ([lines count] < 2)
2436 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2437 for (size_t i(1), e([lines count]); i != e; ++i) {
2438 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2439 [trimmed addObject:trim];
2442 return [trimmed componentsJoinedByString:@"\n"];
2445 - (NSString *) shortDescription {
2446 if (parsed_ != NULL)
2447 return static_cast<NSString *>(parsed_->tagline_);
2449 @synchronized (database_) {
2450 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2452 const char *start, *end;
2453 if (!parser.ShortDesc(start, end))
2456 if (end - start > 100)
2460 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2463 while (end != start && end[-1] == '\r')
2467 return [(id) CYStringCreate(start, end - start) autorelease];
2471 _profile(Package$index)
2472 CFStringRef name((CFStringRef) [self name]);
2473 if (CFStringGetLength(name) == 0)
2475 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2476 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2478 return toupper(character);
2482 - (PackageValue *) metadata {
2487 PackageValue *metadata([self metadata]);
2488 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2491 - (bool) subscribed {
2492 return [self metadata]->subscribed_;
2495 - (bool) setSubscribed:(bool)subscribed {
2496 PackageValue *metadata([self metadata]);
2497 if (metadata->subscribed_ == subscribed)
2499 metadata->subscribed_ = subscribed;
2507 - (NSString *) latest {
2511 - (NSString *) installed {
2515 - (BOOL) uninstalled {
2516 return installed_.empty();
2520 return !version_.end();
2523 - (BOOL) upgradableAndEssential:(BOOL)essential {
2524 _profile(Package$upgradableAndEssential)
2525 pkgCache::VerIterator current(iterator_.CurrentVer());
2527 return essential && essential_;
2529 return !version_.end() && version_ != current;
2533 - (BOOL) essential {
2538 return [database_ cache][iterator_].InstBroken();
2541 - (BOOL) unfiltered {
2542 _profile(Package$unfiltered$obsolete)
2543 if (_unlikely(obsolete_))
2547 _profile(Package$unfiltered$hasSupportingRole)
2548 if (_unlikely(![self hasSupportingRole]))
2556 if (![self unfiltered])
2561 _profile(Package$visible$section)
2562 section = [self section];
2565 _profile(Package$visible$isSectionVisible)
2566 if (!isSectionVisible(section))
2574 unsigned char current(iterator_->CurrentState);
2575 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2578 - (BOOL) halfConfigured {
2579 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2582 - (BOOL) halfInstalled {
2583 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2587 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2588 return state.Mode != pkgDepCache::ModeKeep;
2591 - (NSString *) mode {
2592 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2594 switch (state.Mode) {
2595 case pkgDepCache::ModeDelete:
2596 if ((state.iFlags & pkgDepCache::Purge) != 0)
2600 case pkgDepCache::ModeKeep:
2601 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2602 return @"REINSTALL";
2603 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2607 case pkgDepCache::ModeInstall:
2608 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2609 return @"REINSTALL";
2610 else*/ switch (state.Status) {
2612 return @"DOWNGRADE";
2618 return @"NEW_INSTALL";
2629 - (NSString *) name {
2630 return name_.empty() ? id_ : name_;
2633 - (UIImage *) icon {
2634 NSString *section = [self simpleSection];
2637 if (parsed_ != NULL)
2638 if (NSString *href = parsed_->icon_)
2639 if ([href hasPrefix:@"file:///"])
2640 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2641 if (icon == nil) if (section != nil)
2642 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2643 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2644 if ([dicon hasPrefix:@"file:///"])
2645 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2647 icon = [UIImage applicationImageNamed:@"unknown.png"];
2651 - (NSString *) homepage {
2652 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2655 - (NSString *) depiction {
2656 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2659 - (MIMEAddress *) sponsor {
2660 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2663 - (MIMEAddress *) author {
2664 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2667 - (NSString *) support {
2668 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2671 - (NSArray *) files {
2672 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2673 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2676 fin.open([path UTF8String]);
2681 while (std::getline(fin, line))
2682 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2687 - (NSString *) state {
2688 @synchronized (database_) {
2689 if ([database_ era] != era_ || file_.end())
2692 switch (iterator_->CurrentState) {
2693 case pkgCache::State::NotInstalled:
2694 return @"NotInstalled";
2695 case pkgCache::State::UnPacked:
2697 case pkgCache::State::HalfConfigured:
2698 return @"HalfConfigured";
2699 case pkgCache::State::HalfInstalled:
2700 return @"HalfInstalled";
2701 case pkgCache::State::ConfigFiles:
2702 return @"ConfigFiles";
2703 case pkgCache::State::Installed:
2704 return @"Installed";
2705 case pkgCache::State::TriggersAwaited:
2706 return @"TriggersAwaited";
2707 case pkgCache::State::TriggersPending:
2708 return @"TriggersPending";
2711 return (NSString *) [NSNull null];
2714 - (NSString *) selection {
2715 @synchronized (database_) {
2716 if ([database_ era] != era_ || file_.end())
2719 switch (iterator_->SelectedState) {
2720 case pkgCache::State::Unknown:
2722 case pkgCache::State::Install:
2724 case pkgCache::State::Hold:
2726 case pkgCache::State::DeInstall:
2727 return @"DeInstall";
2728 case pkgCache::State::Purge:
2732 return (NSString *) [NSNull null];
2735 - (NSArray *) warnings {
2736 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2737 const char *name(iterator_.Name());
2739 size_t length(strlen(name));
2740 if (length < 2) invalid:
2741 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2742 else for (size_t i(0); i != length; ++i)
2744 /* XXX: technically this is not allowed */
2745 (name[i] < 'A' || name[i] > 'Z') &&
2746 (name[i] < 'a' || name[i] > 'z') &&
2747 (name[i] < '0' || name[i] > '9') &&
2748 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2751 if (strcmp(name, "cydia") != 0) {
2754 bool _private = false;
2757 bool repository = [[self section] isEqualToString:@"Repositories"];
2759 if (NSArray *files = [self files])
2760 for (NSString *file in files)
2761 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2763 else if (!user && [file isEqualToString:@"/User"])
2765 else if (!_private && [file isEqualToString:@"/private"])
2767 else if (!stash && [file isEqualToString:@"/var/stash"])
2770 /* XXX: this is not sensitive enough. only some folders are valid. */
2771 if (cydia && !repository)
2772 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2774 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2776 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2778 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2781 return [warnings count] == 0 ? nil : warnings;
2784 - (NSArray *) applications {
2785 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2787 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2789 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2790 if (NSArray *files = [self files])
2791 for (NSString *file in files)
2792 if (application_r(file)) {
2793 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2794 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2795 if ([id isEqualToString:me])
2798 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2800 display = application_r[1];
2802 NSString *bundle([file stringByDeletingLastPathComponent]);
2803 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2804 if (icon == nil || [icon length] == 0)
2806 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2808 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2809 [applications addObject:application];
2811 [application addObject:id];
2812 [application addObject:display];
2813 [application addObject:url];
2816 return [applications count] == 0 ? nil : applications;
2819 - (Source *) source {
2820 if (source_ == nil) {
2821 @synchronized (database_) {
2822 if ([database_ era] != era_ || file_.end())
2823 source_ = (Source *) [NSNull null];
2825 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2829 return source_ == (Source *) [NSNull null] ? nil : source_;
2836 - (BOOL) matches:(NSArray *)query {
2837 if (query == nil || [query count] == 0)
2846 string = [self name];
2847 length = [string length];
2849 for (NSString *term in query) {
2850 range = [string rangeOfString:term options:MatchCompareOptions_];
2851 if (range.location != NSNotFound)
2852 rank_ -= 6 * 1000000 / length;
2857 length = [string length];
2859 for (NSString *term in query) {
2860 range = [string rangeOfString:term options:MatchCompareOptions_];
2861 if (range.location != NSNotFound)
2862 rank_ -= 6 * 1000000 / length;
2866 string = [self shortDescription];
2867 length = [string length];
2868 NSUInteger stop(std::min<NSUInteger>(length, 100));
2870 for (NSString *term in query) {
2871 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2872 if (range.location != NSNotFound)
2873 rank_ -= 2 * 100000;
2879 - (bool) hasSupportingRole {
2884 if ([Role_ isEqualToString:@"User"])
2888 if ([Role_ isEqualToString:@"Hacker"])
2892 if ([Role_ isEqualToString:@"Developer"])
2897 - (NSArray *) tags {
2901 - (BOOL) hasTag:(NSString *)tag {
2902 return tags_ == nil ? NO : [tags_ containsObject:tag];
2905 - (NSString *) primaryPurpose {
2906 for (NSString *tag in (NSArray *) tags_)
2907 if ([tag hasPrefix:@"purpose::"])
2908 return [tag substringFromIndex:9];
2912 - (NSArray *) purposes {
2913 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2914 for (NSString *tag in (NSArray *) tags_)
2915 if ([tag hasPrefix:@"purpose::"])
2916 [purposes addObject:[tag substringFromIndex:9]];
2917 return [purposes count] == 0 ? nil : purposes;
2920 - (bool) isCommercial {
2921 return [self hasTag:@"cydia::commercial"];
2924 - (void) setIndex:(size_t)index {
2925 if (metadata_->index_ != index)
2926 metadata_->index_ = index;
2929 - (CYString &) cyname {
2930 return name_.empty() ? id_ : name_;
2933 - (uint32_t) compareBySection:(NSArray *)sections {
2934 NSString *section([self section]);
2935 for (size_t i(0), e([sections count]); i != e; ++i) {
2936 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2940 return _not(uint32_t);
2944 @synchronized (database_) {
2945 pkgProblemResolver *resolver = [database_ resolver];
2946 resolver->Clear(iterator_);
2948 pkgCacheFile &cache([database_ cache]);
2949 cache->SetReInstall(iterator_, false);
2950 cache->MarkKeep(iterator_, false);
2954 @synchronized (database_) {
2955 pkgProblemResolver *resolver = [database_ resolver];
2956 resolver->Clear(iterator_);
2957 resolver->Protect(iterator_);
2959 pkgCacheFile &cache([database_ cache]);
2960 cache->SetReInstall(iterator_, false);
2961 cache->MarkInstall(iterator_, false);
2963 pkgDepCache::StateCache &state((*cache)[iterator_]);
2964 if (!state.Install())
2965 cache->SetReInstall(iterator_, true);
2969 @synchronized (database_) {
2970 pkgProblemResolver *resolver = [database_ resolver];
2971 resolver->Clear(iterator_);
2972 resolver->Remove(iterator_);
2973 resolver->Protect(iterator_);
2975 pkgCacheFile &cache([database_ cache]);
2976 cache->SetReInstall(iterator_, false);
2977 cache->MarkDelete(iterator_, true);
2980 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2981 _profile(Package$isUnfilteredAndSearchedForBy)
2984 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2985 value &= [self unfiltered];
2988 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2989 value &= [self matches:query];
2996 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2997 if ([search length] == 0)
3000 _profile(Package$isUnfilteredAndSelectedForBy)
3003 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3004 value &= [self unfiltered];
3007 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3008 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3015 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3016 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3019 - (bool) isVisibleInSection:(NSString *)name {
3020 NSString *section([self section]);
3024 section == nil && [name length] == 0 ||
3025 [name isEqualToString:section]
3026 ) && [self visible];
3029 - (bool) isVisibleInSource:(Source *)source {
3030 return [self source] == source && [self visible];
3035 /* Section Class {{{ */
3036 @interface Section : NSObject {
3041 _H<NSString> localized_;
3044 - (NSComparisonResult) compareByLocalized:(Section *)section;
3045 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3046 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3047 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3048 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3049 - (NSString *) name;
3056 - (void) addToCount;
3058 - (void) setCount:(size_t)count;
3059 - (NSString *) localized;
3063 @implementation Section
3065 - (NSComparisonResult) compareByLocalized:(Section *)section {
3066 NSString *lhs(localized_);
3067 NSString *rhs([section localized]);
3069 /*if ([lhs length] != 0 && [rhs length] != 0) {
3070 unichar lhc = [lhs characterAtIndex:0];
3071 unichar rhc = [rhs characterAtIndex:0];
3073 if (isalpha(lhc) && !isalpha(rhc))
3074 return NSOrderedAscending;
3075 else if (!isalpha(lhc) && isalpha(rhc))
3076 return NSOrderedDescending;
3079 return [lhs compare:rhs options:LaxCompareOptions_];
3082 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3083 if ((self = [self initWithName:name localize:NO]) != nil) {
3084 if (localized != nil)
3085 localized_ = localized;
3089 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3090 return [self initWithName:name row:0 localize:localize];
3093 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3094 if ((self = [super init]) != nil) {
3099 localized_ = LocalizeSection(name_);
3103 /* XXX: localize the index thingees */
3104 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3105 if ((self = [super init]) != nil) {
3106 name_ = [NSString stringWithCharacters:&index length:1];
3112 - (NSString *) name {
3132 - (void) addToCount {
3136 - (void) setCount:(size_t)count {
3140 - (NSString *) localized {
3147 static NSString *Colon_;
3149 static NSString *Error_;
3150 static NSString *Warning_;
3152 class CydiaLogCleaner :
3153 public pkgArchiveCleaner
3156 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3161 /* Database Implementation {{{ */
3162 @implementation Database
3164 + (Database *) sharedInstance {
3165 static _H<Database> instance;
3166 if (instance == nil)
3167 instance = [[[Database alloc] init] autorelease];
3175 - (void) releasePackages {
3176 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3177 CFArrayRemoveAllValues(packages_);
3181 // XXX: actually implement this thing
3183 [self releasePackages];
3184 apr_pool_destroy(pool_);
3185 NSRecycleZone(zone_);
3189 - (void) _readCydia:(NSNumber *)fd {
3190 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3191 std::istream is(&ib);
3194 static Pcre finish_r("^finish:([^:]*)$");
3196 while (std::getline(is, line)) {
3197 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3199 const char *data(line.c_str());
3200 size_t size = line.size();
3201 lprintf("C:%s\n", data);
3203 if (finish_r(data, size)) {
3204 NSString *finish = finish_r[1];
3205 int index = [Finishes_ indexOfObject:finish];
3206 if (index != INT_MAX && index > Finish_)
3216 - (void) _readStatus:(NSNumber *)fd {
3217 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3218 std::istream is(&ib);
3221 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3222 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3224 while (std::getline(is, line)) {
3225 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3227 const char *data(line.c_str());
3228 size_t size(line.size());
3229 lprintf("S:%s\n", data);
3231 if (conffile_r(data, size)) {
3232 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3233 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3234 } else if (strncmp(data, "status: ", 8) == 0) {
3235 // status: <package>: {unpacked,half-configured,installed}
3236 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3237 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3238 } else if (strncmp(data, "processing: ", 12) == 0) {
3239 // processing: configure: config-test
3240 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3241 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3242 } else if (pmstatus_r(data, size)) {
3243 std::string type([pmstatus_r[1] UTF8String]);
3245 NSString *package = pmstatus_r[2];
3246 if ([package isEqualToString:@"dpkg-exec"])
3249 float percent([pmstatus_r[3] floatValue]);
3250 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3252 NSString *string = pmstatus_r[4];
3254 if (type == "pmerror") {
3255 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3256 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3257 } else if (type == "pmstatus") {
3258 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3259 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3260 } else if (type == "pmconffile")
3261 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3263 lprintf("E:unknown pmstatus\n");
3265 lprintf("E:unknown status\n");
3273 - (void) _readOutput:(NSNumber *)fd {
3274 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3275 std::istream is(&ib);
3278 while (std::getline(is, line)) {
3279 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3281 lprintf("O:%s\n", line.c_str());
3283 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3284 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3296 - (Package *) packageWithName:(NSString *)name {
3299 @synchronized (self) {
3300 if (static_cast<pkgDepCache *>(cache_) == NULL)
3302 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3303 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3307 if ((self = [super init]) != nil) {
3314 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3315 apr_pool_create(&pool_, NULL);
3317 size_t capacity(MetaFile_->active_);
3323 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3324 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3328 _assert(pipe(fds) != -1);
3331 _config->Set("APT::Keep-Fds::", cydiafd_);
3332 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3335 detachNewThreadSelector:@selector(_readCydia:)
3337 withObject:[NSNumber numberWithInt:fds[0]]
3340 _assert(pipe(fds) != -1);
3344 detachNewThreadSelector:@selector(_readStatus:)
3346 withObject:[NSNumber numberWithInt:fds[0]]
3349 _assert(pipe(fds) != -1);
3350 _assert(dup2(fds[0], 0) != -1);
3351 _assert(close(fds[0]) != -1);
3353 input_ = fdopen(fds[1], "a");
3355 _assert(pipe(fds) != -1);
3356 _assert(dup2(fds[1], 1) != -1);
3357 _assert(close(fds[1]) != -1);
3360 detachNewThreadSelector:@selector(_readOutput:)
3362 withObject:[NSNumber numberWithInt:fds[0]]
3367 - (pkgCacheFile &) cache {
3371 - (pkgDepCache::Policy *) policy {
3375 - (pkgRecords *) records {
3379 - (pkgProblemResolver *) resolver {
3383 - (pkgAcquire &) fetcher {
3387 - (pkgSourceList &) list {
3391 - (NSArray *) packages {
3392 return (NSArray *) packages_;
3395 - (NSArray *) sources {
3399 - (Source *) sourceWithKey:(NSString *)key {
3400 for (Source *source in [self sources]) {
3401 if ([[source key] isEqualToString:key])
3406 - (bool) popErrorWithTitle:(NSString *)title {
3409 while (!_error->empty()) {
3411 bool warning(!_error->PopMessage(error));
3416 size_t size(error.size());
3417 if (size == 0 || error[size - 1] != '\n')
3419 error.resize(size - 1);
3422 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3424 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3430 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3431 return [self popErrorWithTitle:title] || !success;
3434 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3435 @synchronized (self) {
3438 [self releasePackages];
3441 [sourceList_ removeAllObjects];
3461 apr_pool_clear(pool_);
3463 NSRecycleZone(zone_);
3464 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3466 int chk(creat("/tmp/cydia.chk", 0644));
3470 if (invocation != nil)
3471 [invocation invoke];
3473 NSString *title(UCLocalize("DATABASE"));
3476 OpProgress progress;
3477 while (!cache_.Open(progress, true)) { pop:
3479 bool warning(!_error->PopMessage(error));
3480 lprintf("cache_.Open():[%s]\n", error.c_str());
3482 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3483 [delegate_ repairWithSelector:@selector(configure)];
3484 else if (error == "The package lists or status file could not be parsed or opened.")
3485 [delegate_ repairWithSelector:@selector(update)];
3486 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3487 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3488 // else if (error == "Malformed Status line")
3489 // else if (error == "The list of sources could not be read.")
3491 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3501 unlink("/tmp/cydia.chk");
3503 now_ = [[NSDate date] timeIntervalSince1970];
3505 policy_ = new pkgDepCache::Policy();
3506 records_ = new pkgRecords(cache_);
3507 resolver_ = new pkgProblemResolver(cache_);
3508 fetcher_ = new pkgAcquire(&status_);
3511 list_ = new pkgSourceList();
3512 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3515 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3516 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3520 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3523 if (cache_->BrokenCount() != 0) {
3524 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3527 if (cache_->BrokenCount() != 0) {
3528 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3532 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3536 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3537 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3538 [sourceList_ addObject:object];
3540 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3541 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3542 // XXX: this could be more intelligent
3543 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3544 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3546 sourceMap_[cached->ID] = object;
3551 /*std::vector<Package *> packages;
3552 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3557 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3558 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3559 //packages.push_back(package);
3560 CFArrayAppendValue(packages_, CFRetain(package));
3564 /*if (packages.empty())
3565 packages_ = [[NSArray alloc] init];
3567 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3570 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3571 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3572 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3580 /*if (!packages.empty())
3581 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3582 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3584 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3586 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3588 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3592 size_t count(CFArrayGetCount(packages_));
3593 MetaFile_->active_ = count;
3595 for (size_t index(0); index != count; ++index)
3596 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3603 @synchronized (self) {
3605 resolver_ = new pkgProblemResolver(cache_);
3607 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3608 if (!cache_[iterator].Keep())
3609 cache_->MarkKeep(iterator, false);
3610 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3611 cache_->SetReInstall(iterator, false);
3614 - (void) configure {
3615 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3617 system([dpkg UTF8String]);
3622 // XXX: I don't remember this condition
3627 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3629 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3631 if ([self popErrorWithTitle:title])
3635 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3637 CydiaLogCleaner cleaner;
3638 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3645 fetcher_->Shutdown();
3647 pkgRecords records(cache_);
3649 lock_ = new FileFd();
3650 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3652 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3654 if ([self popErrorWithTitle:title])
3658 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3661 manager_ = (_system->CreatePM(cache_));
3662 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3669 bool substrate(RestartSubstrate_);
3670 RestartSubstrate_ = false;
3672 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3674 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3676 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3678 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3679 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3682 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3684 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3686 [self popErrorWithTitle:title];
3690 bool failed = false;
3691 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3692 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3694 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3700 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3708 RestartSubstrate_ = true;
3711 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3713 if (_error->PendingError()) {
3718 if (result == pkgPackageManager::Failed) {
3723 if (result != pkgPackageManager::Completed) {
3728 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3730 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3732 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3733 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3736 if (![before isEqualToArray:after])
3741 NSString *title(UCLocalize("UPGRADE"));
3742 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3748 [self updateWithStatus:status_];
3751 - (void) updateWithStatus:(Status &)status {
3752 NSString *title(UCLocalize("REFRESHING_DATA"));
3755 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3759 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3760 if ([self popErrorWithTitle:title])
3763 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3765 bool success(ListUpdate(status, list, PulseInterval_));
3766 if (status.WasCancelled())
3769 [self popErrorWithTitle:title forOperation:success];
3770 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3774 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3777 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3778 delegate_ = delegate;
3781 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3782 progress_ = delegate;
3783 status_.setDelegate(delegate);
3786 - (NSObject<ProgressDelegate> *) progressDelegate {
3790 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3791 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3792 return i == sourceMap_.end() ? nil : i->second;
3795 - (NSString *) mappedSectionForPointer:(const char *)section {
3796 _H<NSString> *mapped;
3798 _profile(Database$mappedSectionForPointer$Cache)
3799 mapped = §ions_[section];
3802 if (*mapped == NULL) {
3803 size_t length(strlen(section));
3804 char spaced[length + 1];
3806 _profile(Database$mappedSectionForPointer$Replace)
3807 for (size_t index(0); index != length; ++index)
3808 spaced[index] = section[index] == '_' ? ' ' : section[index];
3809 spaced[length] = '\0';
3814 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3815 string = [NSString stringWithUTF8String:spaced];
3818 _profile(Database$mappedSectionForPointer$Map)
3819 string = [SectionMap_ objectForKey:string] ?: string;
3829 static _H<NSMutableSet> Diversions_;
3831 @interface Diversion : NSObject {
3834 _H<NSString> format_;
3839 @implementation Diversion
3841 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3842 if ((self = [super init]) != nil) {
3843 pattern_ = [from UTF8String];
3849 - (NSString *) divert:(NSString *)url {
3850 return !pattern_(url) ? nil : pattern_->*format_;
3853 + (NSURL *) divertURL:(NSURL *)url {
3855 NSString *href([url absoluteString]);
3857 for (Diversion *diversion in (id) Diversions_)
3858 if (NSString *diverted = [diversion divert:href]) {
3860 NSLog(@"div: %@", diverted);
3862 url = [NSURL URLWithString:diverted];
3869 - (NSString *) key {
3873 - (NSUInteger) hash {
3877 - (BOOL) isEqual:(Diversion *)object {
3878 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3883 @interface CydiaObject : NSObject {
3884 _H<IndirectDelegate> indirect_;
3885 _transient id delegate_;
3888 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3892 @interface CydiaWebViewController : CyteWebViewController {
3893 _H<CydiaObject> cydia_;
3896 + (void) addDiversion:(Diversion *)diversion;
3900 /* Web Scripting {{{ */
3901 @implementation CydiaObject
3903 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3904 if ((self = [super init]) != nil) {
3905 indirect_ = indirect;
3909 - (void) setDelegate:(id)delegate {
3910 delegate_ = delegate;
3913 + (NSArray *) _attributeKeys {
3914 return [NSArray arrayWithObjects:
3931 - (NSArray *) attributeKeys {
3932 return [[self class] _attributeKeys];
3935 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3936 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3939 - (NSString *) version {
3943 - (NSString *) device {
3944 return [[UIDevice currentDevice] uniqueIdentifier];
3947 - (NSString *) firmware {
3948 return [[UIDevice currentDevice] systemVersion];
3951 - (NSString *) hostname {
3952 return [[UIDevice currentDevice] name];
3955 - (NSString *) idiom {
3956 return (id) Idiom_ ?: [NSNull null];
3959 - (NSString *) plmn {
3960 return (id) PLMN_ ?: [NSNull null];
3963 - (NSString *) bbsnum {
3964 return (id) BBSNum_ ?: [NSNull null];
3967 - (NSString *) ecid {
3968 return (id) ChipID_ ?: [NSNull null];
3971 - (NSString *) serial {
3972 return SerialNumber_;
3975 - (NSString *) role {
3976 return (id) Role_ ?: [NSNull null];
3979 - (NSString *) model {
3980 return [NSString stringWithUTF8String:Machine_];
3983 - (NSString *) token {
3984 return (id) Token_ ?: [NSNull null];
3987 + (NSString *) webScriptNameForSelector:(SEL)selector {
3989 else if (selector == @selector(addBridgedHost:))
3990 return @"addBridgedHost";
3991 else if (selector == @selector(addInsecureHost:))
3992 return @"addInsecureHost";
3993 else if (selector == @selector(addInternalRedirect::))
3994 return @"addInternalRedirect";
3995 else if (selector == @selector(addPipelinedHost:scheme:))
3996 return @"addPipelinedHost";
3997 else if (selector == @selector(addSource:::))
3998 return @"addSource";
3999 else if (selector == @selector(addTokenHost:))
4000 return @"addTokenHost";
4001 else if (selector == @selector(addTrivialSource:))
4002 return @"addTrivialSource";
4003 else if (selector == @selector(close))
4005 else if (selector == @selector(du:))
4007 else if (selector == @selector(stringWithFormat:arguments:))
4009 else if (selector == @selector(getAllSources))
4010 return @"getAllSourcs";
4011 else if (selector == @selector(getKernelNumber:))
4012 return @"getKernelNumber";
4013 else if (selector == @selector(getKernelString:))
4014 return @"getKernelString";
4015 else if (selector == @selector(getInstalledPackages))
4016 return @"getInstalledPackages";
4017 else if (selector == @selector(getIORegistryEntry::))
4018 return @"getIORegistryEntry";
4019 else if (selector == @selector(getLocaleIdentifier))
4020 return @"getLocaleIdentifier";
4021 else if (selector == @selector(getPreferredLanguages))
4022 return @"getPreferredLanguages";
4023 else if (selector == @selector(getPackageById:))
4024 return @"getPackageById";
4025 else if (selector == @selector(getMetadataKeys))
4026 return @"getMetadataKeys";
4027 else if (selector == @selector(getMetadataValue:))
4028 return @"getMetadataValue";
4029 else if (selector == @selector(getSessionValue:))
4030 return @"getSessionValue";
4031 else if (selector == @selector(installPackages:))
4032 return @"installPackages";
4033 else if (selector == @selector(localizedStringForKey:value:table:))
4035 else if (selector == @selector(popViewController:))
4036 return @"popViewController";
4037 else if (selector == @selector(refreshSources))
4038 return @"refreshSources";
4039 else if (selector == @selector(removeButton))
4040 return @"removeButton";
4041 else if (selector == @selector(saveConfig))
4042 return @"saveConfig";
4043 else if (selector == @selector(setCydiaSource:))
4044 return @"setCydiaSource";
4045 else if (selector == @selector(setMetadataValue::))
4046 return @"setMetadataValue";
4047 else if (selector == @selector(setSessionValue::))
4048 return @"setSessionValue";
4049 else if (selector == @selector(substitutePackageNames:))
4050 return @"substitutePackageNames";
4051 else if (selector == @selector(scrollToBottom:))
4052 return @"scrollToBottom";
4053 else if (selector == @selector(setAllowsNavigationAction:))
4054 return @"setAllowsNavigationAction";
4055 else if (selector == @selector(setBadgeValue:))
4056 return @"setBadgeValue";
4057 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4058 return @"setButtonImage";
4059 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4060 return @"setButtonTitle";
4061 else if (selector == @selector(setHidesBackButton:))
4062 return @"setHidesBackButton";
4063 else if (selector == @selector(setHidesNavigationBar:))
4064 return @"setHidesNavigationBar";
4065 else if (selector == @selector(setNavigationBarStyle:))
4066 return @"setNavigationBarStyle";
4067 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4068 return @"setNavigationBarTintColor";
4069 else if (selector == @selector(setPasteboardString:))
4070 return @"setPasteboardString";
4071 else if (selector == @selector(setPasteboardURL:))
4072 return @"setPasteboardURL";
4073 else if (selector == @selector(setToken:))
4075 else if (selector == @selector(setViewportWidth:))
4076 return @"setViewportWidth";
4077 else if (selector == @selector(statfs:))
4079 else if (selector == @selector(supports:))
4081 else if (selector == @selector(unload))
4087 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4088 return [self webScriptNameForSelector:selector] == nil;
4091 - (BOOL) supports:(NSString *)feature {
4092 return [feature isEqualToString:@"window.open"];
4096 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4099 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4100 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4103 - (NSNumber *) getKernelNumber:(NSString *)name {
4104 const char *string([name UTF8String]);
4107 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4108 return (id) [NSNull null];
4110 if (size != sizeof(int))
4111 return (id) [NSNull null];
4114 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4115 return (id) [NSNull null];
4117 return [NSNumber numberWithInt:value];
4120 - (NSString *) getKernelString:(NSString *)name {
4121 const char *string([name UTF8String]);
4124 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4125 return (id) [NSNull null];
4127 char value[size + 1];
4128 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4129 return (id) [NSNull null];
4131 // XXX: just in case you request something ludicrous
4134 return [NSString stringWithCString:value];
4137 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4138 NSObject *value(CYIOGetValue([path UTF8String], entry));
4141 if ([value isKindOfClass:[NSData class]])
4142 value = CYHex((NSData *) value);
4147 - (void) _setCydiaSource:(NSString *)source {
4148 @synchronized (HostConfig_) {
4149 CydiaSource_ = source;
4150 [Metadata_ setObject:source forKey:@"CydiaSource"];
4156 - (void) setCydiaSource:(NSString *)source {
4157 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4160 - (NSString *) cydiaSource {
4161 @synchronized (HostConfig_) {
4162 return (id) CydiaSource_ ?: [NSNull null];
4166 - (NSArray *) getMetadataKeys {
4167 @synchronized (Values_) {
4168 return [Values_ allKeys];
4171 - (id) getMetadataValue:(NSString *)key {
4172 @synchronized (Values_) {
4173 return [Values_ objectForKey:key];
4176 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4177 @synchronized (Values_) {
4178 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4179 [Values_ removeObjectForKey:key];
4181 [Values_ setObject:value forKey:key];
4183 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4186 - (id) getSessionValue:(NSString *)key {
4187 @synchronized (SessionData_) {
4188 return [SessionData_ objectForKey:key];
4191 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4192 @synchronized (SessionData_) {
4193 if (value == (id) [WebUndefined undefined])
4194 [SessionData_ removeObjectForKey:key];
4196 [SessionData_ setObject:value forKey:key];
4199 - (void) addBridgedHost:(NSString *)host {
4200 @synchronized (HostConfig_) {
4201 [BridgedHosts_ addObject:host];
4204 - (void) addInsecureHost:(NSString *)host {
4205 @synchronized (HostConfig_) {
4206 [InsecureHosts_ addObject:host];
4209 - (void) addTokenHost:(NSString *)host {
4210 @synchronized (HostConfig_) {
4211 [TokenHosts_ addObject:host];
4214 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4215 @synchronized (HostConfig_) {
4216 if (scheme != (id) [WebUndefined undefined])
4217 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4219 [PipelinedHosts_ addObject:host];
4222 - (void) popViewController:(NSNumber *)value {
4223 if (value == (id) [WebUndefined undefined])
4224 value = [NSNumber numberWithBool:YES];
4225 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4228 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4229 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4231 for (NSString *section in sections)
4232 [array addObject:section];
4234 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4237 distribution, @"Distribution",
4239 nil] waitUntilDone:NO];
4242 - (void) addTrivialSource:(NSString *)href {
4243 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4246 - (void) refreshSources {
4247 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4250 - (void) saveConfig {
4251 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4254 - (NSArray *) getAllSources {
4255 return [[Database sharedInstance] sources];
4258 - (NSArray *) getInstalledPackages {
4259 Database *database([Database sharedInstance]);
4260 @synchronized (database) {
4261 NSArray *packages([database packages]);
4262 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4263 for (Package *package in packages)
4264 if (![package uninstalled])
4265 [installed addObject:package];
4269 - (Package *) getPackageById:(NSString *)id {
4270 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4274 return (Package *) [NSNull null];
4277 - (NSString *) getLocaleIdentifier {
4278 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4281 - (NSArray *) getPreferredLanguages {
4285 - (NSArray *) statfs:(NSString *)path {
4288 if (path == nil || statfs([path UTF8String], &stat) == -1)
4291 return [NSArray arrayWithObjects:
4292 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4293 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4294 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4298 - (NSNumber *) du:(NSString *)path {
4299 NSNumber *value(nil);
4302 _assert(pipe(fds) != -1);
4304 pid_t pid(ExecFork());
4306 _assert(dup2(fds[1], 1) != -1);
4307 _assert(close(fds[0]) != -1);
4308 _assert(close(fds[1]) != -1);
4309 /* XXX: this should probably not use du */
4310 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4315 _assert(close(fds[1]) != -1);
4317 if (FILE *du = fdopen(fds[0], "r")) {
4319 while (fgets(line, sizeof(line), du) != NULL) {
4320 size_t length(strlen(line));
4321 while (length != 0 && line[length - 1] == '\n')
4322 line[--length] = '\0';
4323 if (char *tab = strchr(line, '\t')) {
4325 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4330 } else _assert(close(fds[0]));
4334 if (waitpid(pid, &status, 0) == -1)
4337 else _assert(false);
4343 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4346 - (void) installPackages:(NSArray *)packages {
4347 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4350 - (NSString *) substitutePackageNames:(NSString *)message {
4351 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4352 for (size_t i(0), e([words count]); i != e; ++i) {
4353 NSString *word([words objectAtIndex:i]);
4354 if (Package *package = [[Database sharedInstance] packageWithName:word])
4355 [words replaceObjectAtIndex:i withObject:[package name]];
4358 return [words componentsJoinedByString:@" "];
4361 - (void) removeButton {
4362 [indirect_ removeButton];
4365 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4366 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4369 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4370 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4373 - (void) setBadgeValue:(id)value {
4374 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4377 - (void) setAllowsNavigationAction:(NSString *)value {
4378 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4381 - (void) setHidesBackButton:(NSString *)value {
4382 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4385 - (void) setHidesNavigationBar:(NSString *)value {
4386 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4389 - (void) setNavigationBarStyle:(NSString *)value {
4390 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4393 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4394 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4395 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4396 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4399 - (void) setPasteboardString:(NSString *)value {
4400 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4403 - (void) setPasteboardURL:(NSString *)value {
4404 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4407 - (void) _setToken:(NSString *)token {
4411 [Metadata_ removeObjectForKey:@"Token"];
4413 [Metadata_ setObject:Token_ forKey:@"Token"];
4418 - (void) setToken:(NSString *)token {
4419 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4422 - (void) scrollToBottom:(NSNumber *)animated {
4423 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4426 - (void) setViewportWidth:(float)width {
4427 [indirect_ setViewportWidthOnMainThread:width];
4430 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4431 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4432 unsigned count([arguments count]);
4434 for (unsigned i(0); i != count; ++i)
4435 values[i] = [arguments objectAtIndex:i];
4436 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4439 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4440 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4442 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4444 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4450 @interface NSURL (CydiaSecure)
4453 @implementation NSURL (CydiaSecure)
4455 - (bool) isCydiaSecure {
4456 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4459 @synchronized (HostConfig_) {
4460 if ([InsecureHosts_ containsObject:[self host]])
4469 /* Cydia Browser Controller {{{ */
4470 @implementation CydiaWebViewController
4472 - (NSURL *) navigationURL {
4473 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4476 + (void) initialize {
4477 Diversions_ = [NSMutableSet setWithCapacity:0];
4480 + (void) addDiversion:(Diversion *)diversion {
4481 [Diversions_ addObject:diversion];
4484 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4485 [super webView:view didClearWindowObject:window forFrame:frame];
4487 WebDataSource *source([frame dataSource]);
4488 NSURLResponse *response([source response]);
4489 NSURL *url([response URL]);
4490 NSString *scheme([[url scheme] lowercaseString]);
4492 bool bridged(false);
4494 @synchronized (HostConfig_) {
4495 if ([scheme isEqualToString:@"file"])
4497 else if ([scheme isEqualToString:@"https"])
4498 if ([BridgedHosts_ containsObject:[url host]])
4503 [window setValue:cydia_ forKey:@"cydia"];
4506 - (void) _setupMail:(MFMailComposeViewController *)controller {
4507 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4509 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4510 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4513 - (NSURL *) URLWithURL:(NSURL *)url {
4514 return [Diversion divertURL:url];
4517 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4518 NSURL *url([request URL]);
4519 NSString *host([url host]);
4521 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4523 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4524 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4525 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4526 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4529 @synchronized (HostConfig_) {
4530 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4533 if ([url isCydiaSecure] && token) {
4534 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4535 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4541 - (void) setDelegate:(id)delegate {
4542 [super setDelegate:delegate];
4543 [cydia_ setDelegate:delegate];
4546 - (NSString *) applicationNameForUserAgent {
4547 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4550 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4552 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4553 if (Product_ != nil)
4554 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4560 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4561 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4569 @interface NSObject (CydiaScript)
4570 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4573 @implementation NSObject (CydiaScript)
4575 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4581 @implementation NSArray (CydiaScript)
4583 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4584 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4585 for (size_t i(0), e([self count]); i != e; ++i)
4586 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4592 @implementation NSDictionary (CydiaScript)
4594 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4595 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4597 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4604 /* Confirmation Controller {{{ */
4605 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4606 if (!iterator.end())
4607 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4608 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4610 pkgCache::PkgIterator package(dep.TargetPkg());
4613 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4620 @protocol ConfirmationControllerDelegate
4621 - (void) cancelAndClear:(bool)clear;
4622 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4626 @interface ConfirmationController : CydiaWebViewController {
4627 _transient Database *database_;
4629 _H<UIAlertView> essential_;
4631 _H<NSDictionary> changes_;
4632 _H<NSMutableArray> issues_;
4633 _H<NSDictionary> sizes_;
4638 - (id) initWithDatabase:(Database *)database;
4642 @implementation ConfirmationController
4646 RestartSubstrate_ = true;
4647 [delegate_ confirmWithNavigationController:[self navigationController]];
4650 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4651 NSString *context([alert context]);
4653 if ([context isEqualToString:@"remove"]) {
4654 if (button == [alert cancelButtonIndex])
4655 [self dismissModalViewControllerAnimated:YES];
4656 else if (button == [alert firstOtherButtonIndex]) {
4660 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4661 } else if ([context isEqualToString:@"unable"]) {
4662 [self dismissModalViewControllerAnimated:YES];
4663 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4665 [super alertView:alert clickedButtonAtIndex:button];
4669 - (void) _doContinue {
4670 [self dismissModalViewControllerAnimated:YES];
4671 [delegate_ cancelAndClear:NO];
4674 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4675 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4679 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4680 [super webView:view didClearWindowObject:window forFrame:frame];
4682 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4683 (id) changes_, @"changes",
4684 (id) issues_, @"issues",
4685 (id) sizes_, @"sizes",
4687 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4690 - (id) initWithDatabase:(Database *)database {
4691 if ((self = [super init]) != nil) {
4692 database_ = database;
4694 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4695 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4696 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4697 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4698 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4702 pkgCacheFile &cache([database_ cache]);
4703 NSArray *packages([database_ packages]);
4704 pkgDepCache::Policy *policy([database_ policy]);
4706 issues_ = [NSMutableArray arrayWithCapacity:4];
4708 for (Package *package in packages) {
4709 pkgCache::PkgIterator iterator([package iterator]);
4710 NSString *name([package id]);
4712 if ([package broken]) {
4713 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4715 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4717 reasons, @"reasons",
4720 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4724 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4725 pkgCache::DepIterator start;
4726 pkgCache::DepIterator end;
4727 dep.GlobOr(start, end); // ++dep
4729 if (!cache->IsImportantDep(end))
4731 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4734 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4736 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4737 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4738 clauses, @"clauses",
4742 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4744 pkgCache::PkgIterator target(start.TargetPkg());
4745 if (target->ProvidesList != 0)
4746 reason = @"missing";
4748 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4750 reason = @"installed";
4751 installed = [NSString stringWithUTF8String:ver.VerStr()];
4752 } else if (!cache[target].CandidateVerIter(cache).end())
4753 reason = @"uninstalled";
4754 else if (target->ProvidesList == 0)
4755 reason = @"uninstallable";
4757 reason = @"virtual";
4760 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4761 [NSString stringWithUTF8String:start.CompType()], @"operator",
4762 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4765 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4766 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4767 version, @"version",
4769 installed, @"installed",
4772 // yes, seriously. (wtf?)
4780 pkgDepCache::StateCache &state(cache[iterator]);
4782 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4784 if (state.NewInstall())
4785 [installs addObject:name];
4786 // XXX: else if (state.Install())
4787 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4788 [reinstalls addObject:name];
4789 // XXX: move before previous if
4790 else if (state.Upgrade())
4791 [upgrades addObject:name];
4792 else if (state.Downgrade())
4793 [downgrades addObject:name];
4794 else if (!state.Delete())
4795 // XXX: _assert(state.Keep());
4797 else if (special_r(name))
4798 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4799 [NSNull null], @"package",
4800 [NSArray arrayWithObjects:
4801 [NSDictionary dictionaryWithObjectsAndKeys:
4802 @"Conflicts", @"relationship",
4803 [NSArray arrayWithObjects:
4804 [NSDictionary dictionaryWithObjectsAndKeys:
4806 [NSNull null], @"version",
4807 @"installed", @"reason",
4814 if ([package essential])
4816 [removes addObject:name];
4819 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4820 substrate_ |= DepSubstrate(iterator.CurrentVer());
4825 else if (Advanced_) {
4826 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4828 essential_ = [[[UIAlertView alloc]
4829 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4830 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4832 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4834 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4838 [essential_ setContext:@"remove"];
4840 essential_ = [[[UIAlertView alloc]
4841 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4842 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4844 cancelButtonTitle:UCLocalize("OKAY")
4845 otherButtonTitles:nil
4848 [essential_ setContext:@"unable"];
4851 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4852 installs, @"installs",
4853 reinstalls, @"reinstalls",
4854 upgrades, @"upgrades",
4855 downgrades, @"downgrades",
4856 removes, @"removes",
4859 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4860 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4861 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4864 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4868 - (UIBarButtonItem *) leftButton {
4869 return [[[UIBarButtonItem alloc]
4870 initWithTitle:UCLocalize("CANCEL")
4871 style:UIBarButtonItemStylePlain
4873 action:@selector(cancelButtonClicked)
4878 - (void) applyRightButton {
4879 if ([issues_ count] == 0 && ![self isLoading])
4880 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4881 initWithTitle:UCLocalize("CONFIRM")
4882 style:UIBarButtonItemStyleDone
4884 action:@selector(confirmButtonClicked)
4887 [[self navigationItem] setRightBarButtonItem:nil];
4891 - (void) cancelButtonClicked {
4892 [self dismissModalViewControllerAnimated:YES];
4893 [delegate_ cancelAndClear:YES];
4897 - (void) confirmButtonClicked {
4898 if (essential_ != nil)
4908 /* Progress Data {{{ */
4909 @interface CydiaProgressData : NSObject {
4910 _transient id delegate_;
4919 _H<NSMutableArray> events_;
4920 _H<NSString> title_;
4922 _H<NSString> status_;
4923 _H<NSString> finish_;
4928 @implementation CydiaProgressData
4930 + (NSArray *) _attributeKeys {
4931 return [NSArray arrayWithObjects:
4943 - (NSArray *) attributeKeys {
4944 return [[self class] _attributeKeys];
4947 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4948 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4952 if ((self = [super init]) != nil) {
4953 events_ = [NSMutableArray arrayWithCapacity:32];
4957 - (void) setDelegate:(id)delegate {
4958 delegate_ = delegate;
4961 - (void) setPercent:(float)value {
4965 - (NSNumber *) percent {
4966 return [NSNumber numberWithFloat:percent_];
4969 - (void) setCurrent:(float)value {
4973 - (NSNumber *) current {
4974 return [NSNumber numberWithFloat:current_];
4977 - (void) setTotal:(float)value {
4981 - (NSNumber *) total {
4982 return [NSNumber numberWithFloat:total_];
4985 - (void) setSpeed:(float)value {
4989 - (NSNumber *) speed {
4990 return [NSNumber numberWithFloat:speed_];
4993 - (NSArray *) events {
4997 - (void) removeAllEvents {
4998 [events_ removeAllObjects];
5001 - (void) addEvent:(CydiaProgressEvent *)event {
5002 [events_ addObject:event];
5005 - (void) setTitle:(NSString *)text {
5009 - (NSString *) title {
5013 - (void) setFinish:(NSString *)text {
5017 - (NSString *) finish {
5018 return (id) finish_ ?: [NSNull null];
5021 - (void) setRunning:(bool)running {
5025 - (NSNumber *) running {
5026 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5031 /* Progress Controller {{{ */
5032 @interface ProgressController : CydiaWebViewController <
5035 _transient Database *database_;
5036 _H<CydiaProgressData, 1> progress_;
5040 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5042 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5044 - (void) setTitle:(NSString *)title;
5045 - (void) setCancellable:(bool)cancellable;
5049 @implementation ProgressController
5052 [database_ setProgressDelegate:nil];
5056 - (UIBarButtonItem *) leftButton {
5057 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5058 initWithTitle:UCLocalize("CANCEL")
5059 style:UIBarButtonItemStylePlain
5061 action:@selector(cancel)
5062 ] autorelease] : nil;
5065 - (void) updateCancel {
5066 [super applyLeftButton];
5069 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5070 if ((self = [super init]) != nil) {
5071 database_ = database;
5072 delegate_ = delegate;
5074 [database_ setProgressDelegate:self];
5076 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5077 [progress_ setDelegate:self];
5079 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5081 [scroller_ setBackgroundColor:[UIColor blackColor]];
5083 [[self navigationItem] setHidesBackButton:YES];
5085 [self updateCancel];
5089 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5090 [super webView:view didClearWindowObject:window forFrame:frame];
5091 [window setValue:progress_ forKey:@"cydiaProgress"];
5094 - (void) updateProgress {
5095 [self dispatchEvent:@"CydiaProgressUpdate"];
5098 - (void) viewWillAppear:(BOOL)animated {
5099 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5100 [super viewWillAppear:animated];
5104 UpdateExternalStatus(0);
5107 [delegate_ saveState];
5114 [delegate_ terminateWithSuccess];
5115 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5116 [delegate_ suspendWithAnimation:YES];
5118 [delegate_ suspend];*/
5130 system("/usr/bin/sbreload");
5136 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5137 SBReboot(SBSSpringBoardServerPort());
5139 reboot2(RB_AUTOBOOT);
5146 - (void) setTitle:(NSString *)title {
5147 [progress_ setTitle:title];
5148 [self updateProgress];
5151 - (UIBarButtonItem *) rightButton {
5152 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5153 initWithTitle:UCLocalize("CLOSE")
5154 style:UIBarButtonItemStylePlain
5156 action:@selector(close)
5160 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5161 UpdateExternalStatus(1);
5163 [progress_ setRunning:true];
5164 [self setTitle:title];
5165 // implicit updateProgress
5167 SHA1SumValue notifyconf; {
5169 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5172 MMap mmap(file, MMap::ReadOnly);
5174 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5175 notifyconf = sha1.Result();
5179 SHA1SumValue springlist; {
5181 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5184 MMap mmap(file, MMap::ReadOnly);
5186 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5187 springlist = sha1.Result();
5191 if (invocation != nil) {
5192 [invocation yieldToSelector:@selector(invoke)];
5193 [self setTitle:@"COMPLETE"];
5198 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5201 MMap mmap(file, MMap::ReadOnly);
5203 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5204 if (!(notifyconf == sha1.Result()))
5211 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5214 MMap mmap(file, MMap::ReadOnly);
5216 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5217 if (!(springlist == sha1.Result()))
5223 if (RestartSubstrate_)
5227 RestartSubstrate_ = false;
5230 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5231 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5232 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5233 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5234 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5238 system("su -c /usr/bin/uicache mobile");
5241 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5243 [progress_ setRunning:false];
5244 [self updateProgress];
5246 [self applyRightButton];
5249 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5250 [progress_ addEvent:event];
5251 [self updateProgress];
5254 - (bool) isProgressCancelled {
5255 return cancel_ == 2;
5260 [self updateCancel];
5263 - (void) setCancellable:(bool)cancellable {
5264 unsigned cancel(cancel_);
5268 else if (cancel_ == 0)
5271 if (cancel != cancel_)
5272 [self updateCancel];
5275 - (void) setProgressCancellable:(NSNumber *)cancellable {
5276 [self setCancellable:[cancellable boolValue]];
5279 - (void) setProgressPercent:(NSNumber *)percent {
5280 [progress_ setPercent:[percent floatValue]];
5281 [self updateProgress];
5284 - (void) setProgressStatus:(NSDictionary *)status {
5285 if (status == nil) {
5286 [progress_ setCurrent:0];
5287 [progress_ setTotal:0];
5288 [progress_ setSpeed:0];
5290 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5292 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5293 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5294 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5297 [self updateProgress];
5303 /* Package Cell {{{ */
5304 @interface PackageCell : CyteTableViewCell <
5305 CyteTableViewCellDelegate
5309 _H<NSString> description_;
5311 _H<NSString> source_;
5313 _H<UIImage> placard_;
5317 - (PackageCell *) init;
5318 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5320 - (void) drawContentRect:(CGRect)rect;
5324 @implementation PackageCell
5326 - (PackageCell *) init {
5327 CGRect frame(CGRectMake(0, 0, 320, 74));
5328 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5329 UIView *content([self contentView]);
5330 CGRect bounds([content bounds]);
5332 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5333 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5334 [content addSubview:content_];
5336 [content_ setDelegate:self];
5337 [content_ setOpaque:YES];
5341 - (NSString *) accessibilityLabel {
5342 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5345 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5346 summarized_ = summary;
5357 Source *source = [package source];
5359 icon_ = [package icon];
5361 if (NSString *name = [package name])
5362 name_ = [NSString stringWithString:name];
5364 NSString *description(nil);
5366 if (description == nil && IsWildcat_)
5367 description = [package longDescription];
5368 if (description == nil)
5369 description = [package shortDescription];
5371 if (description != nil)
5372 description_ = [NSString stringWithString:description];
5374 commercial_ = [package isCommercial];
5376 NSString *label = nil;
5377 bool trusted = false;
5379 if (source != nil) {
5380 label = [source label];
5381 trusted = [source trusted];
5382 } else if ([[package id] isEqualToString:@"firmware"])
5383 label = UCLocalize("APPLE");
5385 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5387 NSString *from(label);
5389 NSString *section = [package simpleSection];
5390 if (section != nil && ![section isEqualToString:label]) {
5391 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5392 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5395 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5397 if (NSString *purpose = [package primaryPurpose])
5398 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5403 if (NSString *mode = [package mode]) {
5404 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5405 color = RemovingColor_;
5406 //placard = @"removing";
5408 color = InstallingColor_;
5409 //placard = @"installing";
5412 // XXX: the removing/installing placards are not @2x
5415 color = [UIColor whiteColor];
5417 if ([package installed] != nil)
5418 placard = @"installed";
5423 [content_ setBackgroundColor:color];
5426 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5428 [self setNeedsDisplay];
5429 [content_ setNeedsDisplay];
5432 - (void) drawSummaryContentRect:(CGRect)rect {
5433 bool highlighted(highlighted_);
5434 float width([self bounds].size.width);
5438 rect.size = [(UIImage *) icon_ size];
5440 rect.size.width /= 4;
5441 rect.size.height /= 4;
5443 rect.origin.x = 14 - rect.size.width / 4;
5444 rect.origin.y = 14 - rect.size.height / 4;
5446 [icon_ drawInRect:rect];
5449 if (badge_ != nil) {
5451 rect.size = [(UIImage *) badge_ size];
5453 rect.size.width /= 4;
5454 rect.size.height /= 4;
5456 rect.origin.x = 20 - rect.size.width / 4;
5457 rect.origin.y = 20 - rect.size.height / 4;
5459 [badge_ drawInRect:rect];
5466 UISetColor(commercial_ ? Purple_ : Black_);
5467 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5469 if (placard_ != nil)
5470 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5473 - (void) drawNormalContentRect:(CGRect)rect {
5474 bool highlighted(highlighted_);
5475 float width([self bounds].size.width);
5479 rect.size = [(UIImage *) icon_ size];
5481 rect.size.width /= 2;
5482 rect.size.height /= 2;
5484 rect.origin.x = 25 - rect.size.width / 2;
5485 rect.origin.y = 25 - rect.size.height / 2;
5487 [icon_ drawInRect:rect];
5490 if (badge_ != nil) {
5492 rect.size = [(UIImage *) badge_ size];
5494 rect.size.width /= 2;
5495 rect.size.height /= 2;
5497 rect.origin.x = 36 - rect.size.width / 2;
5498 rect.origin.y = 36 - rect.size.height / 2;
5500 [badge_ drawInRect:rect];
5507 UISetColor(commercial_ ? Purple_ : Black_);
5508 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5509 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5512 UISetColor(commercial_ ? Purplish_ : Gray_);
5513 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5515 if (placard_ != nil)
5516 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5519 - (void) drawContentRect:(CGRect)rect {
5521 [self drawSummaryContentRect:rect];
5523 [self drawNormalContentRect:rect];
5528 /* Section Cell {{{ */
5529 @interface SectionCell : CyteTableViewCell <
5530 CyteTableViewCellDelegate
5532 _H<NSString> basic_;
5533 _H<NSString> section_;
5535 _H<NSString> count_;
5537 _H<UISwitch> switch_;
5541 - (void) setSection:(Section *)section editing:(BOOL)editing;
5545 @implementation SectionCell
5547 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5548 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5549 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5550 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5551 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5553 UIView *content([self contentView]);
5554 CGRect bounds([content bounds]);
5556 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5557 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5558 [content addSubview:content_];
5559 [content_ setBackgroundColor:[UIColor whiteColor]];
5561 [content_ setDelegate:self];
5565 - (void) onSwitch:(id)sender {
5566 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5567 if (metadata == nil) {
5568 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5569 [Sections_ setObject:metadata forKey:basic_];
5572 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5576 - (void) setSection:(Section *)section editing:(BOOL)editing {
5577 if (editing != editing_) {
5579 [switch_ removeFromSuperview];
5581 [self addSubview:switch_];
5590 if (section == nil) {
5591 name_ = UCLocalize("ALL_PACKAGES");
5594 basic_ = [section name];
5595 section_ = [section localized];
5597 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5598 count_ = [NSString stringWithFormat:@"%d", [section count]];
5601 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5604 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5605 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5607 [content_ setNeedsDisplay];
5610 - (void) setFrame:(CGRect)frame {
5611 [super setFrame:frame];
5613 CGRect rect([switch_ frame]);
5614 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5617 - (NSString *) accessibilityLabel {
5621 - (void) drawContentRect:(CGRect)rect {
5622 bool highlighted(highlighted_ && !editing_);
5624 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5629 float width(rect.size.width);
5635 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5637 CGSize size = [count_ sizeWithFont:Font14_];
5641 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5647 /* File Table {{{ */
5648 @interface FileTable : CyteViewController <
5649 UITableViewDataSource,
5652 _transient Database *database_;
5653 _H<Package> package_;
5655 _H<NSMutableArray> files_;
5656 _H<UITableView, 2> list_;
5659 - (id) initWithDatabase:(Database *)database;
5660 - (void) setPackage:(Package *)package;
5664 @implementation FileTable
5666 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5667 return files_ == nil ? 0 : [files_ count];
5670 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5674 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5675 static NSString *reuseIdentifier = @"Cell";
5677 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5679 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5680 [cell setFont:[UIFont systemFontOfSize:16]];
5682 [cell setText:[files_ objectAtIndex:indexPath.row]];
5683 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5688 - (NSURL *) navigationURL {
5689 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5693 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5695 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5696 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5697 [list_ setRowHeight:24.0f];
5698 [(UITableView *) list_ setDataSource:self];
5699 [list_ setDelegate:self];
5700 [[self view] addSubview:list_];
5703 - (void) viewDidLoad {
5704 [super viewDidLoad];
5706 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5709 - (void) releaseSubviews {
5712 [super releaseSubviews];
5715 - (id) initWithDatabase:(Database *)database {
5716 if ((self = [super init]) != nil) {
5717 database_ = database;
5719 files_ = [NSMutableArray arrayWithCapacity:32];
5723 - (void) setPackage:(Package *)package {
5727 [files_ removeAllObjects];
5729 if (package != nil) {
5731 name_ = [package id];
5733 if (NSArray *files = [package files])
5734 [files_ addObjectsFromArray:files];
5736 if ([files_ count] != 0) {
5737 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5738 [files_ removeObjectAtIndex:0];
5739 [files_ sortUsingSelector:@selector(compareByPath:)];
5741 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5742 [stack addObject:@"/"];
5744 for (int i(0), e([files_ count]); i != e; ++i) {
5745 NSString *file = [files_ objectAtIndex:i];
5746 while (![file hasPrefix:[stack lastObject]])
5747 [stack removeLastObject];
5748 NSString *directory = [stack lastObject];
5749 [stack addObject:[file stringByAppendingString:@"/"]];
5750 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5751 ([stack count] - 2) * 3, "",
5752 [file substringFromIndex:[directory length]]
5761 - (void) reloadData {
5764 [self setPackage:[database_ packageWithName:name_]];
5769 /* Package Controller {{{ */
5770 @interface CYPackageController : CydiaWebViewController <
5771 UIActionSheetDelegate
5773 _transient Database *database_;
5774 _H<Package> package_;
5777 _H<NSMutableArray> buttons_;
5778 _H<UIBarButtonItem> button_;
5781 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5785 @implementation CYPackageController
5787 - (NSURL *) navigationURL {
5788 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5791 /* XXX: this is not safe at all... localization of /fail/ */
5792 - (void) _clickButtonWithName:(NSString *)name {
5793 if ([name isEqualToString:UCLocalize("CLEAR")])
5794 [delegate_ clearPackage:package_];
5795 else if ([name isEqualToString:UCLocalize("INSTALL")])
5796 [delegate_ installPackage:package_];
5797 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5798 [delegate_ installPackage:package_];
5799 else if ([name isEqualToString:UCLocalize("REMOVE")])
5800 [delegate_ removePackage:package_];
5801 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5802 [delegate_ installPackage:package_];
5803 else _assert(false);
5806 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5807 NSString *context([sheet context]);
5809 if ([context isEqualToString:@"modify"]) {
5810 if (button != [sheet cancelButtonIndex]) {
5811 NSString *buttonName = [buttons_ objectAtIndex:button];
5812 [self _clickButtonWithName:buttonName];
5815 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5819 - (bool) _allowJavaScriptPanel {
5824 - (void) _customButtonClicked {
5825 int count([buttons_ count]);
5830 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5832 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5833 [buttons addObjectsFromArray:buttons_];
5835 UIActionSheet *sheet = [[[UIActionSheet alloc]
5838 cancelButtonTitle:nil
5839 destructiveButtonTitle:nil
5840 otherButtonTitles:nil
5843 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5845 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5846 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5848 [sheet setContext:@"modify"];
5850 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5854 // We don't want to allow non-commercial packages to do custom things to the install button,
5855 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5856 - (void) customButtonClicked {
5858 [super customButtonClicked];
5860 [self _customButtonClicked];
5863 - (void) reloadButtonClicked {
5864 // Don't reload a commerical package by tapping the loading button,
5865 // but if it's not an Install button, we should forward it on.
5866 if (![package_ uninstalled])
5867 [self _customButtonClicked];
5870 - (void) applyLoadingTitle {
5871 // Don't show "Loading" as the title. Ever.
5874 - (UIBarButtonItem *) rightButton {
5879 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5880 if ((self = [super init]) != nil) {
5881 database_ = database;
5882 buttons_ = [NSMutableArray arrayWithCapacity:4];
5883 name_ = [NSString stringWithString:name];
5884 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5888 - (void) reloadData {
5891 package_ = [database_ packageWithName:name_];
5893 [buttons_ removeAllObjects];
5895 if (package_ != nil) {
5896 [(Package *) package_ parse];
5898 commercial_ = [package_ isCommercial];
5900 if ([package_ mode] != nil)
5901 [buttons_ addObject:UCLocalize("CLEAR")];
5902 if ([package_ source] == nil);
5903 else if ([package_ upgradableAndEssential:NO])
5904 [buttons_ addObject:UCLocalize("UPGRADE")];
5905 else if ([package_ uninstalled])
5906 [buttons_ addObject:UCLocalize("INSTALL")];
5908 [buttons_ addObject:UCLocalize("REINSTALL")];
5909 if (![package_ uninstalled])
5910 [buttons_ addObject:UCLocalize("REMOVE")];
5914 switch ([buttons_ count]) {
5915 case 0: title = nil; break;
5916 case 1: title = [buttons_ objectAtIndex:0]; break;
5917 default: title = UCLocalize("MODIFY"); break;
5920 button_ = [[[UIBarButtonItem alloc]
5922 style:UIBarButtonItemStylePlain
5924 action:@selector(customButtonClicked)
5928 - (bool) isLoading {
5929 return commercial_ ? [super isLoading] : false;
5935 /* Package List Controller {{{ */
5936 @interface PackageListController : CyteViewController <
5937 UITableViewDataSource,
5940 _transient Database *database_;
5942 _H<NSArray> packages_;
5943 _H<NSMutableArray> sections_;
5944 _H<UITableView, 2> list_;
5945 _H<NSMutableArray> index_;
5946 _H<NSMutableDictionary> indices_;
5947 _H<NSString> title_;
5948 unsigned reloading_;
5951 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5952 - (void) setDelegate:(id)delegate;
5953 - (void) resetCursor;
5958 @implementation PackageListController
5960 - (bool) isSummarized {
5964 - (bool) showsSections {
5968 - (void) deselectWithAnimation:(BOOL)animated {
5969 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5972 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5973 CGRect base = [[self view] bounds];
5974 base.size.height -= bounds.size.height;
5975 base.origin = [list_ frame].origin;
5977 [UIView beginAnimations:nil context:NULL];
5978 [UIView setAnimationBeginsFromCurrentState:YES];
5979 [UIView setAnimationCurve:curve];
5980 [UIView setAnimationDuration:duration];
5981 [list_ setFrame:base];
5982 [UIView commitAnimations];
5985 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5986 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5989 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5990 [self resizeForKeyboardBounds:bounds duration:0];
5993 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5994 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5995 *curve = UIViewAnimationCurveEaseInOut;
5997 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5999 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6002 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6005 - (void) keyboardWillShow:(NSNotification *)notification {
6008 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6009 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6011 NSTimeInterval duration;
6012 UIViewAnimationCurve curve;
6013 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6015 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);
6016 UIViewController *base = self;
6017 while ([base parentViewController] != nil)
6018 base = [base parentViewController];
6019 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6020 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6022 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6023 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
6025 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6028 - (void) keyboardWillHide:(NSNotification *)notification {
6029 NSTimeInterval duration;
6030 UIViewAnimationCurve curve;
6031 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6033 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6036 - (void) viewWillAppear:(BOOL)animated {
6037 [super viewWillAppear:animated];
6039 [self resizeForKeyboardBounds:CGRectZero];
6040 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6041 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6044 - (void) viewWillDisappear:(BOOL)animated {
6045 [super viewWillDisappear:animated];
6047 [self resizeForKeyboardBounds:CGRectZero];
6048 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6049 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6052 - (void) viewDidAppear:(BOOL)animated {
6053 [super viewDidAppear:animated];
6054 [self deselectWithAnimation:animated];
6057 - (void) didSelectPackage:(Package *)package {
6058 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6059 [view setDelegate:delegate_];
6060 [[self navigationController] pushViewController:view animated:YES];
6063 #if TryIndexedCollation
6064 + (BOOL) hasIndexedCollation {
6065 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6069 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6070 NSInteger count([sections_ count]);
6071 return count == 0 ? 1 : count;
6074 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6075 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6077 return [[sections_ objectAtIndex:section] name];
6080 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6081 if ([sections_ count] == 0)
6083 return [[sections_ objectAtIndex:section] count];
6086 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6087 @synchronized (database_) {
6088 if ([database_ era] != era_)
6091 Section *section([sections_ objectAtIndex:[path section]]);
6092 NSInteger row([path row]);
6093 Package *package([packages_ objectAtIndex:([section row] + row)]);
6094 return [[package retain] autorelease];
6097 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6098 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6100 cell = [[[PackageCell alloc] init] autorelease];
6102 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6103 [cell setPackage:package asSummary:[self isSummarized]];
6107 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6108 Package *package([self packageAtIndexPath:path]);
6109 package = [database_ packageWithName:[package id]];
6110 [self didSelectPackage:package];
6113 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6114 if (![self showsSections])
6120 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6121 #if TryIndexedCollation
6122 if ([[self class] hasIndexedCollation]) {
6123 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6130 - (void) updateHeight {
6131 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6134 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6135 if ((self = [super init]) != nil) {
6136 database_ = database;
6137 title_ = [title copy];
6138 [[self navigationItem] setTitle:title_];
6140 #if TryIndexedCollation
6141 if ([[self class] hasIndexedCollation])
6142 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6145 index_ = [NSMutableArray arrayWithCapacity:32];
6147 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6149 packages_ = [NSArray array];
6150 sections_ = [NSMutableArray arrayWithCapacity:16];
6155 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6157 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6158 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6159 [[self view] addSubview:list_];
6161 // XXX: is 20 the most optimal number here?
6162 [list_ setSectionIndexMinimumDisplayRowCount:20];
6164 [(UITableView *) list_ setDataSource:self];
6165 [list_ setDelegate:self];
6167 [self updateHeight];
6170 - (void) releaseSubviews {
6173 [super releaseSubviews];
6176 - (void) setDelegate:(id)delegate {
6177 delegate_ = delegate;
6180 - (bool) shouldYield {
6184 - (bool) shouldBlock {
6188 - (NSMutableArray *) _reloadPackages {
6189 @synchronized (database_) {
6190 era_ = [database_ era];
6191 NSArray *packages([database_ packages]);
6193 return [NSMutableArray arrayWithArray:packages];
6196 - (void) _reloadData {
6197 if (reloading_ != 0) {
6204 if ([self shouldYield]) {
6208 if (![self shouldBlock])
6211 hud = [delegate_ addProgressHUD];
6212 [hud setText:UCLocalize("LOADING")];
6216 packages = [self yieldToSelector:@selector(_reloadPackages)];
6219 [delegate_ removeProgressHUD:hud];
6220 } while (reloading_ == 2);
6224 packages = [self _reloadPackages];
6227 packages_ = packages;
6229 [indices_ removeAllObjects];
6230 [sections_ removeAllObjects];
6232 Section *section = nil;
6234 #if TryIndexedCollation
6235 if ([[self class] hasIndexedCollation]) {
6236 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6237 NSArray *titles = [collation sectionIndexTitles];
6240 _profile(PackageTable$reloadData$Section)
6241 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6245 _profile(PackageTable$reloadData$Section$Package)
6246 package = [packages_ objectAtIndex:offset];
6247 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6250 while (secidx < index) {
6253 _profile(PackageTable$reloadData$Section$Allocate)
6254 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6257 _profile(PackageTable$reloadData$Section$Add)
6258 [sections_ addObject:section];
6262 [section addToCount];
6268 [index_ removeAllObjects];
6270 bool sectioned([self showsSections]);
6272 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6273 [sections_ addObject:section];
6276 _profile(PackageTable$reloadData$Section)
6277 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6281 _profile(PackageTable$reloadData$Section$Package)
6282 package = [packages_ objectAtIndex:offset];
6283 index = [package index];
6286 if (sectioned && (section == nil || [section index] != index)) {
6287 _profile(PackageTable$reloadData$Section$Allocate)
6288 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6291 [index_ addObject:[section name]];
6292 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6294 _profile(PackageTable$reloadData$Section$Add)
6295 [sections_ addObject:section];
6299 [section addToCount];
6304 [self updateHeight];
6306 _profile(PackageTable$reloadData$List)
6307 [(UITableView *) list_ setDataSource:self];
6312 - (void) reloadData {
6314 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6317 - (void) resetCursor {
6318 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6321 - (void) clearData {
6322 [self updateHeight];
6324 [list_ setDataSource:nil];
6332 /* Filtered Package List Controller {{{ */
6333 @interface FilteredPackageListController : PackageListController {
6336 _H<NSObject> object_;
6339 - (void) setObject:(id)object;
6340 - (void) setObject:(id)object forFilter:(SEL)filter;
6343 - (void) setFilter:(SEL)filter;
6345 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6349 @implementation FilteredPackageListController
6355 - (void) setFilter:(SEL)filter {
6356 @synchronized (self) {
6359 /* XXX: this is an unsafe optimization of doomy hell */
6360 Method method(class_getInstanceMethod([Package class], filter));
6361 _assert(method != NULL);
6362 imp_ = method_getImplementation(method);
6363 _assert(imp_ != NULL);
6366 - (void) setObject:(id)object {
6367 @synchronized (self) {
6371 - (void) setObject:(id)object forFilter:(SEL)filter {
6372 @synchronized (self) {
6373 [self setFilter:filter];
6374 [self setObject:object];
6377 - (NSMutableArray *) _reloadPackages {
6378 @synchronized (database_) {
6379 era_ = [database_ era];
6380 NSArray *packages([database_ packages]);
6382 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6386 _H<NSObject> object;
6388 @synchronized (self) {
6394 _profile(PackageTable$reloadData$Filter)
6395 for (Package *package in packages)
6396 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6397 [filtered addObject:package];
6403 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6404 if ((self = [super initWithDatabase:database title:title]) != nil) {
6405 [self setFilter:filter];
6406 [self setObject:object];
6413 /* Home Controller {{{ */
6414 @interface HomeController : CydiaWebViewController {
6419 @implementation HomeController
6422 if ((self = [super init]) != nil) {
6423 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6428 - (NSURL *) navigationURL {
6429 return [NSURL URLWithString:@"cydia://home"];
6432 - (void) aboutButtonClicked {
6433 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6435 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6436 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6437 [alert setCancelButtonIndex:0];
6440 @"Copyright \u00a9 2008-2011\n"
6443 "Jay Freeman (saurik)\n"
6444 "saurik@saurik.com\n"
6445 "http://www.saurik.com/"
6451 - (UIBarButtonItem *) leftButton {
6452 return [[[UIBarButtonItem alloc]
6453 initWithTitle:UCLocalize("ABOUT")
6454 style:UIBarButtonItemStylePlain
6456 action:@selector(aboutButtonClicked)
6462 /* Manage Controller {{{ */
6463 @interface ManageController : CydiaWebViewController {
6466 - (void) queueStatusDidChange;
6470 @implementation ManageController
6473 if ((self = [super init]) != nil) {
6474 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6478 - (NSURL *) navigationURL {
6479 return [NSURL URLWithString:@"cydia://manage"];
6482 - (UIBarButtonItem *) leftButton {
6483 return [[[UIBarButtonItem alloc]
6484 initWithTitle:UCLocalize("SETTINGS")
6485 style:UIBarButtonItemStylePlain
6487 action:@selector(settingsButtonClicked)
6491 - (void) settingsButtonClicked {
6492 [delegate_ showSettings];
6495 - (void) queueButtonClicked {
6499 - (UIBarButtonItem *) customButton {
6500 return Queuing_ ? [[[UIBarButtonItem alloc]
6501 initWithTitle:UCLocalize("QUEUE")
6502 style:UIBarButtonItemStyleDone
6504 action:@selector(queueButtonClicked)
6505 ] autorelease] : [super customButton];
6508 - (void) queueStatusDidChange {
6509 [self applyRightButton];
6512 - (bool) isLoading {
6513 return !Queuing_ && [super isLoading];
6519 /* Refresh Bar {{{ */
6520 @interface RefreshBar : UINavigationBar {
6521 _H<UIProgressIndicator> indicator_;
6522 _H<UITextLabel> prompt_;
6523 _H<UIProgressBar> progress_;
6524 _H<UINavigationButton> cancel_;
6529 @implementation RefreshBar
6531 - (void) positionViews {
6532 CGRect frame = [cancel_ frame];
6533 frame.size = [cancel_ sizeThatFits:frame.size];
6534 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6535 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6536 [cancel_ setFrame:frame];
6538 CGSize prgsize = {75, 100};
6540 [self frame].size.width - prgsize.width - 10,
6541 ([self frame].size.height - prgsize.height) / 2
6543 [progress_ setFrame:prgrect];
6545 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6546 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6547 CGRect indrect = {{indoffset, indoffset}, indsize};
6548 [indicator_ setFrame:indrect];
6550 CGSize prmsize = {215, indsize.height + 4};
6552 indoffset * 2 + indsize.width,
6553 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6555 [prompt_ setFrame:prmrect];
6558 - (void) setFrame:(CGRect)frame {
6559 [super setFrame:frame];
6560 [self positionViews];
6563 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6564 if ((self = [super initWithFrame:frame]) != nil) {
6565 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6567 [self setBarStyle:UIBarStyleBlack];
6569 UIBarStyle barstyle([self _barStyle:NO]);
6570 bool ugly(barstyle == UIBarStyleDefault);
6572 UIProgressIndicatorStyle style = ugly ?
6573 UIProgressIndicatorStyleMediumBrown :
6574 UIProgressIndicatorStyleMediumWhite;
6576 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6577 [(UIProgressIndicator *) indicator_ setStyle:style];
6578 [indicator_ startAnimation];
6579 [self addSubview:indicator_];
6581 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6582 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6583 [prompt_ setBackgroundColor:[UIColor clearColor]];
6584 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6585 [self addSubview:prompt_];
6587 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6588 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6589 [(UIProgressBar *) progress_ setStyle:0];
6590 [self addSubview:progress_];
6592 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6593 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6594 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6595 [cancel_ setBarStyle:barstyle];
6597 [self positionViews];
6601 - (void) setCancellable:(bool)cancellable {
6603 [self addSubview:cancel_];
6605 [cancel_ removeFromSuperview];
6609 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6610 [progress_ setProgress:0];
6614 [self setCancellable:NO];
6617 - (void) setPrompt:(NSString *)prompt {
6618 [prompt_ setText:prompt];
6621 - (void) setProgress:(float)progress {
6622 [progress_ setProgress:progress];
6628 /* Cydia Navigation Controller Interface {{{ */
6629 @interface UINavigationController (Cydia)
6631 - (NSArray *) navigationURLCollection;
6632 - (void) unloadData;
6637 /* Cydia Tab Bar Controller {{{ */
6638 @interface CYTabBarController : UITabBarController <
6639 UITabBarControllerDelegate,
6642 _transient Database *database_;
6643 _H<RefreshBar, 1> refreshbar_;
6647 // XXX: ok, "updatedelegate_"?...
6648 _transient NSObject<CydiaDelegate> *updatedelegate_;
6650 _H<UIViewController> remembered_;
6651 _transient UIViewController *transient_;
6654 - (NSArray *) navigationURLCollection;
6655 - (void) dropBar:(BOOL)animated;
6656 - (void) beginUpdate;
6657 - (void) raiseBar:(BOOL)animated;
6659 - (void) unloadData;
6663 @implementation CYTabBarController
6665 - (void) setUnselectedViewController:(UIViewController *)transient {
6666 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6667 if (transient != nil) {
6668 if (transient_ == nil)
6669 remembered_ = [controllers objectAtIndex:0];
6670 transient_ = transient;
6671 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6672 [controllers replaceObjectAtIndex:0 withObject:transient_];
6673 [self setSelectedIndex:0];
6674 [self setViewControllers:controllers];
6675 [self concealTabBarSelection];
6676 } else if (remembered_ != nil) {
6677 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6678 transient_ = transient;
6679 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6681 [self setViewControllers:controllers];
6682 [self revealTabBarSelection];
6686 - (UIViewController *) unselectedViewController {
6690 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6691 if ([self unselectedViewController])
6692 [self setUnselectedViewController:nil];
6695 - (NSArray *) navigationURLCollection {
6696 NSMutableArray *items([NSMutableArray array]);
6698 // XXX: Should this deal with transient view controllers?
6699 for (id navigation in [self viewControllers]) {
6700 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6702 [items addObject:stack];
6708 - (void) unloadData {
6711 for (UINavigationController *controller in [self viewControllers])
6712 [controller unloadData];
6714 if (UIViewController *selected = [self selectedViewController])
6715 [selected reloadData];
6717 if (UIViewController *unselected = [self unselectedViewController]) {
6718 [unselected unloadData];
6719 [unselected reloadData];
6724 [[NSNotificationCenter defaultCenter] removeObserver:self];
6729 - (id) initWithDatabase:(Database *)database {
6730 if ((self = [super init]) != nil) {
6731 database_ = database;
6732 [self setDelegate:self];
6734 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6735 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6737 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6741 - (void) setUpdate:(NSDate *)date {
6745 - (void) beginUpdate {
6746 [(RefreshBar *) refreshbar_ start];
6749 [updatedelegate_ retainNetworkActivityIndicator];
6753 detachNewThreadSelector:@selector(performUpdate)
6759 - (void) performUpdate {
6760 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6763 status.setDelegate(self);
6764 [database_ updateWithStatus:status];
6767 performSelectorOnMainThread:@selector(completeUpdate)
6775 - (void) stopUpdateWithSelector:(SEL)selector {
6777 [updatedelegate_ releaseNetworkActivityIndicator];
6779 [self raiseBar:YES];
6782 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6785 - (void) completeUpdate {
6788 [self stopUpdateWithSelector:@selector(reloadData)];
6791 - (void) cancelUpdate {
6792 [self stopUpdateWithSelector:@selector(updateData)];
6795 - (void) cancelPressed {
6796 [self cancelUpdate];
6803 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6804 [refreshbar_ setPrompt:[event compoundMessage]];
6807 - (bool) isProgressCancelled {
6811 - (void) setProgressCancellable:(NSNumber *)cancellable {
6812 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6815 - (void) setProgressPercent:(NSNumber *)percent {
6816 [refreshbar_ setProgress:[percent floatValue]];
6819 - (void) setProgressStatus:(NSDictionary *)status {
6821 [self setProgressPercent:[status objectForKey:@"Percent"]];
6824 - (void) setUpdateDelegate:(id)delegate {
6825 updatedelegate_ = delegate;
6828 - (UIView *) transitionView {
6829 if ([self respondsToSelector:@selector(_transitionView)])
6830 return [self _transitionView];
6832 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6835 - (void) dropBar:(BOOL)animated {
6840 UIView *transition([self transitionView]);
6841 [[self view] addSubview:refreshbar_];
6843 CGRect barframe([refreshbar_ frame]);
6845 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6846 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6848 barframe.origin.y = 0;
6850 [refreshbar_ setFrame:barframe];
6853 [UIView beginAnimations:nil context:NULL];
6855 CGRect viewframe = [transition frame];
6856 viewframe.origin.y += barframe.size.height;
6857 viewframe.size.height -= barframe.size.height;
6858 [transition setFrame:viewframe];
6861 [UIView commitAnimations];
6863 // Ensure bar has the proper width for our view, it might have changed
6864 barframe.size.width = viewframe.size.width;
6865 [refreshbar_ setFrame:barframe];
6868 - (void) raiseBar:(BOOL)animated {
6873 UIView *transition([self transitionView]);
6874 [refreshbar_ removeFromSuperview];
6876 CGRect barframe([refreshbar_ frame]);
6879 [UIView beginAnimations:nil context:NULL];
6881 CGRect viewframe = [transition frame];
6882 viewframe.origin.y -= barframe.size.height;
6883 viewframe.size.height += barframe.size.height;
6884 [transition setFrame:viewframe];
6887 [UIView commitAnimations];
6890 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6891 bool dropped(dropped_);
6896 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6902 - (void) statusBarFrameChanged:(NSNotification *)notification {
6912 /* Cydia Navigation Controller Implementation {{{ */
6913 @implementation UINavigationController (Cydia)
6915 - (NSArray *) navigationURLCollection {
6916 NSMutableArray *stack([NSMutableArray array]);
6918 for (CyteViewController *controller in [self viewControllers]) {
6919 NSString *url = [[controller navigationURL] absoluteString];
6921 [stack addObject:url];
6927 - (void) reloadData {
6930 UIViewController *visible([self visibleViewController]);
6932 [visible reloadData];
6934 // on the iPad, this view controller is ALSO visible. :(
6936 if (UIViewController *top = [self topViewController])
6941 - (void) unloadData {
6942 for (CyteViewController *page in [self viewControllers])
6951 /* Cydia:// Protocol {{{ */
6952 @interface CydiaURLProtocol : NSURLProtocol {
6957 @implementation CydiaURLProtocol
6959 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6960 NSURL *url([request URL]);
6964 NSString *scheme([[url scheme] lowercaseString]);
6965 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6967 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6973 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6977 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6978 id<NSURLProtocolClient> client([self client]);
6980 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6982 NSData *data(UIImagePNGRepresentation(icon));
6984 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6985 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6986 [client URLProtocol:self didLoadData:data];
6987 [client URLProtocolDidFinishLoading:self];
6991 - (void) startLoading {
6992 id<NSURLProtocolClient> client([self client]);
6993 NSURLRequest *request([self request]);
6995 NSURL *url([request URL]);
6996 NSString *href([url absoluteString]);
6997 NSString *scheme([[url scheme] lowercaseString]);
7001 if ([scheme isEqualToString:@"cydia"])
7002 path = [href substringFromIndex:8];
7003 else if ([scheme isEqualToString:@"about"])
7004 path = [href substringFromIndex:12];
7005 else _assert(false);
7007 NSRange slash([path rangeOfString:@"/"]);
7010 if (slash.location == NSNotFound) {
7014 command = [path substringToIndex:slash.location];
7015 path = [path substringFromIndex:(slash.location + 1)];
7018 Database *database([Database sharedInstance]);
7020 if ([command isEqualToString:@"package-icon"]) {
7023 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7024 Package *package([database packageWithName:path]);
7028 UIImage *icon([package icon]);
7029 [self _returnPNGWithImage:icon forRequest:request];
7030 } else if ([command isEqualToString:@"source-icon"]) {
7033 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7034 NSString *source(Simplify(path));
7035 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7037 icon = [UIImage applicationImageNamed:@"unknown.png"];
7038 [self _returnPNGWithImage:icon forRequest:request];
7039 } else if ([command isEqualToString:@"uikit-image"]) {
7042 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7043 UIImage *icon(_UIImageWithName(path));
7044 [self _returnPNGWithImage:icon forRequest:request];
7045 } else if ([command isEqualToString:@"section-icon"]) {
7048 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7049 NSString *section(Simplify(path));
7050 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7052 icon = [UIImage applicationImageNamed:@"unknown.png"];
7053 [self _returnPNGWithImage:icon forRequest:request];
7055 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7059 - (void) stopLoading {
7065 /* Section Controller {{{ */
7066 @interface SectionController : FilteredPackageListController {
7067 _H<NSString> section_;
7070 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7074 @implementation SectionController
7076 - (NSURL *) navigationURL {
7077 NSString *name = section_;
7081 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7084 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7087 title = UCLocalize("ALL_PACKAGES");
7088 else if (![name isEqual:@""])
7089 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7091 title = UCLocalize("NO_SECTION");
7093 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7100 /* Sections Controller {{{ */
7101 @interface SectionsController : CyteViewController <
7102 UITableViewDataSource,
7105 _transient Database *database_;
7106 _H<NSMutableArray> sections_;
7107 _H<NSMutableArray> filtered_;
7108 _H<UITableView, 2> list_;
7111 - (id) initWithDatabase:(Database *)database;
7112 - (void) editButtonClicked;
7116 @implementation SectionsController
7118 - (NSURL *) navigationURL {
7119 return [NSURL URLWithString:@"cydia://sections"];
7122 - (void) updateNavigationItem {
7123 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7124 if ([sections_ count] == 0) {
7125 [[self navigationItem] setRightBarButtonItem:nil];
7127 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7128 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7130 action:@selector(editButtonClicked)
7131 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7135 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7136 [super setEditing:editing animated:animated];
7141 [delegate_ updateData];
7143 [self updateNavigationItem];
7146 - (void) viewDidAppear:(BOOL)animated {
7147 [super viewDidAppear:animated];
7148 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7151 - (void) viewWillDisappear:(BOOL)animated {
7152 [super viewWillDisappear:animated];
7153 if ([self isEditing]) [self setEditing:NO];
7156 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7157 Section *section = nil;
7158 int index = [indexPath row];
7159 if (![self isEditing]) {
7162 section = [filtered_ objectAtIndex:index];
7164 section = [sections_ objectAtIndex:index];
7169 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7170 if ([self isEditing])
7171 return [sections_ count];
7173 return [filtered_ count] + 1;
7176 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7180 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7181 static NSString *reuseIdentifier = @"SectionCell";
7183 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7185 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7187 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7192 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7193 if ([self isEditing])
7196 Section *section = [self sectionAtIndexPath:indexPath];
7198 SectionController *controller = [[[SectionController alloc]
7199 initWithDatabase:database_
7200 section:[section name]
7202 [controller setDelegate:delegate_];
7204 [[self navigationController] pushViewController:controller animated:YES];
7208 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7210 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7211 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7212 [list_ setRowHeight:45.0f];
7213 [(UITableView *) list_ setDataSource:self];
7214 [list_ setDelegate:self];
7215 [[self view] addSubview:list_];
7218 - (void) viewDidLoad {
7219 [super viewDidLoad];
7221 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7224 - (void) releaseSubviews {
7227 [super releaseSubviews];
7230 - (id) initWithDatabase:(Database *)database {
7231 if ((self = [super init]) != nil) {
7232 database_ = database;
7234 sections_ = [NSMutableArray arrayWithCapacity:16];
7235 filtered_ = [NSMutableArray arrayWithCapacity:16];
7239 - (void) reloadData {
7242 NSArray *packages = [database_ packages];
7244 [sections_ removeAllObjects];
7245 [filtered_ removeAllObjects];
7247 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7250 for (Package *package in packages) {
7251 NSString *name([package section]);
7252 NSString *key(name == nil ? @"" : name);
7256 _profile(SectionsView$reloadData$Section)
7257 section = [sections objectForKey:key];
7258 if (section == nil) {
7259 _profile(SectionsView$reloadData$Section$Allocate)
7260 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7261 [sections setObject:section forKey:key];
7266 [section addToCount];
7268 _profile(SectionsView$reloadData$Filter)
7269 if (![package valid] || ![package visible])
7277 [sections_ addObjectsFromArray:[sections allValues]];
7279 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7281 for (Section *section in (id) sections_) {
7282 size_t count([section row]);
7286 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7287 [section setCount:count];
7288 [filtered_ addObject:section];
7291 [self updateNavigationItem];
7296 - (void) editButtonClicked {
7297 [self setEditing:![self isEditing] animated:YES];
7303 /* Changes Controller {{{ */
7304 @interface ChangesController : CyteViewController <
7305 UITableViewDataSource,
7308 _transient Database *database_;
7310 _H<NSArray> packages_;
7311 _H<NSMutableArray> sections_;
7312 _H<UITableView, 2> list_;
7316 - (id) initWithDatabase:(Database *)database;
7320 @implementation ChangesController
7322 - (NSURL *) navigationURL {
7323 return [NSURL URLWithString:@"cydia://changes"];
7326 - (void) viewDidAppear:(BOOL)animated {
7327 [super viewDidAppear:animated];
7328 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7331 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7332 NSInteger count([sections_ count]);
7333 return count == 0 ? 1 : count;
7336 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7337 if ([sections_ count] == 0)
7339 return [[sections_ objectAtIndex:section] name];
7342 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7343 if ([sections_ count] == 0)
7345 return [[sections_ objectAtIndex:section] count];
7348 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7349 @synchronized (database_) {
7350 if ([database_ era] != era_)
7353 NSUInteger sectionIndex([path section]);
7354 if (sectionIndex >= [sections_ count])
7356 Section *section([sections_ objectAtIndex:sectionIndex]);
7357 NSInteger row([path row]);
7358 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7361 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7362 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7364 cell = [[[PackageCell alloc] init] autorelease];
7366 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7367 [cell setPackage:package asSummary:false];
7371 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7372 Package *package([self packageAtIndexPath:path]);
7373 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7374 [view setDelegate:delegate_];
7375 [[self navigationController] pushViewController:view animated:YES];
7379 - (void) refreshButtonClicked {
7380 [delegate_ beginUpdate];
7381 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7384 - (void) upgradeButtonClicked {
7385 [delegate_ distUpgrade];
7386 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7390 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7392 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7393 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7394 [list_ setRowHeight:73];
7395 [(UITableView *) list_ setDataSource:self];
7396 [list_ setDelegate:self];
7397 [[self view] addSubview:list_];
7400 - (void) viewDidLoad {
7401 [super viewDidLoad];
7403 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7406 - (void) releaseSubviews {
7409 [super releaseSubviews];
7412 - (id) initWithDatabase:(Database *)database {
7413 if ((self = [super init]) != nil) {
7414 database_ = database;
7416 packages_ = [NSArray array];
7417 sections_ = [NSMutableArray arrayWithCapacity:16];
7421 - (NSMutableArray *) _reloadPackages {
7422 @synchronized (database_) {
7423 era_ = [database_ era];
7424 NSArray *packages([database_ packages]);
7426 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7429 _profile(ChangesController$_reloadPackages$Filter)
7430 for (Package *package in packages)
7431 if ([package upgradableAndEssential:YES] || [package visible])
7432 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7435 _profile(ChangesController$_reloadPackages$radixSort)
7436 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7443 - (void) _reloadData {
7448 UIProgressHUD *hud([delegate_ addProgressHUD]);
7449 [hud setText:UCLocalize("LOADING")];
7450 //NSLog(@"HUD:%@::%@", delegate_, hud);
7451 packages = [self yieldToSelector:@selector(_reloadPackages)];
7452 [delegate_ removeProgressHUD:hud];
7454 packages = [self _reloadPackages];
7457 @synchronized (database_) {
7458 if (era_ != [database_ era])
7461 packages_ = packages;
7462 [sections_ removeAllObjects];
7464 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7465 Section *ignored = nil;
7466 Section *section = nil;
7470 bool unseens = false;
7472 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7474 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7475 Package *package = [packages_ objectAtIndex:offset];
7477 BOOL uae = [package upgradableAndEssential:YES];
7481 time_t seen([package seen]);
7483 if (section == nil || last != seen) {
7487 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7490 _profile(ChangesController$reloadData$Allocate)
7491 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7492 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7493 [sections_ addObject:section];
7497 [section addToCount];
7498 } else if ([package ignored]) {
7499 if (ignored == nil) {
7500 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7502 [ignored addToCount];
7505 [upgradable addToCount];
7510 CFRelease(formatter);
7513 Section *last = [sections_ lastObject];
7514 size_t count = [last count];
7515 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7516 [sections_ removeLastObject];
7519 if ([ignored count] != 0)
7520 [sections_ insertObject:ignored atIndex:0];
7522 [sections_ insertObject:upgradable atIndex:0];
7526 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7527 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7528 style:UIBarButtonItemStylePlain
7530 action:@selector(upgradeButtonClicked)
7531 ] autorelease]) animated:YES];
7533 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7534 initWithTitle:UCLocalize("REFRESH")
7535 style:UIBarButtonItemStylePlain
7537 action:@selector(refreshButtonClicked)
7538 ] autorelease]) animated:YES];
7543 - (void) reloadData {
7545 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7550 /* Search Controller {{{ */
7551 @interface SearchController : FilteredPackageListController <
7554 _H<UISearchBar, 1> search_;
7558 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7559 - (void) reloadData;
7563 @implementation SearchController
7565 - (NSURL *) navigationURL {
7566 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7567 return [NSURL URLWithString:@"cydia://search"];
7569 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7572 - (void) useSearch {
7573 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7578 - (void) viewWillAppear:(BOOL)animated {
7579 [super viewWillAppear:animated];
7581 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7585 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7586 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7591 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7592 [search_ resignFirstResponder];
7596 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7597 [search_ setText:@""];
7598 [self searchBarButtonClicked:searchBar];
7601 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7602 [self searchBarButtonClicked:searchBar];
7605 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7606 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7610 - (bool) shouldYield {
7614 - (bool) shouldBlock {
7615 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7618 - (bool) isSummarized {
7619 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7622 - (bool) showsSections {
7626 - (NSMutableArray *) _reloadPackages {
7627 NSMutableArray *packages([super _reloadPackages]);
7628 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7629 [packages radixSortUsingSelector:@selector(rank)];
7633 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7634 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7635 search_ = [[[UISearchBar alloc] init] autorelease];
7636 [search_ setDelegate:self];
7639 [search_ setText:query];
7643 - (void) viewDidAppear:(BOOL)animated {
7644 [super viewDidAppear:animated];
7646 if (!searchloaded_) {
7647 searchloaded_ = YES;
7648 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7649 [search_ layoutSubviews];
7650 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7652 UITextField *textField;
7653 if ([search_ respondsToSelector:@selector(searchField)])
7654 textField = [search_ searchField];
7656 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7658 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7659 [textField setEnablesReturnKeyAutomatically:NO];
7660 [[self navigationItem] setTitleView:textField];
7664 - (void) reloadData {
7665 id object([search_ text]);
7666 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7667 object = [object componentsSeparatedByString:@" "];
7669 [self setObject:object];
7675 - (void) didSelectPackage:(Package *)package {
7676 [search_ resignFirstResponder];
7677 [super didSelectPackage:package];
7682 /* Package Settings Controller {{{ */
7683 @interface PackageSettingsController : CyteViewController <
7684 UITableViewDataSource,
7687 _transient Database *database_;
7689 _H<Package> package_;
7690 _H<UITableView, 2> table_;
7691 _H<UISwitch> subscribedSwitch_;
7692 _H<UISwitch> ignoredSwitch_;
7693 _H<UITableViewCell> subscribedCell_;
7694 _H<UITableViewCell> ignoredCell_;
7697 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7701 @implementation PackageSettingsController
7703 - (NSURL *) navigationURL {
7704 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7707 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7708 if (package_ == nil)
7711 if ([package_ installed] == nil)
7717 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7718 if (package_ == nil)
7721 // both sections contain just one item right now.
7725 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7729 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7731 return UCLocalize("SHOW_ALL_CHANGES_EX");
7733 return UCLocalize("IGNORE_UPGRADES_EX");
7736 - (void) onSubscribed:(id)control {
7737 bool value([control isOn]);
7738 if (package_ == nil)
7740 if ([package_ setSubscribed:value])
7741 [delegate_ updateData];
7744 - (void) _updateIgnored {
7745 const char *package([name_ UTF8String]);
7746 bool on([ignoredSwitch_ isOn]);
7748 pid_t pid(ExecFork());
7750 FILE *dpkg(popen("dpkg --set-selections", "w"));
7751 fwrite(package, strlen(package), 1, dpkg);
7754 fwrite(" hold\n", 6, 1, dpkg);
7756 fwrite(" install\n", 9, 1, dpkg);
7766 int result(waitpid(pid, &status, 0));
7769 _assert(result == pid);
7775 - (void) onIgnored:(id)control {
7776 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7777 [invocation setTarget:self];
7778 [invocation setSelector:@selector(_updateIgnored)];
7780 [delegate_ reloadDataWithInvocation:invocation];
7783 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7784 if (package_ == nil)
7787 switch ([indexPath section]) {
7788 case 0: return subscribedCell_;
7789 case 1: return ignoredCell_;
7798 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7800 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7801 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7802 [(UITableView *) table_ setDataSource:self];
7803 [table_ setDelegate:self];
7804 [[self view] addSubview:table_];
7806 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7807 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7808 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7810 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7811 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7812 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7814 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7815 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7816 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7817 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7819 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7820 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7821 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7822 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7825 - (void) viewDidLoad {
7826 [super viewDidLoad];
7828 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7831 - (void) releaseSubviews {
7833 subscribedCell_ = nil;
7835 ignoredSwitch_ = nil;
7836 subscribedSwitch_ = nil;
7838 [super releaseSubviews];
7841 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7842 if ((self = [super init]) != nil) {
7843 database_ = database;
7848 - (void) reloadData {
7851 package_ = [database_ packageWithName:name_];
7853 if (package_ != nil) {
7854 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7855 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7856 } // XXX: what now, G?
7858 [table_ reloadData];
7864 /* Installed Controller {{{ */
7865 @interface InstalledController : FilteredPackageListController {
7869 - (id) initWithDatabase:(Database *)database;
7871 - (void) updateRoleButton;
7872 - (void) queueStatusDidChange;
7876 @implementation InstalledController
7878 - (NSURL *) navigationURL {
7879 return [NSURL URLWithString:@"cydia://installed"];
7882 - (id) initWithDatabase:(Database *)database {
7883 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7884 [self updateRoleButton];
7885 [self queueStatusDidChange];
7890 - (void) queueButtonClicked {
7895 - (void) queueStatusDidChange {
7899 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7900 initWithTitle:UCLocalize("QUEUE")
7901 style:UIBarButtonItemStyleDone
7903 action:@selector(queueButtonClicked)
7906 [[self navigationItem] setLeftBarButtonItem:nil];
7912 - (void) updateRoleButton {
7913 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7914 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7915 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7916 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7918 action:@selector(roleButtonClicked)
7922 - (void) roleButtonClicked {
7923 [self setObject:[NSNumber numberWithBool:expert_]];
7927 [self updateRoleButton];
7933 /* Source Cell {{{ */
7934 @interface SourceCell : CyteTableViewCell <
7935 CyteTableViewCellDelegate
7938 _H<NSString> origin_;
7939 _H<NSString> label_;
7942 - (void) setSource:(Source *)source;
7946 @implementation SourceCell
7948 - (void) _setImage:(UIImage *)image {
7950 [content_ setNeedsDisplay];
7953 - (void) _setSource:(Source *)source {
7954 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7956 if (NSString *base = [source base])
7957 if ([base length] != 0) {
7958 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7960 if (NSData *data = [NSURLConnection
7961 sendSynchronousRequest:[NSURLRequest
7963 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7967 returningResponse:NULL
7970 if (UIImage *image = [UIImage imageWithData:data])
7971 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7977 - (void) setSource:(Source *)source {
7978 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7980 origin_ = [source name];
7981 label_ = [source uri];
7983 [content_ setNeedsDisplay];
7985 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7988 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7989 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7990 UIView *content([self contentView]);
7991 CGRect bounds([content bounds]);
7993 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7994 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7995 [content_ setBackgroundColor:[UIColor whiteColor]];
7996 [content addSubview:content_];
7998 [content_ setDelegate:self];
7999 [content_ setOpaque:YES];
8003 - (NSString *) accessibilityLabel {
8007 - (void) drawContentRect:(CGRect)rect {
8008 bool highlighted(highlighted_);
8009 float width(rect.size.width);
8012 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8019 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8023 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8028 /* Source Controller {{{ */
8029 @interface SourceController : FilteredPackageListController {
8030 _transient Source *source_;
8034 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8038 @implementation SourceController
8040 - (NSURL *) navigationURL {
8041 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8044 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8045 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8047 key_ = [source key];
8051 - (void) reloadData {
8052 source_ = [database_ sourceWithKey:key_];
8053 key_ = [source_ key];
8054 [self setObject:source_];
8056 [[self navigationItem] setTitle:[source_ label]];
8063 /* Sources Controller {{{ */
8064 @interface SourcesController : CyteViewController <
8065 UITableViewDataSource,
8068 _transient Database *database_;
8069 _H<UITableView, 2> list_;
8070 _H<NSMutableArray> sources_;
8074 _H<UIProgressHUD> hud_;
8077 //NSURLConnection *installer_;
8078 NSURLConnection *trivial_;
8079 NSURLConnection *trivial_bz2_;
8080 NSURLConnection *trivial_gz_;
8081 //NSURLConnection *automatic_;
8086 - (id) initWithDatabase:(Database *)database;
8087 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8091 @implementation SourcesController
8093 - (void) _releaseConnection:(NSURLConnection *)connection {
8094 if (connection != nil) {
8095 [connection cancel];
8096 //[connection setDelegate:nil];
8097 [connection release];
8102 //[self _releaseConnection:installer_];
8103 [self _releaseConnection:trivial_];
8104 [self _releaseConnection:trivial_gz_];
8105 [self _releaseConnection:trivial_bz2_];
8106 //[self _releaseConnection:automatic_];
8111 - (NSURL *) navigationURL {
8112 return [NSURL URLWithString:@"cydia://sources"];
8115 - (void) viewDidAppear:(BOOL)animated {
8116 [super viewDidAppear:animated];
8117 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8120 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8121 return offset_ == 0 ? 1 : 2;
8124 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8125 switch (section + (offset_ == 0 ? 1 : 0)) {
8126 case 0: return UCLocalize("ENTERED_BY_USER");
8127 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8133 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8134 int count = [sources_ count];
8136 case 0: return (offset_ == 0 ? count : offset_);
8137 case 1: return count - offset_;
8143 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8145 switch (indexPath.section) {
8146 case 0: idx = indexPath.row; break;
8147 case 1: idx = indexPath.row + offset_; break;
8151 return [sources_ objectAtIndex:idx];
8154 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8155 static NSString *cellIdentifier = @"SourceCell";
8157 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8158 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8159 [cell setSource:[self sourceAtIndexPath:indexPath]];
8160 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8165 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8166 Source *source = [self sourceAtIndexPath:indexPath];
8168 SourceController *controller = [[[SourceController alloc]
8169 initWithDatabase:database_
8173 [controller setDelegate:delegate_];
8175 [[self navigationController] pushViewController:controller animated:YES];
8178 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8179 Source *source = [self sourceAtIndexPath:indexPath];
8180 return [source record] != nil;
8183 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8184 if (editingStyle == UITableViewCellEditingStyleDelete) {
8185 Source *source = [self sourceAtIndexPath:indexPath];
8186 [Sources_ removeObjectForKey:[source key]];
8187 [delegate_ syncData];
8192 [delegate_ addTrivialSource:href_];
8193 [delegate_ syncData];
8196 - (NSString *) getWarning {
8197 NSString *href(href_);
8198 NSRange colon([href rangeOfString:@"://"]);
8199 if (colon.location != NSNotFound)
8200 href = [href substringFromIndex:(colon.location + 3)];
8201 href = [href stringByAddingPercentEscapes];
8202 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8203 href = [href stringByCachingURLWithCurrentCDN];
8205 NSURL *url([NSURL URLWithString:href]);
8207 NSStringEncoding encoding;
8208 NSError *error(nil);
8210 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8211 return [warning length] == 0 ? nil : warning;
8215 - (void) _endConnection:(NSURLConnection *)connection {
8216 // XXX: the memory management in this method is horribly awkward
8218 NSURLConnection **field = NULL;
8219 if (connection == trivial_)
8221 else if (connection == trivial_bz2_)
8222 field = &trivial_bz2_;
8223 else if (connection == trivial_gz_)
8224 field = &trivial_gz_;
8225 _assert(field != NULL);
8226 [connection release];
8231 trivial_bz2_ == nil &&
8234 [delegate_ releaseNetworkActivityIndicator];
8236 [delegate_ removeProgressHUD:hud_];
8242 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8245 UIAlertView *alert = [[[UIAlertView alloc]
8246 initWithTitle:UCLocalize("SOURCE_WARNING")
8249 cancelButtonTitle:UCLocalize("CANCEL")
8251 UCLocalize("ADD_ANYWAY"),
8255 [alert setContext:@"warning"];
8256 [alert setNumberOfRows:1];
8260 } else if (error_ != nil) {
8261 UIAlertView *alert = [[[UIAlertView alloc]
8262 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8263 message:[error_ localizedDescription]
8265 cancelButtonTitle:UCLocalize("OK")
8266 otherButtonTitles:nil
8269 [alert setContext:@"urlerror"];
8272 UIAlertView *alert = [[[UIAlertView alloc]
8273 initWithTitle:UCLocalize("NOT_REPOSITORY")
8274 message:UCLocalize("NOT_REPOSITORY_EX")
8276 cancelButtonTitle:UCLocalize("OK")
8277 otherButtonTitles:nil
8280 [alert setContext:@"trivial"];
8289 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8290 switch ([response statusCode]) {
8296 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8297 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8299 [self _endConnection:connection];
8302 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8303 [self _endConnection:connection];
8306 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8307 NSURL *url([NSURL URLWithString:href]);
8309 NSMutableURLRequest *request = [NSMutableURLRequest
8311 cachePolicy:NSURLRequestUseProtocolCachePolicy
8312 timeoutInterval:120.0
8315 [request setHTTPMethod:method];
8317 if (Machine_ != NULL)
8318 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8320 if ([url isCydiaSecure]) {
8321 if (UniqueID_ != nil)
8322 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8325 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8328 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8329 NSString *context([alert context]);
8331 if ([context isEqualToString:@"source"]) {
8334 NSString *href = [[alert textField] text];
8336 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8338 if (![href hasSuffix:@"/"])
8339 href_ = [href stringByAppendingString:@"/"];
8343 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8344 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8345 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8346 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8350 // XXX: this is stupid
8351 hud_ = [delegate_ addProgressHUD];
8352 [hud_ setText:UCLocalize("VERIFYING_URL")];
8353 [delegate_ retainNetworkActivityIndicator];
8362 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8363 } else if ([context isEqualToString:@"trivial"])
8364 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8365 else if ([context isEqualToString:@"urlerror"])
8366 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8367 else if ([context isEqualToString:@"warning"]) {
8381 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8386 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8388 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8389 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8390 [list_ setRowHeight:56];
8391 [(UITableView *) list_ setDataSource:self];
8392 [list_ setDelegate:self];
8393 [[self view] addSubview:list_];
8396 - (void) viewDidLoad {
8397 [super viewDidLoad];
8399 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8400 [self updateButtonsForEditingStatus:NO animated:NO];
8403 - (void) releaseSubviews {
8406 [super releaseSubviews];
8409 - (id) initWithDatabase:(Database *)database {
8410 if ((self = [super init]) != nil) {
8411 database_ = database;
8412 sources_ = [NSMutableArray arrayWithCapacity:16];
8416 - (void) reloadData {
8420 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8423 [sources_ removeAllObjects];
8424 [sources_ addObjectsFromArray:[database_ sources]];
8426 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8429 int count([sources_ count]);
8431 for (int i = 0; i != count; i++) {
8432 if ([[sources_ objectAtIndex:i] record] == nil)
8437 [list_ setEditing:NO];
8438 [self updateButtonsForEditingStatus:NO animated:NO];
8442 - (void) showAddSourcePrompt {
8443 UIAlertView *alert = [[[UIAlertView alloc]
8444 initWithTitle:UCLocalize("ENTER_APT_URL")
8447 cancelButtonTitle:UCLocalize("CANCEL")
8449 UCLocalize("ADD_SOURCE"),
8453 [alert setContext:@"source"];
8455 [alert setNumberOfRows:1];
8456 [alert addTextFieldWithValue:@"http://" label:@""];
8458 UITextInputTraits *traits = [[alert textField] textInputTraits];
8459 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8460 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8461 [traits setKeyboardType:UIKeyboardTypeURL];
8462 // XXX: UIReturnKeyDone
8463 [traits setReturnKeyType:UIReturnKeyNext];
8468 - (void) addButtonClicked {
8469 [self showAddSourcePrompt];
8472 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8473 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8474 initWithTitle:UCLocalize("ADD")
8475 style:UIBarButtonItemStylePlain
8477 action:@selector(addButtonClicked)
8478 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8480 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8481 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8482 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8484 action:@selector(editButtonClicked)
8485 ] autorelease] animated:animated];
8487 if (IsWildcat_ && !editing)
8488 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8489 initWithTitle:UCLocalize("SETTINGS")
8490 style:UIBarButtonItemStylePlain
8492 action:@selector(settingsButtonClicked)
8496 - (void) settingsButtonClicked {
8497 [delegate_ showSettings];
8500 - (void) editButtonClicked {
8501 [list_ setEditing:![list_ isEditing] animated:YES];
8503 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8509 /* Settings Controller {{{ */
8510 @interface SettingsController : CyteViewController <
8511 UITableViewDataSource,
8514 _transient Database *database_;
8515 // XXX: ok, "roledelegate_"?...
8516 _transient id roledelegate_;
8517 _H<UITableView, 2> table_;
8518 _H<UISegmentedControl> segment_;
8519 _H<UIView> container_;
8522 - (void) showDoneButton;
8523 - (void) resizeSegmentedControl;
8527 @implementation SettingsController
8530 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8532 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8533 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8534 [table_ setDelegate:self];
8535 [(UITableView *) table_ setDataSource:self];
8536 [[self view] addSubview:table_];
8538 NSArray *items = [NSArray arrayWithObjects:
8540 UCLocalize("HACKER"),
8541 UCLocalize("DEVELOPER"),
8543 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8544 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8545 [container_ addSubview:segment_];
8548 - (void) viewDidLoad {
8549 [super viewDidLoad];
8551 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8554 if ([Role_ isEqualToString:@"User"]) index = 0;
8555 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8556 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8558 [segment_ setSelectedSegmentIndex:index];
8559 [self showDoneButton];
8562 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8563 [self resizeSegmentedControl];
8566 - (void) releaseSubviews {
8571 [super releaseSubviews];
8574 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8575 if ((self = [super init]) != nil) {
8576 database_ = database;
8577 roledelegate_ = delegate;
8581 - (void) resizeSegmentedControl {
8582 CGFloat width = [[self view] frame].size.width;
8583 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8586 - (void) viewWillAppear:(BOOL)animated {
8587 [super viewWillAppear:animated];
8589 [self resizeSegmentedControl];
8592 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8593 [self resizeSegmentedControl];
8596 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8597 [self resizeSegmentedControl];
8601 NSString *role(nil);
8603 switch ([segment_ selectedSegmentIndex]) {
8604 case 0: role = @"User"; break;
8605 case 1: role = @"Hacker"; break;
8606 case 2: role = @"Developer"; break;
8611 if (![role isEqualToString:Role_]) {
8612 bool rolling(Role_ == nil);
8615 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8619 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8623 [roledelegate_ loadData];
8625 [roledelegate_ updateData];
8629 - (void) segmentChanged:(UISegmentedControl *)control {
8630 [self showDoneButton];
8633 - (void) saveAndClose {
8636 [[self navigationItem] setRightBarButtonItem:nil];
8637 [[self navigationController] dismissModalViewControllerAnimated:YES];
8640 - (void) doneButtonClicked {
8641 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8642 [spinner startAnimating];
8643 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8644 [[self navigationItem] setRightBarButtonItem:spinItem];
8646 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8649 - (void) showDoneButton {
8650 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8651 initWithTitle:UCLocalize("DONE")
8652 style:UIBarButtonItemStyleDone
8654 action:@selector(doneButtonClicked)
8655 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8658 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8659 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8663 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8667 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8668 return nil; // This method is required by the protocol.
8671 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8673 return UCLocalize("ROLE_EX");
8675 return [NSString stringWithFormat:
8676 @"%@: %@\n%@: %@\n%@: %@",
8677 UCLocalize("USER"), UCLocalize("USER_EX"),
8678 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8679 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8684 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8685 return section == 3 ? 44.0f : 0;
8688 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8689 return section == 3 ? container_ : nil;
8692 - (void) reloadData {
8695 [table_ reloadData];
8700 /* Stash Controller {{{ */
8701 @interface StashController : CyteViewController {
8702 _H<UIActivityIndicatorView> spinner_;
8703 _H<UILabel> status_;
8704 _H<UILabel> caption_;
8709 @implementation StashController
8712 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8713 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8715 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8716 CGRect spinrect = [spinner_ frame];
8717 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8718 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8719 [spinner_ setFrame:spinrect];
8720 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8721 [[self view] addSubview:spinner_];
8722 [spinner_ startAnimating];
8725 captrect.size.width = [[self view] frame].size.width;
8726 captrect.size.height = 40.0f;
8727 captrect.origin.x = 0;
8728 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8729 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8730 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8731 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8732 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8733 [caption_ setTextColor:[UIColor whiteColor]];
8734 [caption_ setBackgroundColor:[UIColor clearColor]];
8735 [caption_ setShadowColor:[UIColor blackColor]];
8736 [caption_ setTextAlignment:UITextAlignmentCenter];
8737 [[self view] addSubview:caption_];
8740 statusrect.size.width = [[self view] frame].size.width;
8741 statusrect.size.height = 30.0f;
8742 statusrect.origin.x = 0;
8743 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8744 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8745 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8746 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8747 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8748 [status_ setTextColor:[UIColor whiteColor]];
8749 [status_ setBackgroundColor:[UIColor clearColor]];
8750 [status_ setShadowColor:[UIColor blackColor]];
8751 [status_ setTextAlignment:UITextAlignmentCenter];
8752 [[self view] addSubview:status_];
8755 - (void) releaseSubviews {
8760 [super releaseSubviews];
8766 @interface CYURLCache : SDURLCache {
8771 @implementation CYURLCache
8773 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8776 else if ([event isEqualToString:@"no-cache"])
8778 else if ([event isEqualToString:@"store"])
8780 else if ([event isEqualToString:@"invalid"])
8782 else if ([event isEqualToString:@"memory"])
8784 else if ([event isEqualToString:@"disk"])
8786 else if ([event isEqualToString:@"miss"])
8789 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8793 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8794 if (NSURLResponse *response = [cached response])
8795 if (NSString *mime = [response MIMEType])
8796 if ([mime isEqualToString:@"text/cache-manifest"]) {
8797 NSURL *url([response URL]);
8800 NSLog(@"###: %@", [url absoluteString]);
8803 @synchronized (HostConfig_) {
8804 [CachedURLs_ addObject:url];
8808 [super storeCachedResponse:cached forRequest:request];
8813 @interface Cydia : UIApplication <
8814 ConfirmationControllerDelegate,
8817 UINavigationControllerDelegate,
8818 UITabBarControllerDelegate
8820 _H<UIWindow> window_;
8821 _H<CYTabBarController> tabbar_;
8822 _H<CydiaLoadingViewController> emulated_;
8824 _H<NSMutableArray> essential_;
8825 _H<NSMutableArray> broken_;
8827 Database *database_;
8829 _H<NSURL> starturl_;
8834 _H<StashController> stash_;
8843 @implementation Cydia
8845 - (void) beginUpdate {
8846 [tabbar_ beginUpdate];
8850 return [tabbar_ updating];
8854 if ([broken_ count] != 0) {
8855 int count = [broken_ count];
8857 UIAlertView *alert = [[[UIAlertView alloc]
8858 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8859 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8861 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8863 UCLocalize("TEMPORARY_IGNORE"),
8867 [alert setContext:@"fixhalf"];
8868 [alert setNumberOfRows:2];
8870 } else if (!Ignored_ && [essential_ count] != 0) {
8871 int count = [essential_ count];
8873 UIAlertView *alert = [[[UIAlertView alloc]
8874 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8875 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8877 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8879 UCLocalize("UPGRADE_ESSENTIAL"),
8880 UCLocalize("COMPLETE_UPGRADE"),
8884 [alert setContext:@"upgrade"];
8889 - (void) _saveConfig {
8895 NSString *error(nil);
8897 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8899 NSError *error(nil);
8900 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8901 NSLog(@"failure to save metadata data: %@", error);
8906 NSLog(@"failure to serialize metadata: %@", error);
8913 // Navigation controller for the queuing badge.
8914 - (UINavigationController *) queueNavigationController {
8915 NSArray *controllers = [tabbar_ viewControllers];
8916 return [controllers objectAtIndex:3];
8919 - (void) unloadData {
8920 [tabbar_ unloadData];
8923 - (void) _updateData {
8927 UINavigationController *navigation = [self queueNavigationController];
8929 id queuedelegate = nil;
8930 if ([[navigation viewControllers] count] > 0)
8931 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8933 [queuedelegate queueStatusDidChange];
8934 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8937 - (void) _refreshIfPossible:(NSDate *)update {
8938 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8940 bool recently = false;
8941 if (update != nil) {
8942 NSTimeInterval interval([update timeIntervalSinceNow]);
8943 if (interval <= 0 && interval > -(15*60))
8947 // Don't automatic refresh if:
8948 // - We already refreshed recently.
8949 // - We already auto-refreshed this launch.
8950 // - Auto-refresh is disabled.
8951 if (recently || loaded_ || ManualRefresh) {
8952 // If we are cancelling, we need to make sure it knows it's already loaded.
8955 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8957 // We are going to load, so remember that.
8960 SCNetworkReachabilityFlags flags; {
8961 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8962 SCNetworkReachabilityGetFlags(reachability, &flags);
8963 CFRelease(reachability);
8966 // XXX: this elaborate mess is what Apple is using to determine this? :(
8967 // XXX: do we care if the user has to intervene? maybe that's ok?
8969 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8970 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8971 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8972 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8973 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8974 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8978 // If we can reach the server, auto-refresh!
8980 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8986 - (void) refreshIfPossible {
8987 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8990 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8991 @synchronized (self) {
8992 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8993 [hud setText:UCLocalize("RELOADING_DATA")];
8995 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8998 [self removeProgressHUD:hud];
9002 [essential_ removeAllObjects];
9003 [broken_ removeAllObjects];
9005 NSArray *packages([database_ packages]);
9006 for (Package *package in packages) {
9008 [broken_ addObject:package];
9009 if ([package upgradableAndEssential:NO]) {
9010 if ([package essential])
9011 [essential_ addObject:package];
9016 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9019 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9020 [changesItem setBadgeValue:badge];
9021 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9022 [self setApplicationIconBadgeNumber:changes];
9025 [changesItem setBadgeValue:nil];
9026 [changesItem setAnimatedBadge:NO];
9027 [self setApplicationIconBadgeNumber:0];
9032 [self refreshIfPossible];
9035 - (void) updateData {
9041 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9044 - (void) disemulate {
9045 if (emulated_ == nil)
9048 [window_ addSubview:[tabbar_ view]];
9049 [[emulated_ view] removeFromSuperview];
9051 [window_ setUserInteractionEnabled:YES];
9054 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9055 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9057 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9059 UIViewController *parent;
9060 if (emulated_ == nil)
9069 [parent presentModalViewController:navigation animated:YES];
9072 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9073 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9075 if (navigation != nil)
9076 [navigation pushViewController:progress animated:YES];
9078 [self presentModalViewController:progress force:YES];
9080 [progress invoke:invocation withTitle:title];
9084 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9085 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9088 - (void) repairWithInvocation:(NSInvocation *)invocation {
9090 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9094 - (void) repairWithSelector:(SEL)selector {
9095 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9098 - (void) reloadData {
9099 [self reloadDataWithInvocation:nil];
9104 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9107 - (void) addSource:(NSDictionary *) source {
9111 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9112 AddSource(href, distribution, sections);
9115 - (void) addTrivialSource:(NSString *)href {
9116 AddSource(href, @"./");
9119 - (void) updateValues {
9124 pkgProblemResolver *resolver = [database_ resolver];
9126 resolver->InstallProtect();
9127 if (!resolver->Resolve(true))
9132 // XXX: this is a really crappy way of doing this.
9133 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9134 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9135 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9136 if ([tabbar_ updating])
9137 [tabbar_ cancelUpdate];
9139 if (![database_ prepare])
9142 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9143 [page setDelegate:self];
9144 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9147 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9148 [tabbar_ presentModalViewController:confirm_ animated:YES];
9154 @synchronized (self) {
9159 - (void) clearPackage:(Package *)package {
9160 @synchronized (self) {
9167 - (void) installPackages:(NSArray *)packages {
9168 @synchronized (self) {
9169 for (Package *package in packages)
9176 - (void) installPackage:(Package *)package {
9177 @synchronized (self) {
9184 - (void) removePackage:(Package *)package {
9185 @synchronized (self) {
9192 - (void) distUpgrade {
9193 @synchronized (self) {
9194 if (![database_ upgrade])
9201 [database_ perform];
9202 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9205 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9208 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9212 - (void) showSettings {
9213 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9216 - (void) retainNetworkActivityIndicator {
9217 if (activity_++ == 0)
9218 [self setNetworkActivityIndicatorVisible:YES];
9221 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9225 - (void) releaseNetworkActivityIndicator {
9226 if (--activity_ == 0)
9227 [self setNetworkActivityIndicatorVisible:NO];
9230 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9235 - (void) cancelAndClear:(bool)clear {
9236 @synchronized (self) {
9248 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9249 NSString *context([alert context]);
9251 if ([context isEqualToString:@"conffile"]) {
9252 FILE *input = [database_ input];
9253 if (button == [alert cancelButtonIndex])
9254 fprintf(input, "N\n");
9255 else if (button == [alert firstOtherButtonIndex])
9256 fprintf(input, "Y\n");
9259 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9260 } else if ([context isEqualToString:@"fixhalf"]) {
9261 if (button == [alert cancelButtonIndex]) {
9262 @synchronized (self) {
9263 for (Package *broken in (id) broken_) {
9266 NSString *id = [broken id];
9267 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9268 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9269 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9270 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9276 } else if (button == [alert firstOtherButtonIndex]) {
9277 [broken_ removeAllObjects];
9281 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9282 } else if ([context isEqualToString:@"upgrade"]) {
9283 if (button == [alert firstOtherButtonIndex]) {
9284 @synchronized (self) {
9285 for (Package *essential in (id) essential_)
9286 [essential install];
9291 } else if (button == [alert firstOtherButtonIndex] + 1) {
9293 } else if (button == [alert cancelButtonIndex]) {
9297 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9301 - (void) system:(NSString *)command {
9302 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9305 system([command UTF8String]);
9311 - (void) applicationWillSuspend {
9313 [super applicationWillSuspend];
9316 - (BOOL) isSafeToSuspend {
9319 NSLog(@"isSafeToSuspend: locked_ != 0");
9324 // Use external process status API internally.
9325 // This is probably a really bad idea.
9326 // XXX: what is the point of this? does this solve anything at all?
9327 uint64_t status = 0;
9329 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9330 notify_get_state(notify_token, &status);
9331 notify_cancel(notify_token);
9336 NSLog(@"isSafeToSuspend: status != 0");
9342 NSLog(@"isSafeToSuspend: -> true");
9347 - (void) applicationSuspend:(__GSEvent *)event {
9348 if ([self isSafeToSuspend])
9349 [super applicationSuspend:event];
9352 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9353 if ([self isSafeToSuspend])
9354 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9357 - (void) _setSuspended:(BOOL)value {
9358 if ([self isSafeToSuspend])
9359 [super _setSuspended:value];
9362 - (UIProgressHUD *) addProgressHUD {
9363 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9364 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9366 [window_ setUserInteractionEnabled:NO];
9368 UIViewController *target(tabbar_);
9369 if (UIViewController *modal = [target modalViewController])
9372 UIView *view([target view]);
9373 [view addSubview:hud];
9381 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9384 [hud removeFromSuperview];
9385 [window_ setUserInteractionEnabled:YES];
9388 - (CyteViewController *) pageForPackage:(NSString *)name {
9389 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9392 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9393 NSString *scheme([[url scheme] lowercaseString]);
9394 if ([[url absoluteString] length] <= [scheme length] + 3)
9396 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9397 NSArray *components([path pathComponents]);
9399 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9400 return [self pageForPackage:[components objectAtIndex:1]];
9402 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9405 NSString *base([components objectAtIndex:0]);
9407 CyteViewController *controller = nil;
9409 if ([base isEqualToString:@"url"]) {
9410 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9411 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9412 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9413 } else if (!external && [components count] == 1) {
9414 if ([base isEqualToString:@"manage"]) {
9415 controller = [[[ManageController alloc] init] autorelease];
9418 if ([base isEqualToString:@"sources"]) {
9419 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9422 if ([base isEqualToString:@"home"]) {
9423 controller = [[[HomeController alloc] init] autorelease];
9426 if ([base isEqualToString:@"sections"]) {
9427 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9430 if ([base isEqualToString:@"search"]) {
9431 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9434 if ([base isEqualToString:@"changes"]) {
9435 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9438 if ([base isEqualToString:@"installed"]) {
9439 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9441 } else if ([components count] == 2) {
9442 NSString *argument = [components objectAtIndex:1];
9444 if ([base isEqualToString:@"package"]) {
9445 controller = [self pageForPackage:argument];
9448 if (!external && [base isEqualToString:@"search"]) {
9449 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9452 if (!external && [base isEqualToString:@"sections"]) {
9453 if ([argument isEqualToString:@"all"])
9455 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9458 if (!external && [base isEqualToString:@"sources"]) {
9459 if ([argument isEqualToString:@"add"]) {
9460 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9461 [(SourcesController *)controller showAddSourcePrompt];
9463 Source *source = [database_ sourceWithKey:argument];
9464 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9468 if (!external && [base isEqualToString:@"launch"]) {
9469 [self launchApplicationWithIdentifier:argument suspended:NO];
9472 } else if (!external && [components count] == 3) {
9473 NSString *arg1 = [components objectAtIndex:1];
9474 NSString *arg2 = [components objectAtIndex:2];
9476 if ([base isEqualToString:@"package"]) {
9477 if ([arg2 isEqualToString:@"settings"]) {
9478 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9479 } else if ([arg2 isEqualToString:@"files"]) {
9480 if (Package *package = [database_ packageWithName:arg1]) {
9481 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9482 [(FileTable *)controller setPackage:package];
9488 [controller setDelegate:self];
9492 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9493 CyteViewController *page([self pageForURL:url forExternal:external]);
9496 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9497 [nav setViewControllers:[NSArray arrayWithObject:page]];
9498 [tabbar_ setUnselectedViewController:nav];
9504 - (void) applicationOpenURL:(NSURL *)url {
9505 [super applicationOpenURL:url];
9510 [self openCydiaURL:url forExternal:YES];
9513 - (void) applicationWillResignActive:(UIApplication *)application {
9514 // Stop refreshing if you get a phone call or lock the device.
9515 if ([tabbar_ updating])
9516 [tabbar_ cancelUpdate];
9518 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9519 [super applicationWillResignActive:application];
9522 - (void) saveState {
9523 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9524 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9525 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9531 - (void) applicationWillTerminate:(UIApplication *)application {
9535 - (void) setConfigurationData:(NSString *)data {
9536 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9538 if (!conffile_r(data)) {
9539 lprintf("E:invalid conffile\n");
9543 NSString *ofile = conffile_r[1];
9544 //NSString *nfile = conffile_r[2];
9546 UIAlertView *alert = [[[UIAlertView alloc]
9547 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9548 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9550 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9552 UCLocalize("ACCEPT_NEW_COPY"),
9553 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9557 [alert setContext:@"conffile"];
9558 [alert setNumberOfRows:2];
9562 - (void) addStashController {
9564 stash_ = [[[StashController alloc] init] autorelease];
9565 [window_ addSubview:[stash_ view]];
9568 - (void) removeStashController {
9569 [[stash_ view] removeFromSuperview];
9575 [self setIdleTimerDisabled:YES];
9577 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9578 UpdateExternalStatus(1);
9579 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9580 UpdateExternalStatus(0);
9582 [self removeStashController];
9584 if (ExecFork() == 0) {
9585 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9586 perror("launchctl stop");
9590 - (void) setupViewControllers {
9591 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9593 NSMutableArray *items([NSMutableArray arrayWithObjects:
9594 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9595 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9596 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9597 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9601 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9602 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9604 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9607 NSMutableArray *controllers([NSMutableArray array]);
9608 for (UITabBarItem *item in items) {
9609 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9610 [controller setTabBarItem:item];
9611 [controllers addObject:controller];
9613 [tabbar_ setViewControllers:controllers];
9615 [tabbar_ setUpdateDelegate:self];
9618 - (void) applicationDidFinishLaunching:(id)unused {
9620 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9621 [self setApplicationSupportsShakeToEdit:NO];
9623 @synchronized (HostConfig_) {
9624 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9627 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9628 initWithMemoryCapacity:524288
9629 diskCapacity:10485760
9630 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9633 [CydiaWebViewController _initialize];
9635 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9637 // this would disallow http{,s} URLs from accessing this data
9638 //[WebView registerURLSchemeAsLocal:@"cydia"];
9640 Font12_ = [UIFont systemFontOfSize:12];
9641 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9642 Font14_ = [UIFont systemFontOfSize:14];
9643 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9644 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9646 essential_ = [NSMutableArray arrayWithCapacity:4];
9647 broken_ = [NSMutableArray arrayWithCapacity:4];
9649 // XXX: I really need this thing... like, seriously... I'm sorry
9650 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9652 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9653 [window_ orderFront:self];
9654 [window_ makeKey:self];
9655 [window_ setHidden:NO];
9658 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9659 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9660 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9661 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9662 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9663 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9664 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9665 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9666 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9669 [self addStashController];
9670 // XXX: this would be much cleaner as a yieldToSelector:
9671 // that way the removeStashController could happen right here inline
9672 // we also could no longer require the useless stash_ field anymore
9673 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9677 database_ = [Database sharedInstance];
9678 [database_ setDelegate:self];
9680 [window_ setUserInteractionEnabled:NO];
9681 [self setupViewControllers];
9683 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9684 [window_ addSubview:[emulated_ view]];
9686 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9690 - (NSArray *) defaultStartPages {
9691 NSMutableArray *standard = [NSMutableArray array];
9692 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9693 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9694 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9696 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9698 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9699 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9701 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9708 [window_ setUserInteractionEnabled:YES];
9709 [self showSettings];
9712 if ([emulated_ modalViewController] != nil)
9713 [emulated_ dismissModalViewControllerAnimated:YES];
9714 [window_ setUserInteractionEnabled:NO];
9722 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9723 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9724 int standardIndex = 0;
9725 NSArray *standard = [self defaultStartPages];
9732 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9733 if (valid && closed != nil) {
9734 NSTimeInterval interval([closed timeIntervalSinceNow]);
9735 // XXX: Is 15 minutes the optimal time here?
9736 if (interval > 0 && interval <= -(15*60))
9740 if (valid && [saved count] != [standard count])
9744 for (unsigned int i = 0; i < [standard count]; i++) {
9745 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9746 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9747 // but it's good enough for now.
9748 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9755 NSArray *items = nil;
9757 [tabbar_ setSelectedIndex:savedIndex];
9760 [tabbar_ setSelectedIndex:standardIndex];
9764 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9765 NSArray *stack = [items objectAtIndex:tab];
9766 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9767 NSMutableArray *current = [NSMutableArray array];
9769 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9770 NSString *addr = [stack objectAtIndex:nav];
9771 NSURL *url = [NSURL URLWithString:addr];
9772 CyteViewController *page = [self pageForURL:url forExternal:NO];
9774 [current addObject:page];
9777 [navigation setViewControllers:current];
9780 // (Try to) show the startup URL.
9781 if (starturl_ != nil) {
9782 [self openCydiaURL:starturl_ forExternal:NO];
9787 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9788 if (item != nil && IsWildcat_) {
9789 [sheet showFromBarButtonItem:item animated:YES];
9791 [sheet showInView:window_];
9795 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9796 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9797 [progress setTitle:task];
9798 [progress addProgressEvent:event];
9801 - (void) addProgressEventForTask:(NSArray *)data {
9802 CydiaProgressEvent *event([data objectAtIndex:0]);
9803 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9804 [self addProgressEvent:event forTask:task];
9807 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9808 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9814 id Alloc_(id self, SEL selector) {
9815 id object = alloc_(self, selector);
9816 lprintf("[%s]A-%p\n", self->isa->name, object);
9821 id Dealloc_(id self, SEL selector) {
9822 id object = dealloc_(self, selector);
9823 lprintf("[%s]D-%p\n", self->isa->name, object);
9827 Class $WebDefaultUIKitDelegate;
9829 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9830 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9831 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9832 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9835 static NSSet *MobilizedFiles_;
9837 static NSURL *MobilizeURL(NSURL *url) {
9838 NSString *path([url path]);
9839 if ([path hasPrefix:@"/var/root/"]) {
9840 NSString *file([path substringFromIndex:10]);
9841 if ([MobilizedFiles_ containsObject:file])
9842 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9848 Class $CFXPreferencesPropertyListSource;
9849 @class CFXPreferencesPropertyListSource;
9851 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9852 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9853 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9854 url = MobilizeURL(url);
9855 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9856 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9862 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9863 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9864 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9865 url = MobilizeURL(url);
9866 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9867 //NSLog(@"%@ %@", [url absoluteString], value);
9873 Class $NSURLConnection;
9875 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9876 NSMutableURLRequest *copy([request mutableCopy]);
9878 NSURL *url([copy URL]);
9880 NSString *href([url absoluteString]);
9881 NSString *host([url host]);
9882 NSString *scheme([[url scheme] lowercaseString]);
9884 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9886 @synchronized (HostConfig_) {
9887 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9888 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9889 [copy setHTTPShouldUsePipelining:YES];
9891 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9892 if ([control isEqualToString:@"max-age=0"])
9893 if ([CachedURLs_ containsObject:href]) {
9895 NSLog(@"~~~: %@", href);
9898 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9900 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9901 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9902 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9906 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9910 int main(int argc, char *argv[]) {
9911 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9915 UpdateExternalStatus(0);
9917 if (Class $UIDevice = objc_getClass("UIDevice")) {
9918 UIDevice *device([$UIDevice currentDevice]);
9919 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9923 UIScreen *screen([UIScreen mainScreen]);
9924 if ([screen respondsToSelector:@selector(scale)])
9925 ScreenScale_ = [screen scale];
9929 UIDevice *device([UIDevice currentDevice]);
9930 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9933 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9934 if (idiom == UIUserInterfaceIdiomPhone)
9936 else if (idiom == UIUserInterfaceIdiomPad)
9939 NSLog(@"unknown UIUserInterfaceIdiom!");
9942 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9944 HostConfig_ = [[[NSObject alloc] init] autorelease];
9945 @synchronized (HostConfig_) {
9946 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9947 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9948 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9949 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9950 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9953 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9955 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9957 MobilizedFiles_ = [NSMutableSet setWithObjects:
9958 @"Library/Preferences/com.apple.Accessibility.plist",
9959 @"Library/Preferences/com.apple.preferences.sounds.plist",
9962 /* Library Hacks {{{ */
9963 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9965 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9967 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9968 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9969 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9970 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9973 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9974 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9975 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9976 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9979 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9980 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9981 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9982 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9983 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9986 $NSURLConnection = objc_getClass("NSURLConnection");
9987 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9988 if (NSURLConnection$init$ != NULL) {
9989 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9990 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9993 /* Set Locale {{{ */
9994 Locale_ = CFLocaleCopyCurrent();
9995 Languages_ = [NSLocale preferredLanguages];
9997 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9998 //NSLog(@"%@", [Languages_ description]);
10001 if (Locale_ != NULL)
10002 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10003 else if (Languages_ != nil && [Languages_ count] != 0)
10004 lang = [[Languages_ objectAtIndex:0] UTF8String];
10006 // XXX: consider just setting to C and then falling through?
10009 if (lang != NULL) {
10010 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10011 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10014 NSLog(@"Setting Language: %s", lang);
10016 if (lang != NULL) {
10017 setenv("LANG", lang, true);
10018 std::setlocale(LC_ALL, lang);
10022 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10024 /* Parse Arguments {{{ */
10025 bool substrate(false);
10031 for (int argi(1); argi != argc; ++argi)
10032 if (strcmp(argv[argi], "--") == 0) {
10034 argv[argi] = argv[0];
10040 for (int argi(1); argi != arge; ++argi)
10041 if (strcmp(args[argi], "--substrate") == 0)
10044 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10048 App_ = [[NSBundle mainBundle] bundlePath];
10054 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10055 alloc_ = alloc->method_imp;
10056 alloc->method_imp = (IMP) &Alloc_;*/
10058 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10059 dealloc_ = dealloc->method_imp;
10060 dealloc->method_imp = (IMP) &Dealloc_;*/
10062 /* System Information {{{ */
10066 size = sizeof(maxproc);
10067 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10068 perror("sysctlbyname(\"kern.maxproc\", ?)");
10069 else if (maxproc < 64) {
10071 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10072 perror("sysctlbyname(\"kern.maxproc\", #)");
10075 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10076 char *osversion = new char[size];
10077 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10078 perror("sysctlbyname(\"kern.osversion\", ?)");
10080 System_ = [NSString stringWithUTF8String:osversion];
10082 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10083 char *machine = new char[size];
10084 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10085 perror("sysctlbyname(\"hw.machine\", ?)");
10087 Machine_ = machine;
10089 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10090 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10091 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10093 UniqueID_ = [device uniqueIdentifier];
10095 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10096 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10097 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10099 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10100 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10101 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10103 if (mcc != NULL && mnc != NULL)
10104 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10111 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10112 Build_ = [system objectForKey:@"ProductBuildVersion"];
10113 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10114 Product_ = [info objectForKey:@"SafariProductVersion"];
10115 Safari_ = [info objectForKey:@"CFBundleVersion"];
10118 /* Load Database {{{ */
10120 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10122 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10124 if (Metadata_ == NULL)
10125 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10127 Settings_ = [Metadata_ objectForKey:@"Settings"];
10129 Packages_ = [Metadata_ objectForKey:@"Packages"];
10131 Values_ = [Metadata_ objectForKey:@"Values"];
10132 Sections_ = [Metadata_ objectForKey:@"Sections"];
10133 Sources_ = [Metadata_ objectForKey:@"Sources"];
10135 Token_ = [Metadata_ objectForKey:@"Token"];
10137 Version_ = [Metadata_ objectForKey:@"Version"];
10139 @synchronized (HostConfig_) {
10140 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10144 if (Settings_ != nil)
10145 Role_ = [Settings_ objectForKey:@"Role"];
10147 if (Values_ == nil) {
10148 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10149 [Metadata_ setObject:Values_ forKey:@"Values"];
10152 if (Sections_ == nil) {
10153 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10154 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10157 if (Sources_ == nil) {
10158 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10159 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10162 if (Version_ == nil) {
10163 Version_ = [NSNumber numberWithUnsignedInt:0];
10164 [Metadata_ setObject:Version_ forKey:@"Version"];
10167 @synchronized (HostConfig_) {
10168 if (CydiaSource_ == nil) {
10169 CydiaSource_ = @"apt.saurik.com";
10170 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10174 if ([Version_ unsignedIntValue] == 0) {
10175 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10176 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10177 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10178 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10180 Version_ = [NSNumber numberWithUnsignedInt:1];
10181 [Metadata_ setObject:Version_ forKey:@"Version"];
10190 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10193 if (Packages_ != nil) {
10195 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10199 [Metadata_ removeObjectForKey:@"Packages"];
10205 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10207 #define MobileSubstrate_(name) \
10208 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10209 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10210 if (handle == NULL) \
10211 NSLog(@"%s", dlerror()); \
10214 MobileSubstrate_(Activator)
10215 MobileSubstrate_(libstatusbar)
10216 MobileSubstrate_(SimulatedKeyEvents)
10217 MobileSubstrate_(WinterBoard)
10219 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10220 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10222 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10224 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10225 unlink("/tmp/.cydia.fw");
10227 } else if (access("/User", F_OK) != 0 || version < 4) {
10230 system("/usr/libexec/cydia/firmware.sh");
10234 _assert([[NSFileManager defaultManager]
10235 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10236 withIntermediateDirectories:YES
10241 if (access("/tmp/cydia.chk", F_OK) == 0) {
10242 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10243 _assert(errno == ENOENT);
10244 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10245 _assert(errno == ENOENT);
10248 /* APT Initialization {{{ */
10249 _assert(pkgInitConfig(*_config));
10250 _assert(pkgInitSystem(*_config, _system));
10253 _config->Set("APT::Acquire::Translation", lang);
10255 // XXX: this timeout might be important :(
10256 //_config->Set("Acquire::http::Timeout", 15);
10258 _config->Set("Acquire::http::MaxParallel", 3);
10260 /* Color Choices {{{ */
10261 space_ = CGColorSpaceCreateDeviceRGB();
10263 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10264 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10265 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10266 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10267 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10268 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10269 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10270 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10271 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10273 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10274 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10276 /* UIKit Configuration {{{ */
10277 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10278 if ($GSFontSetUseLegacyFontMetrics != NULL)
10279 $GSFontSetUseLegacyFontMetrics(YES);
10281 // XXX: I have a feeling this was important
10282 //UIKeyboardDisableAutomaticAppearance();
10285 Colon_ = UCLocalize("COLON_DELIMITED");
10286 Elision_ = UCLocalize("ELISION");
10287 Error_ = UCLocalize("ERROR");
10288 Warning_ = UCLocalize("WARNING");
10291 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10293 CGColorSpaceRelease(space_);
10294 CFRelease(Locale_);