1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <QuartzCore/CALayer.h>
71 #include <WebCore/WebCoreThread.h>
78 #include <ext/stdio_filebuf.h>
82 #include <apt-pkg/acquire.h>
83 #include <apt-pkg/acquire-item.h>
84 #include <apt-pkg/algorithms.h>
85 #include <apt-pkg/cachefile.h>
86 #include <apt-pkg/clean.h>
87 #include <apt-pkg/configuration.h>
88 #include <apt-pkg/debindexfile.h>
89 #include <apt-pkg/debmetaindex.h>
90 #include <apt-pkg/error.h>
91 #include <apt-pkg/init.h>
92 #include <apt-pkg/mmap.h>
93 #include <apt-pkg/pkgrecords.h>
94 #include <apt-pkg/sha1.h>
95 #include <apt-pkg/sourcelist.h>
96 #include <apt-pkg/sptr.h>
97 #include <apt-pkg/strutl.h>
98 #include <apt-pkg/tagfile.h>
100 #include <apr-1/apr_pools.h>
102 #include <sys/types.h>
103 #include <sys/stat.h>
104 #include <sys/sysctl.h>
105 #include <sys/param.h>
106 #include <sys/mount.h>
107 #include <sys/reboot.h>
114 #include <mach-o/nlist.h>
123 #include <Cytore.hpp>
126 #include <CydiaSubstrate/CydiaSubstrate.h>
127 #include "Menes/Menes.h"
129 #include "CyteKit/IndirectDelegate.h"
130 #include "CyteKit/PerlCompatibleRegEx.hpp"
131 #include "CyteKit/TableViewCell.h"
132 #include "CyteKit/WebScriptObject-Cyte.h"
133 #include "CyteKit/WebViewController.h"
134 #include "CyteKit/WebViewTableViewCell.h"
135 #include "CyteKit/stringWithUTF8Bytes.h"
137 #include "Cydia/MIMEAddress.h"
138 #include "Cydia/LoadingViewController.h"
139 #include "Cydia/ProgressEvent.h"
141 #include "SDURLCache/SDURLCache.h"
148 #define _timestamp ({ \
150 gettimeofday(&tv, NULL); \
151 tv.tv_sec * 1000000 + tv.tv_usec; \
154 typedef std::vector<class ProfileTime *> TimeList;
164 ProfileTime(const char *name) :
168 times_.push_back(this);
171 void AddTime(uint64_t time) {
178 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
190 ProfileTimer(ProfileTime &time) :
197 time_.AddTime(_timestamp - start_);
202 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
204 std::cerr << "========" << std::endl;
207 #define _profile(name) { \
208 static ProfileTime name(#name); \
209 ProfileTimer _ ## name(name);
214 extern NSString *Cydia_;
216 #define lprintf(args...) fprintf(stderr, args)
219 #define TraceLogging (1 && !ForRelease)
220 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
221 #define ProfileTimes (0 && !ForRelease)
222 #define ForSaurik (0 && !ForRelease)
223 #define LogBrowser (0 && !ForRelease)
224 #define TrackResize (0 && !ForRelease)
225 #define ManualRefresh (1 && !ForRelease)
226 #define ShowInternals (0 && !ForRelease)
227 #define AlwaysReload (0 && !ForRelease)
228 #define TryIndexedCollation (0 && !ForRelease)
232 #define _trace(args...)
237 #define _profile(name) {
240 #define PrintTimes() do {} while (false)
243 // Hash Functions/Structures {{{
244 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
252 static bool ShowPromoted_;
254 static NSString *Colon_;
256 static NSString *Error_;
257 static NSString *Warning_;
259 static bool AprilFools_;
261 static bool IsReachable(const char *name) {
262 SCNetworkReachabilityFlags flags; {
263 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
264 SCNetworkReachabilityGetFlags(reachability, &flags);
265 CFRelease(reachability);
268 // XXX: this elaborate mess is what Apple is using to determine this? :(
269 // XXX: do we care if the user has to intervene? maybe that's ok?
271 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
272 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
273 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
274 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
275 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
276 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
281 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
283 static _finline NSString *CydiaURL(NSString *path) {
285 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
286 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
287 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
288 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
289 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
291 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
294 static void ReapZombie(pid_t pid) {
297 if (waitpid(pid, &status, 0) == -1)
303 static _finline void UpdateExternalStatus(uint64_t newStatus) {
305 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
306 notify_set_state(notify_token, newStatus);
307 notify_cancel(notify_token);
309 notify_post("com.saurik.Cydia.status");
312 static CGFloat CYStatusBarHeight() {
313 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
314 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
317 /* NSForcedOrderingSearch doesn't work on the iPhone */
318 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
319 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
320 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
322 /* Insertion Sort {{{ */
324 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
325 const char *ptr = (const char *)list;
327 CFIndex half = count / 2;
328 const char *probe = ptr + elementSize * half;
329 CFComparisonResult cr = comparator(element, probe, context);
330 if (0 == cr) return (probe - (const char *)list) / elementSize;
331 ptr = (cr < 0) ? ptr : probe + elementSize;
332 count = (cr < 0) ? half : (half + (count & 1) - 1);
334 return (ptr - (const char *)list) / elementSize;
337 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
338 const char *ptr = (const char *)list;
340 CFIndex half = count / 2;
341 const char *probe = ptr + elementSize * half;
342 CFComparisonResult cr = comparator(element, probe, context);
343 if (0 == cr) return (probe - (const char *)list) / elementSize;
344 ptr = (cr < 0) ? ptr : probe + elementSize;
345 count = (cr < 0) ? half : (half + (count & 1) - 1);
347 return (ptr - (const char *)list) / elementSize;
350 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
351 if (range.length == 0)
353 const void **values(new const void *[range.length]);
354 CFArrayGetValues(array, range, values);
356 #if HistogramInsertionSort > 0
357 uint32_t total(0), *offsets(new uint32_t[range.length]);
360 for (CFIndex index(1); index != range.length; ++index) {
361 const void *value(values[index]);
362 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
363 CFIndex correct(index);
364 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
365 #if HistogramInsertionSort > 1
366 NSLog(@"%@ < %@", value, values[correct - 1]);
371 if (correct != index) {
372 size_t offset(index - correct);
373 #if HistogramInsertionSort
377 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
379 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
380 values[correct] = value;
384 CFArrayReplaceValues(array, range, values, range.length);
387 #if HistogramInsertionSort > 0
388 for (CFIndex index(0); index != range.length; ++index)
389 if (offsets[index] != 0)
390 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
391 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
398 /* Apple Bug Fixes {{{ */
399 @implementation UIWebDocumentView (Cydia)
401 - (void) _setScrollerOffset:(CGPoint)offset {
402 UIScroller *scroller([self _scroller]);
404 CGSize size([scroller contentSize]);
405 CGSize bounds([scroller bounds].size);
408 max.x = size.width - bounds.width;
409 max.y = size.height - bounds.height;
417 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
418 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
420 [scroller setOffset:offset];
426 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
427 size_t length([self length] - state->state);
430 else if (length > count)
432 for (size_t i(0); i != length; ++i)
433 objects[i] = [self item:state->state++];
434 state->itemsPtr = objects;
435 state->mutationsPtr = (unsigned long *) self;
439 /* Cydia NSString Additions {{{ */
440 @interface NSString (Cydia)
441 - (NSComparisonResult) compareByPath:(NSString *)other;
442 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
445 @implementation NSString (Cydia)
447 - (NSComparisonResult) compareByPath:(NSString *)other {
448 NSString *prefix = [self commonPrefixWithString:other options:0];
449 size_t length = [prefix length];
451 NSRange lrange = NSMakeRange(length, [self length] - length);
452 NSRange rrange = NSMakeRange(length, [other length] - length);
454 lrange = [self rangeOfString:@"/" options:0 range:lrange];
455 rrange = [other rangeOfString:@"/" options:0 range:rrange];
457 NSComparisonResult value;
459 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
460 value = NSOrderedSame;
461 else if (lrange.location == NSNotFound)
462 value = NSOrderedAscending;
463 else if (rrange.location == NSNotFound)
464 value = NSOrderedDescending;
466 value = NSOrderedSame;
468 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
469 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
470 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
471 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
473 NSComparisonResult result = [lpath compare:rpath];
474 return result == NSOrderedSame ? value : result;
477 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
478 return [(id)CFURLCreateStringByAddingPercentEscapes(
483 kCFStringEncodingUTF8
490 /* C++ NSString Wrapper Cache {{{ */
491 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
492 return size == 0 ? NULL :
493 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
494 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
497 static _finline CFStringRef CYStringCreate(const char *data) {
498 return CYStringCreate(data, strlen(data));
507 _finline void clear_() {
508 if (cache_ != NULL) {
515 _finline bool empty() const {
519 _finline size_t size() const {
523 _finline char *data() const {
527 _finline void clear() {
532 _finline CYString() :
539 _finline ~CYString() {
543 void operator =(const CYString &rhs) {
547 if (rhs.cache_ == nil)
550 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
553 void copy(apr_pool_t *pool) {
554 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
555 memcpy(temp, data_, size_);
560 void set(apr_pool_t *pool, const char *data, size_t size) {
566 data_ = const_cast<char *>(data);
574 _finline void set(apr_pool_t *pool, const char *data) {
575 set(pool, data, data == NULL ? 0 : strlen(data));
578 _finline void set(apr_pool_t *pool, const std::string &rhs) {
579 set(pool, rhs.data(), rhs.size());
582 bool operator ==(const CYString &rhs) const {
583 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
586 _finline operator CFStringRef() {
588 cache_ = CYStringCreate(data_, size_);
592 _finline operator id() {
593 return (NSString *) static_cast<CFStringRef>(*this);
596 _finline operator const char *() {
597 return reinterpret_cast<const char *>(data_);
601 /* C++ NSString Algorithm Adapters {{{ */
603 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
606 struct NSStringMapHash :
607 std::unary_function<NSString *, size_t>
609 _finline size_t operator ()(NSString *value) const {
610 return CFStringHashNSString((CFStringRef) value);
614 struct NSStringMapLess :
615 std::binary_function<NSString *, NSString *, bool>
617 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
618 return [lhs compare:rhs] == NSOrderedAscending;
622 struct NSStringMapEqual :
623 std::binary_function<NSString *, NSString *, bool>
625 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
626 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
627 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
628 //[lhs isEqualToString:rhs];
633 /* CoreGraphics Primitives {{{ */
638 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
639 CGFloat color[] = {red, green, blue, alpha};
640 return CGColorCreate(space, color);
649 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
650 color_(Create_(space, red, green, blue, alpha))
652 Set(space, red, green, blue, alpha);
657 CGColorRelease(color_);
664 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
666 color_ = Create_(space, red, green, blue, alpha);
669 operator CGColorRef() {
675 /* Random Global Variables {{{ */
676 static int PulseInterval_ = 500000;
678 static const NSString *UI_;
681 static bool RestartSubstrate_;
682 static NSArray *Finishes_;
684 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
685 #define NotifyConfig_ "/etc/notify.conf"
687 static bool Queuing_;
689 static CYColor Blue_;
690 static CYColor Blueish_;
691 static CYColor Black_;
693 static CYColor White_;
694 static CYColor Gray_;
695 static CYColor Green_;
696 static CYColor Purple_;
697 static CYColor Purplish_;
699 static UIColor *InstallingColor_;
700 static UIColor *RemovingColor_;
702 static NSString *App_;
704 static BOOL Advanced_;
705 static BOOL Ignored_;
707 static _H<UIFont> Font12_;
708 static _H<UIFont> Font12Bold_;
709 static _H<UIFont> Font14_;
710 static _H<UIFont> Font18Bold_;
711 static _H<UIFont> Font22Bold_;
713 static const char *Machine_ = NULL;
714 static _H<NSString> System_;
715 static NSString *SerialNumber_ = nil;
716 static NSString *ChipID_ = nil;
717 static NSString *BBSNum_ = nil;
718 static _H<NSString> Token_;
719 static NSString *UniqueID_ = nil;
720 static _H<NSString> UserAgent_;
721 static _H<NSString> Product_;
722 static _H<NSString> Safari_;
724 static CFLocaleRef Locale_;
725 static NSArray *Languages_;
726 static CGColorSpaceRef space_;
728 static NSDictionary *SectionMap_;
729 static NSMutableDictionary *Metadata_;
730 static _transient NSMutableDictionary *Settings_;
731 static _transient NSString *Role_;
732 static _transient NSMutableDictionary *Packages_;
733 static _transient NSMutableDictionary *Values_;
734 static _transient NSMutableDictionary *Sections_;
735 _H<NSMutableDictionary> Sources_;
736 static _transient NSNumber *Version_;
741 static CGFloat ScreenScale_;
742 static NSString *Idiom_;
743 static _H<NSString> Firmware_;
744 static NSString *Major_;
746 static _H<NSMutableDictionary> SessionData_;
747 static _H<NSObject> HostConfig_;
748 static _H<NSMutableSet> BridgedHosts_;
749 static _H<NSMutableSet> TokenHosts_;
750 static _H<NSMutableSet> InsecureHosts_;
751 static _H<NSMutableSet> PipelinedHosts_;
752 static _H<NSMutableSet> CachedURLs_;
754 static NSString *kCydiaProgressEventTypeError = @"Error";
755 static NSString *kCydiaProgressEventTypeInformation = @"Information";
756 static NSString *kCydiaProgressEventTypeStatus = @"Status";
757 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
760 /* Display Helpers {{{ */
761 inline float Interpolate(float begin, float end, float fraction) {
762 return (end - begin) * fraction + begin;
765 static _finline const char *StripVersion_(const char *version) {
766 const char *colon(strchr(version, ':'));
767 return colon == NULL ? version : colon + 1;
770 NSString *LocalizeSection(NSString *section) {
771 static Pcre title_r("^(.*?) \\((.*)\\)$");
772 if (title_r(section)) {
773 NSString *parent(title_r[1]);
774 NSString *child(title_r[2]);
776 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
777 LocalizeSection(parent),
778 LocalizeSection(child)
782 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
785 NSString *Simplify(NSString *title) {
786 const char *data = [title UTF8String];
787 size_t size = [title length];
789 static Pcre square_r("^\\[(.*)\\]$");
790 if (square_r(data, size))
791 return Simplify(square_r[1]);
793 static Pcre paren_r("^\\((.*)\\)$");
794 if (paren_r(data, size))
795 return Simplify(paren_r[1]);
797 static Pcre title_r("^(.*?) \\((.*)\\)$");
798 if (title_r(data, size))
799 return Simplify(title_r[1]);
805 NSString *GetLastUpdate() {
806 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
809 return UCLocalize("NEVER_OR_UNKNOWN");
811 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
812 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
814 CFRelease(formatter);
816 return [(NSString *) formatted autorelease];
819 bool isSectionVisible(NSString *section) {
820 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
821 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
822 return hidden == nil || ![hidden boolValue];
825 static NSObject *CYIOGetValue(const char *path, NSString *property) {
826 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
827 if (entry == MACH_PORT_NULL)
830 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
831 IOObjectRelease(entry);
835 return [(id) value autorelease];
838 static NSString *CYHex(NSData *data, bool reverse = false) {
842 size_t length([data length]);
843 uint8_t bytes[length];
844 [data getBytes:bytes];
846 char string[length * 2 + 1];
847 for (size_t i(0); i != length; ++i)
848 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
850 return [NSString stringWithUTF8String:string];
855 /* Delegate Prototypes {{{ */
858 @class CydiaProgressEvent;
860 @protocol DatabaseDelegate
861 - (void) repairWithSelector:(SEL)selector;
862 - (void) setConfigurationData:(NSString *)data;
863 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
866 @class CYPackageController;
868 @protocol CydiaDelegate
869 - (void) returnToCydia;
871 - (void) retainNetworkActivityIndicator;
872 - (void) releaseNetworkActivityIndicator;
873 - (void) clearPackage:(Package *)package;
874 - (void) installPackage:(Package *)package;
875 - (void) installPackages:(NSArray *)packages;
876 - (void) removePackage:(Package *)package;
877 - (void) beginUpdate;
879 - (void) distUpgrade;
882 - (void) _saveConfig;
884 - (void) addSource:(NSDictionary *)source;
885 - (void) addTrivialSource:(NSString *)href;
886 - (void) showSettings;
887 - (UIProgressHUD *) addProgressHUD;
888 - (void) removeProgressHUD:(UIProgressHUD *)hud;
889 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
890 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
894 /* Status Delegation {{{ */
896 public pkgAcquireStatus
899 _transient NSObject<ProgressDelegate> *delegate_;
909 void setDelegate(NSObject<ProgressDelegate> *delegate) {
910 delegate_ = delegate;
913 NSObject<ProgressDelegate> *getDelegate() const {
917 virtual bool MediaChange(std::string media, std::string drive) {
921 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
925 virtual void Fetch(pkgAcquire::ItemDesc &item) {
926 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
927 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
928 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
931 virtual void Done(pkgAcquire::ItemDesc &item) {
932 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
933 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
934 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
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 {
1310 Database *database_;
1313 CYString depiction_;
1314 CYString description_;
1320 CYString distribution_;
1326 _H<NSString> authority_;
1328 CYString defaultIcon_;
1330 _H<NSDictionary> record_;
1334 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1336 - (NSComparisonResult) compareByName:(Source *)source;
1338 - (NSString *) depictionForPackage:(NSString *)package;
1339 - (NSString *) supportForPackage:(NSString *)package;
1341 - (NSDictionary *) record;
1344 - (NSString *) rooturi;
1345 - (NSString *) distribution;
1346 - (NSString *) type;
1349 - (NSString *) host;
1351 - (NSString *) name;
1352 - (NSString *) shortDescription;
1353 - (NSString *) label;
1354 - (NSString *) origin;
1355 - (NSString *) version;
1357 - (NSString *) defaultIcon;
1358 - (NSURL *) iconURL;
1362 @implementation Source
1366 distribution_.clear();
1371 description_.clear();
1377 defaultIcon_.clear();
1384 + (NSString *) webScriptNameForSelector:(SEL)selector {
1386 else if (selector == @selector(addSection:))
1387 return @"addSection";
1388 else if (selector == @selector(getField:))
1390 else if (selector == @selector(removeSection:))
1391 return @"removeSection";
1392 else if (selector == @selector(remove))
1398 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1399 return [self webScriptNameForSelector:selector] == nil;
1402 + (NSArray *) _attributeKeys {
1403 return [NSArray arrayWithObjects:
1414 @"shortDescription",
1421 - (NSArray *) attributeKeys {
1422 return [[self class] _attributeKeys];
1425 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1426 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1429 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1432 trusted_ = index->IsTrusted();
1434 uri_.set(pool, index->GetURI());
1435 distribution_.set(pool, index->GetDist());
1436 type_.set(pool, index->GetType());
1438 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1439 if (dindex != NULL) {
1440 base_.set(pool, dindex->MetaIndexURI(""));
1443 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1446 pkgTagFile tags(&fd);
1448 pkgTagSection section;
1455 {"default-icon", &defaultIcon_},
1456 {"depiction", &depiction_},
1457 {"description", &description_},
1459 {"origin", &origin_},
1460 {"support", &support_},
1461 {"version", &version_},
1464 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1465 const char *start, *end;
1467 if (section.Find(names[i].name_, start, end)) {
1468 CYString &value(*names[i].value_);
1469 value.set(pool, start, end - start);
1475 record_ = [Sources_ objectForKey:[self key]];
1477 NSURL *url([NSURL URLWithString:uri_]);
1481 host_ = [host_ lowercaseString];
1486 authority_ = [url path];
1489 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1490 if ((self = [super init]) != nil) {
1491 era_ = [database era];
1492 database_ = database;
1495 [self setMetaIndex:index inPool:pool];
1499 - (NSString *) getField:(NSString *)name {
1500 @synchronized (database_) {
1501 if ([database_ era] != era_ || index_ == NULL)
1504 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1509 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1514 pkgTagFile tags(&fd);
1516 pkgTagSection section;
1519 const char *start, *end;
1520 if (!section.Find([name UTF8String], start, end))
1521 return (NSString *) [NSNull null];
1523 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1526 - (NSComparisonResult) compareByName:(Source *)source {
1527 NSString *lhs = [self name];
1528 NSString *rhs = [source name];
1530 if ([lhs length] != 0 && [rhs length] != 0) {
1531 unichar lhc = [lhs characterAtIndex:0];
1532 unichar rhc = [rhs characterAtIndex:0];
1534 if (isalpha(lhc) && !isalpha(rhc))
1535 return NSOrderedAscending;
1536 else if (!isalpha(lhc) && isalpha(rhc))
1537 return NSOrderedDescending;
1540 return [lhs compare:rhs options:LaxCompareOptions_];
1543 - (NSString *) depictionForPackage:(NSString *)package {
1544 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1547 - (NSString *) supportForPackage:(NSString *)package {
1548 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1551 - (NSArray *) sections {
1552 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1555 - (void) _addSection:(NSString *)section {
1558 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1559 if (![sections containsObject:section]) {
1560 [sections addObject:section];
1564 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1569 - (bool) addSection:(NSString *)section {
1573 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1577 - (void) _removeSection:(NSString *)section {
1581 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1582 if ([sections containsObject:section]) {
1583 [sections removeObject:section];
1588 - (bool) removeSection:(NSString *)section {
1592 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1597 [Sources_ removeObjectForKey:[self key]];
1602 bool value(record_ != nil);
1603 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1607 - (NSDictionary *) record {
1615 - (NSString *) rooturi {
1619 - (NSString *) distribution {
1620 return distribution_;
1623 - (NSString *) type {
1627 - (NSString *) baseuri {
1628 return base_.empty() ? nil : (id) base_;
1631 - (NSString *) iconuri {
1632 if (NSString *base = [self baseuri])
1633 return [base stringByAppendingString:@"CydiaIcon.png"];
1638 - (NSURL *) iconURL {
1639 if (NSString *uri = [self iconuri])
1640 return [NSURL URLWithString:uri];
1644 - (NSString *) key {
1645 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1648 - (NSString *) host {
1652 - (NSString *) name {
1653 return origin_.empty() ? (id) authority_ : origin_;
1656 - (NSString *) shortDescription {
1657 return description_;
1660 - (NSString *) label {
1661 return label_.empty() ? (id) authority_ : label_;
1664 - (NSString *) origin {
1668 - (NSString *) version {
1672 - (NSString *) defaultIcon {
1673 return defaultIcon_;
1678 /* CydiaOperation Class {{{ */
1679 @interface CydiaOperation : NSObject {
1680 _H<NSString> operator_;
1681 _H<NSString> value_;
1684 - (NSString *) operator;
1685 - (NSString *) value;
1689 @implementation CydiaOperation
1691 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1692 if ((self = [super init]) != nil) {
1693 operator_ = [NSString stringWithUTF8String:_operator];
1694 value_ = [NSString stringWithUTF8String:value];
1698 + (NSArray *) _attributeKeys {
1699 return [NSArray arrayWithObjects:
1705 - (NSArray *) attributeKeys {
1706 return [[self class] _attributeKeys];
1709 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1710 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1713 - (NSString *) operator {
1717 - (NSString *) value {
1723 /* CydiaClause Class {{{ */
1724 @interface CydiaClause : NSObject {
1725 _H<NSString> package_;
1726 _H<CydiaOperation> version_;
1729 - (NSString *) package;
1730 - (CydiaOperation *) version;
1734 @implementation CydiaClause
1736 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1737 if ((self = [super init]) != nil) {
1738 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1740 if (const char *version = dep.TargetVer())
1741 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1743 version_ = (id) [NSNull null];
1747 + (NSArray *) _attributeKeys {
1748 return [NSArray arrayWithObjects:
1754 - (NSArray *) attributeKeys {
1755 return [[self class] _attributeKeys];
1758 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1759 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1762 - (NSString *) package {
1766 - (CydiaOperation *) version {
1772 /* CydiaRelation Class {{{ */
1773 @interface CydiaRelation : NSObject {
1774 _H<NSString> relationship_;
1775 _H<NSMutableArray> clauses_;
1778 - (NSString *) relationship;
1779 - (NSArray *) clauses;
1783 @implementation CydiaRelation
1785 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1786 if ((self = [super init]) != nil) {
1787 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1788 clauses_ = [NSMutableArray arrayWithCapacity:8];
1790 pkgCache::DepIterator start;
1791 pkgCache::DepIterator end;
1792 dep.GlobOr(start, end); // ++dep
1795 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1797 // yes, seriously. (wtf?)
1805 + (NSArray *) _attributeKeys {
1806 return [NSArray arrayWithObjects:
1812 - (NSArray *) attributeKeys {
1813 return [[self class] _attributeKeys];
1816 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1817 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1820 - (NSString *) relationship {
1821 return relationship_;
1824 - (NSArray *) clauses {
1828 - (void) addClause:(CydiaClause *)clause {
1829 [clauses_ addObject:clause];
1834 /* Package Class {{{ */
1835 struct ParsedPackage {
1839 CYString architecture_;
1842 CYString depiction_;
1852 @interface Package : NSObject {
1855 uint32_t essential_ : 1;
1856 uint32_t obsolete_ : 1;
1857 uint32_t ignored_ : 1;
1858 uint32_t pooled_ : 1;
1864 _transient Database *database_;
1866 pkgCache::VerIterator version_;
1867 pkgCache::PkgIterator iterator_;
1868 pkgCache::VerFileIterator file_;
1874 CYString installed_;
1876 const char *section_;
1877 _transient NSString *section$_;
1881 PackageValue *metadata_;
1882 ParsedPackage *parsed_;
1884 _H<NSMutableArray> tags_;
1887 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1888 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1890 - (pkgCache::PkgIterator) iterator;
1893 - (NSString *) section;
1894 - (NSString *) simpleSection;
1896 - (NSString *) longSection;
1897 - (NSString *) shortSection;
1901 - (MIMEAddress *) maintainer;
1903 - (NSString *) longDescription;
1904 - (NSString *) shortDescription;
1907 - (PackageValue *) metadata;
1910 - (bool) subscribed;
1911 - (bool) setSubscribed:(bool)subscribed;
1915 - (NSString *) latest;
1916 - (NSString *) installed;
1917 - (BOOL) uninstalled;
1920 - (BOOL) upgradableAndEssential:(BOOL)essential;
1923 - (BOOL) unfiltered;
1927 - (BOOL) halfConfigured;
1928 - (BOOL) halfInstalled;
1930 - (NSString *) mode;
1933 - (NSString *) name;
1935 - (NSString *) homepage;
1936 - (NSString *) depiction;
1937 - (MIMEAddress *) author;
1939 - (NSString *) support;
1941 - (NSArray *) files;
1942 - (NSArray *) warnings;
1943 - (NSArray *) applications;
1945 - (Source *) source;
1948 - (BOOL) matches:(NSArray *)query;
1950 - (bool) hasSupportingRole;
1951 - (BOOL) hasTag:(NSString *)tag;
1952 - (NSString *) primaryPurpose;
1953 - (NSArray *) purposes;
1954 - (bool) isCommercial;
1956 - (void) setIndex:(size_t)index;
1958 - (CYString &) cyname;
1960 - (uint32_t) compareBySection:(NSArray *)sections;
1965 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1966 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1967 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1968 - (bool) isVisibleInSection:(NSString *)section;
1969 - (bool) isVisibleInSource:(Source *)source;
1973 uint32_t PackageChangesRadix(Package *self, void *) {
1978 uint32_t timestamp : 30;
1979 uint32_t ignored : 1;
1980 uint32_t upgradable : 1;
1984 bool upgradable([self upgradableAndEssential:YES]);
1985 value.bits.upgradable = upgradable ? 1 : 0;
1988 value.bits.timestamp = 0;
1989 value.bits.ignored = [self ignored] ? 0 : 1;
1990 value.bits.upgradable = 1;
1992 value.bits.timestamp = [self seen] >> 2;
1993 value.bits.ignored = 0;
1994 value.bits.upgradable = 0;
1997 return _not(uint32_t) - value.key;
2000 uint32_t PackagePrefixRadix(Package *self, void *context) {
2001 size_t offset(reinterpret_cast<size_t>(context));
2002 CYString &name([self cyname]);
2004 size_t size(name.size());
2007 char *text(name.data());
2010 if (!isdigit(text[0]))
2014 while (size != digits && isdigit(text[digits]))
2022 if (offset == 0 && zeros != 0) {
2023 memset(data, '0', zeros);
2024 memcpy(data + zeros, text, 4 - zeros);
2026 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2027 if (size <= offset - zeros)
2030 text += offset - zeros;
2031 size -= offset - zeros;
2034 memcpy(data, text, 4);
2036 memcpy(data, text, size);
2037 memset(data + size, 0, 4 - size);
2040 for (size_t i(0); i != 4; ++i)
2041 if (isalpha(data[i]))
2049 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2051 /* XXX: ntohl may be more honest */
2052 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2055 CYString &(*PackageName)(Package *self, SEL sel);
2057 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2058 _profile(PackageNameCompare)
2059 CYString &lhi(PackageName(lhs, @selector(cyname)));
2060 CYString &rhi(PackageName(rhs, @selector(cyname)));
2061 CFStringRef lhn(lhi), rhn(rhi);
2064 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2065 else if (rhn == NULL)
2066 return NSOrderedDescending;
2068 _profile(PackageNameCompare$NumbersLast)
2069 if (!lhi.empty() && !rhi.empty()) {
2070 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2071 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2072 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2073 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2074 return lha ? NSOrderedAscending : NSOrderedDescending;
2078 CFIndex length = CFStringGetLength(lhn);
2080 _profile(PackageNameCompare$Compare)
2081 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2086 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2087 return PackageNameCompare(*lhs, *rhs, context);
2090 struct PackageNameOrdering :
2091 std::binary_function<Package *, Package *, bool>
2093 _finline bool operator ()(Package *lhs, Package *rhs) const {
2094 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2098 @implementation Package
2100 - (NSString *) description {
2101 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2106 apr_pool_destroy(pool_);
2107 if (parsed_ != NULL)
2112 + (NSString *) webScriptNameForSelector:(SEL)selector {
2114 else if (selector == @selector(clear))
2116 else if (selector == @selector(getField:))
2118 else if (selector == @selector(hasTag:))
2120 else if (selector == @selector(install))
2122 else if (selector == @selector(remove))
2128 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2129 return [self webScriptNameForSelector:selector] == nil;
2132 + (NSArray *) _attributeKeys {
2133 return [NSArray arrayWithObjects:
2154 @"shortDescription",
2167 - (NSArray *) attributeKeys {
2168 return [[self class] _attributeKeys];
2171 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2172 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2175 - (NSArray *) relations {
2176 @synchronized (database_) {
2177 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2178 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2179 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2183 - (NSString *) architecture {
2185 @synchronized (database_) {
2186 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2189 - (NSString *) getField:(NSString *)name {
2190 @synchronized (database_) {
2191 if ([database_ era] != era_ || file_.end())
2194 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2196 const char *start, *end;
2197 if (!parser.Find([name UTF8String], start, end))
2198 return (NSString *) [NSNull null];
2200 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2204 if (parsed_ != NULL)
2206 @synchronized (database_) {
2207 if ([database_ era] != era_ || file_.end())
2210 ParsedPackage *parsed(new ParsedPackage);
2213 _profile(Package$parse)
2214 pkgRecords::Parser *parser;
2216 _profile(Package$parse$Lookup)
2217 parser = &[database_ records]->Lookup(file_);
2222 _profile(Package$parse$Find)
2227 {"architecture", &parsed->architecture_},
2228 {"icon", &parsed->icon_},
2229 {"depiction", &parsed->depiction_},
2230 {"homepage", &parsed->homepage_},
2231 {"website", &website},
2232 {"bugs", &parsed->bugs_},
2233 {"support", &parsed->support_},
2234 {"sponsor", &parsed->sponsor_},
2235 {"author", &parsed->author_},
2236 {"md5sum", &parsed->md5sum_},
2239 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2240 const char *start, *end;
2242 if (parser->Find(names[i].name_, start, end)) {
2243 CYString &value(*names[i].value_);
2244 _profile(Package$parse$Value)
2245 value.set(pool_, start, end - start);
2251 _profile(Package$parse$Tagline)
2252 const char *start, *end;
2253 if (parser->ShortDesc(start, end)) {
2254 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2257 while (stop != start && stop[-1] == '\r')
2259 parsed->tagline_.set(pool_, start, stop - start);
2263 _profile(Package$parse$Retain)
2264 if (parsed->homepage_.empty())
2265 parsed->homepage_ = website;
2266 if (parsed->homepage_ == parsed->depiction_)
2267 parsed->homepage_.clear();
2272 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2273 if ((self = [super init]) != nil) {
2274 _profile(Package$initWithVersion)
2276 apr_pool_create(&pool_, NULL);
2282 database_ = database;
2283 era_ = [database era];
2287 pkgCache::PkgIterator iterator(version.ParentPkg());
2288 iterator_ = iterator;
2290 _profile(Package$initWithVersion$Version)
2291 if (!version_.end())
2292 file_ = version_.FileList();
2294 pkgCache &cache([database_ cache]);
2295 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2299 _profile(Package$initWithVersion$Cache)
2300 name_.set(NULL, iterator.Display());
2302 latest_.set(NULL, StripVersion_(version_.VerStr()));
2304 pkgCache::VerIterator current(iterator.CurrentVer());
2306 installed_.set(NULL, StripVersion_(current.VerStr()));
2309 _profile(Package$initWithVersion$Tags)
2310 pkgCache::TagIterator tag(iterator.TagList());
2312 tags_ = [NSMutableArray arrayWithCapacity:8];
2314 const char *name(tag.Name());
2315 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2317 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2318 if (strcmp(name + 6, "enduser") == 0)
2320 else if (strcmp(name + 6, "hacker") == 0)
2322 else if (strcmp(name + 6, "developer") == 0)
2324 else if (strcmp(name + 6, "cydia") == 0)
2330 if (strncmp(name, "cydia::", 7) == 0) {
2331 if (strcmp(name + 7, "essential") == 0)
2333 else if (strcmp(name + 7, "obsolete") == 0)
2338 } while (!tag.end());
2342 _profile(Package$initWithVersion$Metadata)
2343 const char *mixed(iterator.Name());
2344 size_t size(strlen(mixed));
2345 char lower[size + 1];
2347 for (size_t i(0); i != size; ++i)
2348 lower[i] = mixed[i] | 0x20;
2351 PackageValue *metadata(PackageFind(lower, size));
2352 metadata_ = metadata;
2354 id_.set(NULL, metadata->name_, size);
2356 const char *latest(version_.VerStr());
2357 size_t length(strlen(latest));
2359 uint16_t vhash(hashlittle(latest, length));
2361 size_t capped(std::min<size_t>(8, length));
2362 latest = latest + length - capped;
2364 if (metadata->first_ == 0)
2365 metadata->first_ = now_;
2367 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2368 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2369 metadata->vhash_ = vhash;
2370 metadata->last_ = now_;
2371 } else if (metadata->last_ == 0)
2372 metadata->last_ = metadata->first_;
2375 _profile(Package$initWithVersion$Section)
2376 section_ = iterator.Section();
2379 _profile(Package$initWithVersion$Flags)
2380 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2381 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2386 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2387 pkgCache::VerIterator version;
2389 _profile(Package$packageWithIterator$GetCandidateVer)
2390 version = [database policy]->GetCandidateVer(iterator);
2398 _profile(Package$packageWithIterator$Allocate)
2399 package = [Package allocWithZone:zone];
2402 _profile(Package$packageWithIterator$Initialize)
2404 initWithVersion:version
2411 _profile(Package$packageWithIterator$Autorelease)
2412 package = [package autorelease];
2418 - (pkgCache::PkgIterator) iterator {
2422 - (NSString *) section {
2423 if (section$_ == nil) {
2424 if (section_ == NULL)
2427 _profile(Package$section$mappedSectionForPointer)
2428 section$_ = [database_ mappedSectionForPointer:section_];
2433 - (NSString *) simpleSection {
2434 if (NSString *section = [self section])
2435 return Simplify(section);
2440 - (NSString *) longSection {
2441 return LocalizeSection([self section]);
2444 - (NSString *) shortSection {
2445 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2448 - (NSString *) uri {
2451 pkgIndexFile *index;
2452 pkgCache::PkgFileIterator file(file_.File());
2453 if (![database_ list].FindIndex(file, index))
2455 return [NSString stringWithUTF8String:iterator_->Path];
2456 //return [NSString stringWithUTF8String:file.Site()];
2457 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2461 - (MIMEAddress *) maintainer {
2462 @synchronized (database_) {
2463 if ([database_ era] != era_ || file_.end())
2466 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2467 const std::string &maintainer(parser->Maintainer());
2468 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2471 - (NSString *) md5sum {
2472 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2476 @synchronized (database_) {
2477 if ([database_ era] != era_ || version_.end())
2480 return version_->InstalledSize;
2483 - (NSString *) longDescription {
2484 @synchronized (database_) {
2485 if ([database_ era] != era_ || file_.end())
2488 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2489 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2491 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2492 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2493 if ([lines count] < 2)
2496 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2497 for (size_t i(1), e([lines count]); i != e; ++i) {
2498 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2499 [trimmed addObject:trim];
2502 return [trimmed componentsJoinedByString:@"\n"];
2505 - (NSString *) shortDescription {
2506 if (parsed_ != NULL)
2507 return static_cast<NSString *>(parsed_->tagline_);
2509 @synchronized (database_) {
2510 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2512 const char *start, *end;
2513 if (!parser.ShortDesc(start, end))
2516 if (end - start > 200)
2520 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2523 while (end != start && end[-1] == '\r')
2527 return [(id) CYStringCreate(start, end - start) autorelease];
2531 _profile(Package$index)
2532 CFStringRef name((CFStringRef) [self name]);
2533 if (CFStringGetLength(name) == 0)
2535 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2536 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2538 return toupper(character);
2542 - (PackageValue *) metadata {
2547 PackageValue *metadata([self metadata]);
2548 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2551 - (bool) subscribed {
2552 return [self metadata]->subscribed_;
2555 - (bool) setSubscribed:(bool)subscribed {
2556 PackageValue *metadata([self metadata]);
2557 if (metadata->subscribed_ == subscribed)
2559 metadata->subscribed_ = subscribed;
2567 - (NSString *) latest {
2571 - (NSString *) installed {
2575 - (BOOL) uninstalled {
2576 return installed_.empty();
2580 return !version_.end();
2583 - (BOOL) upgradableAndEssential:(BOOL)essential {
2584 _profile(Package$upgradableAndEssential)
2585 pkgCache::VerIterator current(iterator_.CurrentVer());
2587 return essential && essential_;
2589 return !version_.end() && version_ != current;
2593 - (BOOL) essential {
2598 return [database_ cache][iterator_].InstBroken();
2601 - (BOOL) unfiltered {
2602 _profile(Package$unfiltered$obsolete)
2603 if (_unlikely(obsolete_))
2607 _profile(Package$unfiltered$hasSupportingRole)
2608 if (_unlikely(![self hasSupportingRole]))
2616 if (![self unfiltered])
2621 _profile(Package$visible$section)
2622 section = [self section];
2625 _profile(Package$visible$isSectionVisible)
2626 if (!isSectionVisible(section))
2634 unsigned char current(iterator_->CurrentState);
2635 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2638 - (BOOL) halfConfigured {
2639 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2642 - (BOOL) halfInstalled {
2643 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2647 @synchronized (database_) {
2648 if ([database_ era] != era_ || iterator_.end())
2651 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2652 return state.Mode != pkgDepCache::ModeKeep;
2655 - (NSString *) mode {
2656 @synchronized (database_) {
2657 if ([database_ era] != era_ || iterator_.end())
2660 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2662 switch (state.Mode) {
2663 case pkgDepCache::ModeDelete:
2664 if ((state.iFlags & pkgDepCache::Purge) != 0)
2668 case pkgDepCache::ModeKeep:
2669 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2670 return @"REINSTALL";
2671 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2675 case pkgDepCache::ModeInstall:
2676 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2677 return @"REINSTALL";
2678 else*/ switch (state.Status) {
2680 return @"DOWNGRADE";
2686 return @"NEW_INSTALL";
2697 - (NSString *) name {
2698 return name_.empty() ? id_ : name_;
2701 - (UIImage *) icon {
2702 NSString *section = [self simpleSection];
2705 if (parsed_ != NULL)
2706 if (NSString *href = parsed_->icon_)
2707 if ([href hasPrefix:@"file:///"])
2708 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2709 if (icon == nil) if (section != nil)
2710 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2711 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2712 if ([dicon hasPrefix:@"file:///"])
2713 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2715 icon = [UIImage applicationImageNamed:@"unknown.png"];
2719 - (NSString *) homepage {
2720 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2723 - (NSString *) depiction {
2724 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2727 - (MIMEAddress *) sponsor {
2728 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2731 - (MIMEAddress *) author {
2732 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2735 - (NSString *) support {
2736 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2739 - (NSArray *) files {
2740 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2741 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2744 fin.open([path UTF8String]);
2749 while (std::getline(fin, line))
2750 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2755 - (NSString *) state {
2756 @synchronized (database_) {
2757 if ([database_ era] != era_ || file_.end())
2760 switch (iterator_->CurrentState) {
2761 case pkgCache::State::NotInstalled:
2762 return @"NotInstalled";
2763 case pkgCache::State::UnPacked:
2765 case pkgCache::State::HalfConfigured:
2766 return @"HalfConfigured";
2767 case pkgCache::State::HalfInstalled:
2768 return @"HalfInstalled";
2769 case pkgCache::State::ConfigFiles:
2770 return @"ConfigFiles";
2771 case pkgCache::State::Installed:
2772 return @"Installed";
2773 case pkgCache::State::TriggersAwaited:
2774 return @"TriggersAwaited";
2775 case pkgCache::State::TriggersPending:
2776 return @"TriggersPending";
2779 return (NSString *) [NSNull null];
2782 - (NSString *) selection {
2783 @synchronized (database_) {
2784 if ([database_ era] != era_ || file_.end())
2787 switch (iterator_->SelectedState) {
2788 case pkgCache::State::Unknown:
2790 case pkgCache::State::Install:
2792 case pkgCache::State::Hold:
2794 case pkgCache::State::DeInstall:
2795 return @"DeInstall";
2796 case pkgCache::State::Purge:
2800 return (NSString *) [NSNull null];
2803 - (NSArray *) warnings {
2804 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2805 const char *name(iterator_.Name());
2807 size_t length(strlen(name));
2808 if (length < 2) invalid:
2809 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2810 else for (size_t i(0); i != length; ++i)
2812 /* XXX: technically this is not allowed */
2813 (name[i] < 'A' || name[i] > 'Z') &&
2814 (name[i] < 'a' || name[i] > 'z') &&
2815 (name[i] < '0' || name[i] > '9') &&
2816 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2819 if (strcmp(name, "cydia") != 0) {
2822 bool _private = false;
2825 bool repository = [[self section] isEqualToString:@"Repositories"];
2827 if (NSArray *files = [self files])
2828 for (NSString *file in files)
2829 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2831 else if (!user && [file isEqualToString:@"/User"])
2833 else if (!_private && [file isEqualToString:@"/private"])
2835 else if (!stash && [file isEqualToString:@"/var/stash"])
2838 /* XXX: this is not sensitive enough. only some folders are valid. */
2839 if (cydia && !repository)
2840 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2842 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2844 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2846 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2849 return [warnings count] == 0 ? nil : warnings;
2852 - (NSArray *) applications {
2853 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2855 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2857 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2858 if (NSArray *files = [self files])
2859 for (NSString *file in files)
2860 if (application_r(file)) {
2861 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2862 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2863 if ([id isEqualToString:me])
2866 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2868 display = application_r[1];
2870 NSString *bundle([file stringByDeletingLastPathComponent]);
2871 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2872 if (icon == nil || [icon length] == 0)
2874 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2876 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2877 [applications addObject:application];
2879 [application addObject:id];
2880 [application addObject:display];
2881 [application addObject:url];
2884 return [applications count] == 0 ? nil : applications;
2887 - (Source *) source {
2888 if (source_ == nil) {
2889 @synchronized (database_) {
2890 if ([database_ era] != era_ || file_.end())
2891 source_ = (Source *) [NSNull null];
2893 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2897 return source_ == (Source *) [NSNull null] ? nil : source_;
2904 - (BOOL) matches:(NSArray *)query {
2905 if (query == nil || [query count] == 0)
2914 string = [self name];
2915 length = [string length];
2917 for (NSString *term in query) {
2918 range = [string rangeOfString:term options:MatchCompareOptions_];
2919 if (range.location != NSNotFound)
2920 rank_ -= 6 * 1000000 / length;
2925 length = [string length];
2927 for (NSString *term in query) {
2928 range = [string rangeOfString:term options:MatchCompareOptions_];
2929 if (range.location != NSNotFound)
2930 rank_ -= 6 * 1000000 / length;
2934 string = [self shortDescription];
2935 length = [string length];
2936 NSUInteger stop(std::min<NSUInteger>(length, 200));
2938 for (NSString *term in query) {
2939 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2940 if (range.location != NSNotFound)
2941 rank_ -= 2 * 100000;
2947 - (bool) hasSupportingRole {
2952 if ([Role_ isEqualToString:@"User"])
2956 if ([Role_ isEqualToString:@"Hacker"])
2960 if ([Role_ isEqualToString:@"Developer"])
2965 - (NSArray *) tags {
2969 - (BOOL) hasTag:(NSString *)tag {
2970 return tags_ == nil ? NO : [tags_ containsObject:tag];
2973 - (NSString *) primaryPurpose {
2974 for (NSString *tag in (NSArray *) tags_)
2975 if ([tag hasPrefix:@"purpose::"])
2976 return [tag substringFromIndex:9];
2980 - (NSArray *) purposes {
2981 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2982 for (NSString *tag in (NSArray *) tags_)
2983 if ([tag hasPrefix:@"purpose::"])
2984 [purposes addObject:[tag substringFromIndex:9]];
2985 return [purposes count] == 0 ? nil : purposes;
2988 - (bool) isCommercial {
2989 return [self hasTag:@"cydia::commercial"];
2992 - (void) setIndex:(size_t)index {
2993 if (metadata_->index_ != index)
2994 metadata_->index_ = index;
2997 - (CYString &) cyname {
2998 return name_.empty() ? id_ : name_;
3001 - (uint32_t) compareBySection:(NSArray *)sections {
3002 NSString *section([self section]);
3003 for (size_t i(0), e([sections count]); i != e; ++i) {
3004 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3008 return _not(uint32_t);
3012 @synchronized (database_) {
3013 pkgProblemResolver *resolver = [database_ resolver];
3014 resolver->Clear(iterator_);
3016 pkgCacheFile &cache([database_ cache]);
3017 cache->SetReInstall(iterator_, false);
3018 cache->MarkKeep(iterator_, false);
3022 @synchronized (database_) {
3023 pkgProblemResolver *resolver = [database_ resolver];
3024 resolver->Clear(iterator_);
3025 resolver->Protect(iterator_);
3027 pkgCacheFile &cache([database_ cache]);
3028 cache->SetReInstall(iterator_, false);
3029 cache->MarkInstall(iterator_, false);
3031 pkgDepCache::StateCache &state((*cache)[iterator_]);
3032 if (!state.Install())
3033 cache->SetReInstall(iterator_, true);
3037 @synchronized (database_) {
3038 pkgProblemResolver *resolver = [database_ resolver];
3039 resolver->Clear(iterator_);
3040 resolver->Remove(iterator_);
3041 resolver->Protect(iterator_);
3043 pkgCacheFile &cache([database_ cache]);
3044 cache->SetReInstall(iterator_, false);
3045 cache->MarkDelete(iterator_, true);
3048 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3049 _profile(Package$isUnfilteredAndSearchedForBy)
3052 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3053 value &= [self unfiltered];
3056 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3057 value &= [self matches:query];
3064 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3065 if ([search length] == 0)
3068 _profile(Package$isUnfilteredAndSelectedForBy)
3071 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3072 value &= [self unfiltered];
3075 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3076 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3083 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3084 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3087 - (bool) isVisibleInSection:(NSString *)name {
3088 NSString *section([self section]);
3092 section == nil && [name length] == 0 ||
3093 [name isEqualToString:section]
3094 ) && [self visible];
3097 - (bool) isVisibleInSource:(Source *)source {
3098 return [self source] == source && [self visible];
3103 /* Section Class {{{ */
3104 @interface Section : NSObject {
3109 _H<NSString> localized_;
3112 - (NSComparisonResult) compareByLocalized:(Section *)section;
3113 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3114 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3115 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3116 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3117 - (NSString *) name;
3124 - (void) addToCount;
3126 - (void) setCount:(size_t)count;
3127 - (NSString *) localized;
3131 @implementation Section
3133 - (NSComparisonResult) compareByLocalized:(Section *)section {
3134 NSString *lhs(localized_);
3135 NSString *rhs([section localized]);
3137 /*if ([lhs length] != 0 && [rhs length] != 0) {
3138 unichar lhc = [lhs characterAtIndex:0];
3139 unichar rhc = [rhs characterAtIndex:0];
3141 if (isalpha(lhc) && !isalpha(rhc))
3142 return NSOrderedAscending;
3143 else if (!isalpha(lhc) && isalpha(rhc))
3144 return NSOrderedDescending;
3147 return [lhs compare:rhs options:LaxCompareOptions_];
3150 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3151 if ((self = [self initWithName:name localize:NO]) != nil) {
3152 if (localized != nil)
3153 localized_ = localized;
3157 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3158 return [self initWithName:name row:0 localize:localize];
3161 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3162 if ((self = [super init]) != nil) {
3167 localized_ = LocalizeSection(name_);
3171 /* XXX: localize the index thingees */
3172 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3173 if ((self = [super init]) != nil) {
3174 name_ = [NSString stringWithCharacters:&index length:1];
3180 - (NSString *) name {
3200 - (void) addToCount {
3204 - (void) setCount:(size_t)count {
3208 - (NSString *) localized {
3215 class CydiaLogCleaner :
3216 public pkgArchiveCleaner
3219 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3224 /* Database Implementation {{{ */
3225 @implementation Database
3227 + (Database *) sharedInstance {
3228 static _H<Database> instance;
3229 if (instance == nil)
3230 instance = [[[Database alloc] init] autorelease];
3238 - (void) releasePackages {
3239 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3240 CFArrayRemoveAllValues(packages_);
3244 // XXX: actually implement this thing
3246 [self releasePackages];
3247 apr_pool_destroy(pool_);
3248 NSRecycleZone(zone_);
3252 - (void) _readCydia:(NSNumber *)fd {
3253 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3254 std::istream is(&ib);
3257 static Pcre finish_r("^finish:([^:]*)$");
3259 while (std::getline(is, line)) {
3260 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3262 const char *data(line.c_str());
3263 size_t size = line.size();
3264 lprintf("C:%s\n", data);
3266 if (finish_r(data, size)) {
3267 NSString *finish = finish_r[1];
3268 int index = [Finishes_ indexOfObject:finish];
3269 if (index != INT_MAX && index > Finish_)
3279 - (void) _readStatus:(NSNumber *)fd {
3280 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3281 std::istream is(&ib);
3284 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3285 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3287 while (std::getline(is, line)) {
3288 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3290 const char *data(line.c_str());
3291 size_t size(line.size());
3292 lprintf("S:%s\n", data);
3294 if (conffile_r(data, size)) {
3295 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3296 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3297 } else if (strncmp(data, "status: ", 8) == 0) {
3298 // status: <package>: {unpacked,half-configured,installed}
3299 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3300 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3301 } else if (strncmp(data, "processing: ", 12) == 0) {
3302 // processing: configure: config-test
3303 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3304 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3305 } else if (pmstatus_r(data, size)) {
3306 std::string type([pmstatus_r[1] UTF8String]);
3308 NSString *package = pmstatus_r[2];
3309 if ([package isEqualToString:@"dpkg-exec"])
3312 float percent([pmstatus_r[3] floatValue]);
3313 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3315 NSString *string = pmstatus_r[4];
3317 if (type == "pmerror") {
3318 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3319 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3320 } else if (type == "pmstatus") {
3321 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3322 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3323 } else if (type == "pmconffile")
3324 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3326 lprintf("E:unknown pmstatus\n");
3328 lprintf("E:unknown status\n");
3336 - (void) _readOutput:(NSNumber *)fd {
3337 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3338 std::istream is(&ib);
3341 while (std::getline(is, line)) {
3342 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3344 lprintf("O:%s\n", line.c_str());
3346 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3347 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3359 - (Package *) packageWithName:(NSString *)name {
3362 @synchronized (self) {
3363 if (static_cast<pkgDepCache *>(cache_) == NULL)
3365 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3366 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3370 if ((self = [super init]) != nil) {
3377 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3378 apr_pool_create(&pool_, NULL);
3380 size_t capacity(MetaFile_->active_);
3386 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3387 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3391 _assert(pipe(fds) != -1);
3394 _config->Set("APT::Keep-Fds::", cydiafd_);
3395 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3398 detachNewThreadSelector:@selector(_readCydia:)
3400 withObject:[NSNumber numberWithInt:fds[0]]
3403 _assert(pipe(fds) != -1);
3407 detachNewThreadSelector:@selector(_readStatus:)
3409 withObject:[NSNumber numberWithInt:fds[0]]
3412 _assert(pipe(fds) != -1);
3413 _assert(dup2(fds[0], 0) != -1);
3414 _assert(close(fds[0]) != -1);
3416 input_ = fdopen(fds[1], "a");
3418 _assert(pipe(fds) != -1);
3419 _assert(dup2(fds[1], 1) != -1);
3420 _assert(close(fds[1]) != -1);
3423 detachNewThreadSelector:@selector(_readOutput:)
3425 withObject:[NSNumber numberWithInt:fds[0]]
3430 - (pkgCacheFile &) cache {
3434 - (pkgDepCache::Policy *) policy {
3438 - (pkgRecords *) records {
3442 - (pkgProblemResolver *) resolver {
3446 - (pkgAcquire &) fetcher {
3450 - (pkgSourceList &) list {
3454 - (NSArray *) packages {
3455 return (NSArray *) packages_;
3458 - (NSArray *) sources {
3462 - (Source *) sourceWithKey:(NSString *)key {
3463 for (Source *source in [self sources]) {
3464 if ([[source key] isEqualToString:key])
3469 - (bool) popErrorWithTitle:(NSString *)title {
3472 while (!_error->empty()) {
3474 bool warning(!_error->PopMessage(error));
3479 size_t size(error.size());
3480 if (size == 0 || error[size - 1] != '\n')
3482 error.resize(size - 1);
3485 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3487 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3488 if (warning && no_pubkey(error.c_str()))
3491 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3497 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3498 return [self popErrorWithTitle:title] || !success;
3501 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3502 @synchronized (self) {
3505 [self releasePackages];
3508 [sourceList_ removeAllObjects];
3528 apr_pool_clear(pool_);
3530 NSRecycleZone(zone_);
3531 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3533 int chk(creat("/tmp/cydia.chk", 0644));
3537 if (invocation != nil)
3538 [invocation invoke];
3540 NSString *title(UCLocalize("DATABASE"));
3543 OpProgress progress;
3544 while (!cache_.Open(progress, true)) { pop:
3546 bool warning(!_error->PopMessage(error));
3547 lprintf("cache_.Open():[%s]\n", error.c_str());
3549 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3550 [delegate_ repairWithSelector:@selector(configure)];
3551 else if (error == "The package lists or status file could not be parsed or opened.")
3552 [delegate_ repairWithSelector:@selector(update)];
3553 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3554 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3555 // else if (error == "Malformed Status line")
3556 // else if (error == "The list of sources could not be read.")
3558 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3568 unlink("/tmp/cydia.chk");
3570 now_ = [[NSDate date] timeIntervalSince1970];
3572 policy_ = new pkgDepCache::Policy();
3573 records_ = new pkgRecords(cache_);
3574 resolver_ = new pkgProblemResolver(cache_);
3575 fetcher_ = new pkgAcquire(&status_);
3578 list_ = new pkgSourceList();
3579 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3582 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3583 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3587 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3590 if (cache_->BrokenCount() != 0) {
3591 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3594 if (cache_->BrokenCount() != 0) {
3595 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3599 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3603 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3604 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3605 [sourceList_ addObject:object];
3607 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3608 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3609 // XXX: this could be more intelligent
3610 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3611 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3613 sourceMap_[cached->ID] = object;
3618 /*std::vector<Package *> packages;
3619 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3624 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3625 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3626 //packages.push_back(package);
3627 CFArrayAppendValue(packages_, CFRetain(package));
3631 /*if (packages.empty())
3632 packages_ = [[NSArray alloc] init];
3634 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3637 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3638 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3639 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3647 /*if (!packages.empty())
3648 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3649 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3651 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3653 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3655 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3659 size_t count(CFArrayGetCount(packages_));
3660 MetaFile_->active_ = count;
3662 for (size_t index(0); index != count; ++index)
3663 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3670 @synchronized (self) {
3672 resolver_ = new pkgProblemResolver(cache_);
3674 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3675 if (!cache_[iterator].Keep())
3676 cache_->MarkKeep(iterator, false);
3677 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3678 cache_->SetReInstall(iterator, false);
3681 - (void) configure {
3682 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3684 system([dpkg UTF8String]);
3689 @synchronized (self) {
3690 // XXX: I don't remember this condition
3695 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3697 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3699 if ([self popErrorWithTitle:title])
3703 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3705 CydiaLogCleaner cleaner;
3706 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3713 fetcher_->Shutdown();
3715 pkgRecords records(cache_);
3717 lock_ = new FileFd();
3718 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3720 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3722 if ([self popErrorWithTitle:title])
3726 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3729 manager_ = (_system->CreatePM(cache_));
3730 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3737 bool substrate(RestartSubstrate_);
3738 RestartSubstrate_ = false;
3740 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3742 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3744 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3746 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3747 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3750 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3752 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3754 [self popErrorWithTitle:title];
3758 bool failed = false;
3759 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3760 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3762 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3765 std::string uri = (*item)->DescURI();
3766 std::string error = (*item)->ErrorText;
3768 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3771 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3772 [delegate_ addProgressEventOnMainThread:event forTask:title];
3775 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3783 RestartSubstrate_ = true;
3786 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3787 if ([self popErrorWithTitle:title])
3790 if (result == pkgPackageManager::Failed) {
3795 if (result != pkgPackageManager::Completed) {
3800 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3802 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3804 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3805 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3808 if (![before isEqualToArray:after])
3813 NSString *title(UCLocalize("UPGRADE"));
3814 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3820 [self updateWithStatus:status_];
3823 - (void) updateWithStatus:(Status &)status {
3824 NSString *title(UCLocalize("REFRESHING_DATA"));
3827 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3831 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3832 if ([self popErrorWithTitle:title])
3835 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3837 bool success(ListUpdate(status, list, PulseInterval_));
3838 if (status.WasCancelled())
3841 [self popErrorWithTitle:title forOperation:success];
3842 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3846 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3849 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3850 delegate_ = delegate;
3853 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3854 progress_ = delegate;
3855 status_.setDelegate(delegate);
3858 - (NSObject<ProgressDelegate> *) progressDelegate {
3862 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3863 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3864 return i == sourceMap_.end() ? nil : i->second;
3867 - (NSString *) mappedSectionForPointer:(const char *)section {
3868 _H<NSString> *mapped;
3870 _profile(Database$mappedSectionForPointer$Cache)
3871 mapped = §ions_[section];
3874 if (*mapped == NULL) {
3875 size_t length(strlen(section));
3876 char spaced[length + 1];
3878 _profile(Database$mappedSectionForPointer$Replace)
3879 for (size_t index(0); index != length; ++index)
3880 spaced[index] = section[index] == '_' ? ' ' : section[index];
3881 spaced[length] = '\0';
3886 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3887 string = [NSString stringWithUTF8String:spaced];
3890 _profile(Database$mappedSectionForPointer$Map)
3891 string = [SectionMap_ objectForKey:string] ?: string;
3901 static _H<NSMutableSet> Diversions_;
3903 @interface Diversion : NSObject {
3906 _H<NSString> format_;
3911 @implementation Diversion
3913 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3914 if ((self = [super init]) != nil) {
3915 pattern_ = [from UTF8String];
3921 - (NSString *) divert:(NSString *)url {
3922 return !pattern_(url) ? nil : pattern_->*format_;
3925 + (NSURL *) divertURL:(NSURL *)url {
3927 NSString *href([url absoluteString]);
3929 for (Diversion *diversion in (id) Diversions_)
3930 if (NSString *diverted = [diversion divert:href]) {
3932 NSLog(@"div: %@", diverted);
3934 url = [NSURL URLWithString:diverted];
3941 - (NSString *) key {
3945 - (NSUInteger) hash {
3949 - (BOOL) isEqual:(Diversion *)object {
3950 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3955 @interface CydiaObject : NSObject {
3956 _H<IndirectDelegate> indirect_;
3957 _transient id delegate_;
3960 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3966 @interface CydiaWebViewController : CyteWebViewController {
3967 _H<CydiaObject> cydia_;
3970 + (void) addDiversion:(Diversion *)diversion;
3971 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3972 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3973 - (void) setDelegate:(id)delegate;
3977 /* Web Scripting {{{ */
3978 @implementation CydiaObject
3980 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3981 if ((self = [super init]) != nil) {
3982 indirect_ = indirect;
3986 - (void) setDelegate:(id)delegate {
3987 delegate_ = delegate;
3990 + (NSArray *) _attributeKeys {
3991 return [NSArray arrayWithObjects:
3994 @"coreFoundationVersionNumber",
4011 - (NSArray *) attributeKeys {
4012 return [[self class] _attributeKeys];
4015 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4016 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4019 - (NSString *) version {
4023 - (NSString *) build {
4027 - (NSString *) coreFoundationVersionNumber {
4028 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4031 - (NSString *) device {
4032 return [[UIDevice currentDevice] uniqueIdentifier];
4035 - (NSString *) firmware {
4036 return [[UIDevice currentDevice] systemVersion];
4039 - (NSString *) hostname {
4040 return [[UIDevice currentDevice] name];
4043 - (NSString *) idiom {
4044 return (id) Idiom_ ?: [NSNull null];
4047 - (NSString *) mcc {
4048 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4049 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4053 - (NSString *) mnc {
4054 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4055 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4059 - (NSString *) operator {
4060 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4061 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4065 - (NSString *) bbsnum {
4066 return (id) BBSNum_ ?: [NSNull null];
4069 - (NSString *) ecid {
4070 return (id) ChipID_ ?: [NSNull null];
4073 - (NSString *) serial {
4074 return SerialNumber_;
4077 - (NSString *) role {
4078 return (id) Role_ ?: [NSNull null];
4081 - (NSString *) model {
4082 return [NSString stringWithUTF8String:Machine_];
4085 - (NSString *) token {
4086 return (id) Token_ ?: [NSNull null];
4089 + (NSString *) webScriptNameForSelector:(SEL)selector {
4091 else if (selector == @selector(addBridgedHost:))
4092 return @"addBridgedHost";
4093 else if (selector == @selector(addInsecureHost:))
4094 return @"addInsecureHost";
4095 else if (selector == @selector(addInternalRedirect::))
4096 return @"addInternalRedirect";
4097 else if (selector == @selector(addPipelinedHost:scheme:))
4098 return @"addPipelinedHost";
4099 else if (selector == @selector(addSource:::))
4100 return @"addSource";
4101 else if (selector == @selector(addTokenHost:))
4102 return @"addTokenHost";
4103 else if (selector == @selector(addTrivialSource:))
4104 return @"addTrivialSource";
4105 else if (selector == @selector(close))
4107 else if (selector == @selector(du:))
4109 else if (selector == @selector(stringWithFormat:arguments:))
4111 else if (selector == @selector(getAllSources))
4112 return @"getAllSourcs";
4113 else if (selector == @selector(getKernelNumber:))
4114 return @"getKernelNumber";
4115 else if (selector == @selector(getKernelString:))
4116 return @"getKernelString";
4117 else if (selector == @selector(getInstalledPackages))
4118 return @"getInstalledPackages";
4119 else if (selector == @selector(getIORegistryEntry::))
4120 return @"getIORegistryEntry";
4121 else if (selector == @selector(getLocaleIdentifier))
4122 return @"getLocaleIdentifier";
4123 else if (selector == @selector(getPreferredLanguages))
4124 return @"getPreferredLanguages";
4125 else if (selector == @selector(getPackageById:))
4126 return @"getPackageById";
4127 else if (selector == @selector(getMetadataKeys))
4128 return @"getMetadataKeys";
4129 else if (selector == @selector(getMetadataValue:))
4130 return @"getMetadataValue";
4131 else if (selector == @selector(getSessionValue:))
4132 return @"getSessionValue";
4133 else if (selector == @selector(installPackages:))
4134 return @"installPackages";
4135 else if (selector == @selector(isReachable:))
4136 return @"isReachable";
4137 else if (selector == @selector(localizedStringForKey:value:table:))
4139 else if (selector == @selector(popViewController:))
4140 return @"popViewController";
4141 else if (selector == @selector(refreshSources))
4142 return @"refreshSources";
4143 else if (selector == @selector(removeButton))
4144 return @"removeButton";
4145 else if (selector == @selector(saveConfig))
4146 return @"saveConfig";
4147 else if (selector == @selector(setMetadataValue::))
4148 return @"setMetadataValue";
4149 else if (selector == @selector(setSessionValue::))
4150 return @"setSessionValue";
4151 else if (selector == @selector(setShowPromoted:))
4152 return @"setShowPromoted";
4153 else if (selector == @selector(substitutePackageNames:))
4154 return @"substitutePackageNames";
4155 else if (selector == @selector(scrollToBottom:))
4156 return @"scrollToBottom";
4157 else if (selector == @selector(setAllowsNavigationAction:))
4158 return @"setAllowsNavigationAction";
4159 else if (selector == @selector(setBadgeValue:))
4160 return @"setBadgeValue";
4161 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4162 return @"setButtonImage";
4163 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4164 return @"setButtonTitle";
4165 else if (selector == @selector(setHidesBackButton:))
4166 return @"setHidesBackButton";
4167 else if (selector == @selector(setHidesNavigationBar:))
4168 return @"setHidesNavigationBar";
4169 else if (selector == @selector(setNavigationBarStyle:))
4170 return @"setNavigationBarStyle";
4171 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4172 return @"setNavigationBarTintColor";
4173 else if (selector == @selector(setPasteboardString:))
4174 return @"setPasteboardString";
4175 else if (selector == @selector(setPasteboardURL:))
4176 return @"setPasteboardURL";
4177 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4178 return @"setScrollAlwaysBounceVertical";
4179 else if (selector == @selector(setScrollIndicatorStyle:))
4180 return @"setScrollIndicatorStyle";
4181 else if (selector == @selector(setToken:))
4183 else if (selector == @selector(setViewportWidth:))
4184 return @"setViewportWidth";
4185 else if (selector == @selector(statfs:))
4187 else if (selector == @selector(supports:))
4189 else if (selector == @selector(unload))
4195 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4196 return [self webScriptNameForSelector:selector] == nil;
4199 - (BOOL) supports:(NSString *)feature {
4200 return [feature isEqualToString:@"window.open"];
4204 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4207 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4208 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4211 - (void) setScrollIndicatorStyle:(NSString *)style {
4212 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4215 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4216 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4219 - (NSNumber *) getKernelNumber:(NSString *)name {
4220 const char *string([name UTF8String]);
4223 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4224 return (id) [NSNull null];
4226 if (size != sizeof(int))
4227 return (id) [NSNull null];
4230 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4231 return (id) [NSNull null];
4233 return [NSNumber numberWithInt:value];
4236 - (NSString *) getKernelString:(NSString *)name {
4237 const char *string([name UTF8String]);
4240 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4241 return (id) [NSNull null];
4243 char value[size + 1];
4244 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4245 return (id) [NSNull null];
4247 // XXX: just in case you request something ludicrous
4250 return [NSString stringWithCString:value];
4253 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4254 NSObject *value(CYIOGetValue([path UTF8String], entry));
4257 if ([value isKindOfClass:[NSData class]])
4258 value = CYHex((NSData *) value);
4263 - (NSArray *) getMetadataKeys {
4264 @synchronized (Values_) {
4265 return [Values_ allKeys];
4268 - (void) _setShowPromoted:(NSNumber *)value {
4269 [Metadata_ setObject:value forKey:@"ShowPromoted"];
4273 - (void) setShowPromoted:(NSNumber *)value {
4274 [self performSelectorOnMainThread:@selector(_setShowPromoted:) withObject:value waitUntilDone:NO];
4277 - (id) getMetadataValue:(NSString *)key {
4278 @synchronized (Values_) {
4279 return [Values_ objectForKey:key];
4282 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4283 @synchronized (Values_) {
4284 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4285 [Values_ removeObjectForKey:key];
4287 [Values_ setObject:value forKey:key];
4289 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4292 - (id) getSessionValue:(NSString *)key {
4293 @synchronized (SessionData_) {
4294 return [SessionData_ objectForKey:key];
4297 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4298 @synchronized (SessionData_) {
4299 if (value == (id) [WebUndefined undefined])
4300 [SessionData_ removeObjectForKey:key];
4302 [SessionData_ setObject:value forKey:key];
4305 - (void) addBridgedHost:(NSString *)host {
4306 @synchronized (HostConfig_) {
4307 [BridgedHosts_ addObject:host];
4310 - (void) addInsecureHost:(NSString *)host {
4311 @synchronized (HostConfig_) {
4312 [InsecureHosts_ addObject:host];
4315 - (void) addTokenHost:(NSString *)host {
4316 @synchronized (HostConfig_) {
4317 [TokenHosts_ addObject:host];
4320 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4321 @synchronized (HostConfig_) {
4322 if (scheme != (id) [WebUndefined undefined])
4323 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4325 [PipelinedHosts_ addObject:host];
4328 - (void) popViewController:(NSNumber *)value {
4329 if (value == (id) [WebUndefined undefined])
4330 value = [NSNumber numberWithBool:YES];
4331 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4334 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4335 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4337 for (NSString *section in sections)
4338 [array addObject:section];
4340 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4343 distribution, @"Distribution",
4345 nil] waitUntilDone:NO];
4348 - (void) addTrivialSource:(NSString *)href {
4349 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4352 - (void) refreshSources {
4353 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4356 - (void) saveConfig {
4357 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4360 - (NSArray *) getAllSources {
4361 return [[Database sharedInstance] sources];
4364 - (NSArray *) getInstalledPackages {
4365 Database *database([Database sharedInstance]);
4366 @synchronized (database) {
4367 NSArray *packages([database packages]);
4368 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4369 for (Package *package in packages)
4370 if (![package uninstalled])
4371 [installed addObject:package];
4375 - (Package *) getPackageById:(NSString *)id {
4376 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4380 return (Package *) [NSNull null];
4383 - (NSString *) getLocaleIdentifier {
4384 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4387 - (NSArray *) getPreferredLanguages {
4391 - (NSArray *) statfs:(NSString *)path {
4394 if (path == nil || statfs([path UTF8String], &stat) == -1)
4397 return [NSArray arrayWithObjects:
4398 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4399 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4400 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4404 - (NSNumber *) du:(NSString *)path {
4405 NSNumber *value(nil);
4408 _assert(pipe(fds) != -1);
4410 pid_t pid(ExecFork());
4412 _assert(dup2(fds[1], 1) != -1);
4413 _assert(close(fds[0]) != -1);
4414 _assert(close(fds[1]) != -1);
4415 /* XXX: this should probably not use du */
4416 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4421 _assert(close(fds[1]) != -1);
4423 if (FILE *du = fdopen(fds[0], "r")) {
4425 while (fgets(line, sizeof(line), du) != NULL) {
4426 size_t length(strlen(line));
4427 while (length != 0 && line[length - 1] == '\n')
4428 line[--length] = '\0';
4429 if (char *tab = strchr(line, '\t')) {
4431 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4436 } else _assert(close(fds[0]));
4444 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4447 - (NSNumber *) isReachable:(NSString *)name {
4448 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4451 - (void) installPackages:(NSArray *)packages {
4452 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4455 - (NSString *) substitutePackageNames:(NSString *)message {
4456 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4457 for (size_t i(0), e([words count]); i != e; ++i) {
4458 NSString *word([words objectAtIndex:i]);
4459 if (Package *package = [[Database sharedInstance] packageWithName:word])
4460 [words replaceObjectAtIndex:i withObject:[package name]];
4463 return [words componentsJoinedByString:@" "];
4466 - (void) removeButton {
4467 [indirect_ removeButton];
4470 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4471 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4474 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4475 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4478 - (void) setBadgeValue:(id)value {
4479 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4482 - (void) setAllowsNavigationAction:(NSString *)value {
4483 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4486 - (void) setHidesBackButton:(NSString *)value {
4487 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4490 - (void) setHidesNavigationBar:(NSString *)value {
4491 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4494 - (void) setNavigationBarStyle:(NSString *)value {
4495 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4498 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4499 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4500 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4501 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4504 - (void) setPasteboardString:(NSString *)value {
4505 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4508 - (void) setPasteboardURL:(NSString *)value {
4509 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4512 - (void) _setToken:(NSString *)token {
4516 [Metadata_ removeObjectForKey:@"Token"];
4518 [Metadata_ setObject:Token_ forKey:@"Token"];
4523 - (void) setToken:(NSString *)token {
4524 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4527 - (void) scrollToBottom:(NSNumber *)animated {
4528 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4531 - (void) setViewportWidth:(float)width {
4532 [indirect_ setViewportWidthOnMainThread:width];
4535 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4536 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4537 unsigned count([arguments count]);
4539 for (unsigned i(0); i != count; ++i)
4540 values[i] = [arguments objectAtIndex:i];
4541 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4544 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4545 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4547 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4549 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4555 @interface NSURL (CydiaSecure)
4558 @implementation NSURL (CydiaSecure)
4560 - (bool) isCydiaSecure {
4561 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4564 @synchronized (HostConfig_) {
4565 if ([InsecureHosts_ containsObject:[self host]])
4574 /* Cydia Browser Controller {{{ */
4575 @implementation CydiaWebViewController
4577 - (NSURL *) navigationURL {
4578 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4581 + (void) _initialize {
4582 [super _initialize];
4584 Diversions_ = [NSMutableSet setWithCapacity:0];
4587 + (void) addDiversion:(Diversion *)diversion {
4588 [Diversions_ addObject:diversion];
4591 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4592 [super webView:view didClearWindowObject:window forFrame:frame];
4593 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4596 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4597 WebDataSource *source([frame dataSource]);
4598 NSURLResponse *response([source response]);
4599 NSURL *url([response URL]);
4600 NSString *scheme([[url scheme] lowercaseString]);
4602 bool bridged(false);
4604 @synchronized (HostConfig_) {
4605 if ([scheme isEqualToString:@"file"])
4607 else if ([scheme isEqualToString:@"https"])
4608 if ([BridgedHosts_ containsObject:[url host]])
4613 [window setValue:cydia forKey:@"cydia"];
4616 - (void) _setupMail:(MFMailComposeViewController *)controller {
4617 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4619 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4620 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4623 - (NSURL *) URLWithURL:(NSURL *)url {
4624 return [Diversion divertURL:url];
4627 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4628 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4631 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4632 NSMutableURLRequest *copy([request mutableCopy]);
4634 NSURL *url([copy URL]);
4635 NSString *href([url absoluteString]);
4636 NSString *host([url host]);
4638 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4639 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4640 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4641 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4644 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4645 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4647 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4651 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4652 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4653 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4654 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4659 @synchronized (HostConfig_) {
4660 bridged = [BridgedHosts_ containsObject:host];
4661 token = [TokenHosts_ containsObject:host];
4664 if ([url isCydiaSecure]) {
4666 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4667 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4669 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4670 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4677 - (void) setDelegate:(id)delegate {
4678 [super setDelegate:delegate];
4679 [cydia_ setDelegate:delegate];
4682 - (NSString *) applicationNameForUserAgent {
4687 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4688 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4694 @interface AppCacheController : CydiaWebViewController {
4699 @implementation AppCacheController
4701 - (void) didReceiveMemoryWarning {
4702 // XXX: this doesn't work
4705 - (bool) retainsNetworkActivityIndicator {
4713 @interface NSObject (CydiaScript)
4714 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4717 @implementation NSObject (CydiaScript)
4719 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4725 @implementation NSArray (CydiaScript)
4727 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4728 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4729 for (size_t i(0), e([self count]); i != e; ++i)
4730 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4736 @implementation NSDictionary (CydiaScript)
4738 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4739 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4741 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4748 /* Confirmation Controller {{{ */
4749 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4750 if (!iterator.end())
4751 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4752 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4754 pkgCache::PkgIterator package(dep.TargetPkg());
4757 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4764 @protocol ConfirmationControllerDelegate
4765 - (void) cancelAndClear:(bool)clear;
4766 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4770 @interface ConfirmationController : CydiaWebViewController {
4771 _transient Database *database_;
4773 _H<UIAlertView> essential_;
4775 _H<NSDictionary> changes_;
4776 _H<NSMutableArray> issues_;
4777 _H<NSDictionary> sizes_;
4782 - (id) initWithDatabase:(Database *)database;
4786 @implementation ConfirmationController
4790 RestartSubstrate_ = true;
4791 [delegate_ confirmWithNavigationController:[self navigationController]];
4794 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4795 NSString *context([alert context]);
4797 if ([context isEqualToString:@"remove"]) {
4798 if (button == [alert cancelButtonIndex])
4799 [self dismissModalViewControllerAnimated:YES];
4800 else if (button == [alert firstOtherButtonIndex]) {
4804 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4805 } else if ([context isEqualToString:@"unable"]) {
4806 [self dismissModalViewControllerAnimated:YES];
4807 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4809 [super alertView:alert clickedButtonAtIndex:button];
4813 - (void) _doContinue {
4814 [delegate_ cancelAndClear:NO];
4815 [self dismissModalViewControllerAnimated:YES];
4818 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4819 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4823 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4824 [super webView:view didClearWindowObject:window forFrame:frame];
4826 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4827 (id) changes_, @"changes",
4828 (id) issues_, @"issues",
4829 (id) sizes_, @"sizes",
4831 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4834 - (id) initWithDatabase:(Database *)database {
4835 if ((self = [super init]) != nil) {
4836 database_ = database;
4838 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4839 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4840 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4841 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4842 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4846 pkgCacheFile &cache([database_ cache]);
4847 NSArray *packages([database_ packages]);
4848 pkgDepCache::Policy *policy([database_ policy]);
4850 issues_ = [NSMutableArray arrayWithCapacity:4];
4852 for (Package *package in packages) {
4853 pkgCache::PkgIterator iterator([package iterator]);
4854 NSString *name([package id]);
4856 if ([package broken]) {
4857 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4859 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4861 reasons, @"reasons",
4864 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4868 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4869 pkgCache::DepIterator start;
4870 pkgCache::DepIterator end;
4871 dep.GlobOr(start, end); // ++dep
4873 if (!cache->IsImportantDep(end))
4875 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4878 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4880 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4881 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4882 clauses, @"clauses",
4886 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4888 pkgCache::PkgIterator target(start.TargetPkg());
4889 if (target->ProvidesList != 0)
4890 reason = @"missing";
4892 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4894 reason = @"installed";
4895 installed = [NSString stringWithUTF8String:ver.VerStr()];
4896 } else if (!cache[target].CandidateVerIter(cache).end())
4897 reason = @"uninstalled";
4898 else if (target->ProvidesList == 0)
4899 reason = @"uninstallable";
4901 reason = @"virtual";
4904 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4905 [NSString stringWithUTF8String:start.CompType()], @"operator",
4906 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4909 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4910 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4911 version, @"version",
4913 installed, @"installed",
4916 // yes, seriously. (wtf?)
4924 pkgDepCache::StateCache &state(cache[iterator]);
4926 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4928 if (state.NewInstall())
4929 [installs addObject:name];
4930 // XXX: else if (state.Install())
4931 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4932 [reinstalls addObject:name];
4933 // XXX: move before previous if
4934 else if (state.Upgrade())
4935 [upgrades addObject:name];
4936 else if (state.Downgrade())
4937 [downgrades addObject:name];
4938 else if (!state.Delete())
4939 // XXX: _assert(state.Keep());
4941 else if (special_r(name))
4942 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4943 [NSNull null], @"package",
4944 [NSArray arrayWithObjects:
4945 [NSDictionary dictionaryWithObjectsAndKeys:
4946 @"Conflicts", @"relationship",
4947 [NSArray arrayWithObjects:
4948 [NSDictionary dictionaryWithObjectsAndKeys:
4950 [NSNull null], @"version",
4951 @"installed", @"reason",
4958 if ([package essential])
4960 [removes addObject:name];
4963 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4964 substrate_ |= DepSubstrate(iterator.CurrentVer());
4969 else if (Advanced_) {
4970 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4972 essential_ = [[[UIAlertView alloc]
4973 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4974 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4976 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4978 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4982 [essential_ setContext:@"remove"];
4984 essential_ = [[[UIAlertView alloc]
4985 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4986 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4988 cancelButtonTitle:UCLocalize("OKAY")
4989 otherButtonTitles:nil
4992 [essential_ setContext:@"unable"];
4995 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4996 installs, @"installs",
4997 reinstalls, @"reinstalls",
4998 upgrades, @"upgrades",
4999 downgrades, @"downgrades",
5000 removes, @"removes",
5003 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5004 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5005 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5008 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5012 - (UIBarButtonItem *) leftButton {
5013 return [[[UIBarButtonItem alloc]
5014 initWithTitle:UCLocalize("CANCEL")
5015 style:UIBarButtonItemStylePlain
5017 action:@selector(cancelButtonClicked)
5022 - (void) applyRightButton {
5023 if ([issues_ count] == 0 && ![self isLoading])
5024 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5025 initWithTitle:UCLocalize("CONFIRM")
5026 style:UIBarButtonItemStyleDone
5028 action:@selector(confirmButtonClicked)
5031 [[self navigationItem] setRightBarButtonItem:nil];
5035 - (void) cancelButtonClicked {
5036 [delegate_ cancelAndClear:YES];
5037 [self dismissModalViewControllerAnimated:YES];
5041 - (void) confirmButtonClicked {
5042 if (essential_ != nil)
5052 /* Progress Data {{{ */
5053 @interface CydiaProgressData : NSObject {
5054 _transient id delegate_;
5063 _H<NSMutableArray> events_;
5064 _H<NSString> title_;
5066 _H<NSString> status_;
5067 _H<NSString> finish_;
5072 @implementation CydiaProgressData
5074 + (NSArray *) _attributeKeys {
5075 return [NSArray arrayWithObjects:
5087 - (NSArray *) attributeKeys {
5088 return [[self class] _attributeKeys];
5091 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5092 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5096 if ((self = [super init]) != nil) {
5097 events_ = [NSMutableArray arrayWithCapacity:32];
5101 - (void) setDelegate:(id)delegate {
5102 delegate_ = delegate;
5105 - (void) setPercent:(float)value {
5109 - (NSNumber *) percent {
5110 return [NSNumber numberWithFloat:percent_];
5113 - (void) setCurrent:(float)value {
5117 - (NSNumber *) current {
5118 return [NSNumber numberWithFloat:current_];
5121 - (void) setTotal:(float)value {
5125 - (NSNumber *) total {
5126 return [NSNumber numberWithFloat:total_];
5129 - (void) setSpeed:(float)value {
5133 - (NSNumber *) speed {
5134 return [NSNumber numberWithFloat:speed_];
5137 - (NSArray *) events {
5141 - (void) removeAllEvents {
5142 [events_ removeAllObjects];
5145 - (void) addEvent:(CydiaProgressEvent *)event {
5146 [events_ addObject:event];
5149 - (void) setTitle:(NSString *)text {
5153 - (NSString *) title {
5157 - (void) setFinish:(NSString *)text {
5161 - (NSString *) finish {
5162 return (id) finish_ ?: [NSNull null];
5165 - (void) setRunning:(bool)running {
5169 - (NSNumber *) running {
5170 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5175 /* Progress Controller {{{ */
5176 @interface ProgressController : CydiaWebViewController <
5179 _transient Database *database_;
5180 _H<CydiaProgressData, 1> progress_;
5184 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5186 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5188 - (void) setTitle:(NSString *)title;
5189 - (void) setCancellable:(bool)cancellable;
5193 @implementation ProgressController
5196 [database_ setProgressDelegate:nil];
5200 - (UIBarButtonItem *) leftButton {
5201 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5202 initWithTitle:UCLocalize("CANCEL")
5203 style:UIBarButtonItemStylePlain
5205 action:@selector(cancel)
5206 ] autorelease] : nil;
5209 - (void) updateCancel {
5210 [super applyLeftButton];
5213 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5214 if ((self = [super init]) != nil) {
5215 database_ = database;
5216 delegate_ = delegate;
5218 [database_ setProgressDelegate:self];
5220 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5221 [progress_ setDelegate:self];
5223 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5225 [scroller_ setBackgroundColor:[UIColor blackColor]];
5227 [[self navigationItem] setHidesBackButton:YES];
5229 [self updateCancel];
5233 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5234 [super webView:view didClearWindowObject:window forFrame:frame];
5235 [window setValue:progress_ forKey:@"cydiaProgress"];
5238 - (void) updateProgress {
5239 [self dispatchEvent:@"CydiaProgressUpdate"];
5242 - (void) viewWillAppear:(BOOL)animated {
5243 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5244 [super viewWillAppear:animated];
5247 - (void) reloadSpringBoard {
5248 pid_t pid(ExecFork());
5250 pid_t pid(ExecFork());
5252 execl("/usr/bin/sbreload", "sbreload", NULL);
5263 system("/usr/bin/killall SpringBoard");
5267 UpdateExternalStatus(0);
5270 [delegate_ saveState];
5274 [delegate_ returnToCydia];
5278 [delegate_ terminateWithSuccess];
5279 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5280 [delegate_ suspendWithAnimation:YES];
5282 [delegate_ suspend];*/
5294 UIProgressHUD *hud([delegate_ addProgressHUD]);
5295 [hud setText:UCLocalize("LOADING")];
5296 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5302 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5303 SBReboot(SBSSpringBoardServerPort());
5305 reboot2(RB_AUTOBOOT);
5312 - (void) setTitle:(NSString *)title {
5313 [progress_ setTitle:title];
5314 [self updateProgress];
5317 - (UIBarButtonItem *) rightButton {
5318 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5319 initWithTitle:UCLocalize("CLOSE")
5320 style:UIBarButtonItemStylePlain
5322 action:@selector(close)
5328 system("su -c /usr/bin/uicache mobile");
5332 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5333 UpdateExternalStatus(1);
5335 [progress_ setRunning:true];
5336 [self setTitle:title];
5337 // implicit updateProgress
5339 SHA1SumValue notifyconf; {
5341 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5344 MMap mmap(file, MMap::ReadOnly);
5346 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5347 notifyconf = sha1.Result();
5351 SHA1SumValue springlist; {
5353 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5356 MMap mmap(file, MMap::ReadOnly);
5358 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5359 springlist = sha1.Result();
5363 if (invocation != nil) {
5364 [invocation yieldToSelector:@selector(invoke)];
5365 [self setTitle:@"COMPLETE"];
5370 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5373 MMap mmap(file, MMap::ReadOnly);
5375 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5376 if (!(notifyconf == sha1.Result()))
5383 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5386 MMap mmap(file, MMap::ReadOnly);
5388 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5389 if (!(springlist == sha1.Result()))
5395 if (RestartSubstrate_)
5399 RestartSubstrate_ = false;
5402 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5403 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5404 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5405 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5406 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5409 UIProgressHUD *hud([delegate_ addProgressHUD]);
5410 [hud setText:UCLocalize("LOADING")];
5411 [self yieldToSelector:@selector(uicache)];
5412 [delegate_ removeProgressHUD:hud];
5414 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5416 [progress_ setRunning:false];
5417 [self updateProgress];
5419 [self applyRightButton];
5422 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5423 [progress_ addEvent:event];
5424 [self updateProgress];
5427 - (bool) isProgressCancelled {
5428 return cancel_ == 2;
5433 [self updateCancel];
5436 - (void) setCancellable:(bool)cancellable {
5437 unsigned cancel(cancel_);
5441 else if (cancel_ == 0)
5444 if (cancel != cancel_)
5445 [self updateCancel];
5448 - (void) setProgressCancellable:(NSNumber *)cancellable {
5449 [self setCancellable:[cancellable boolValue]];
5452 - (void) setProgressPercent:(NSNumber *)percent {
5453 [progress_ setPercent:[percent floatValue]];
5454 [self updateProgress];
5457 - (void) setProgressStatus:(NSDictionary *)status {
5458 if (status == nil) {
5459 [progress_ setCurrent:0];
5460 [progress_ setTotal:0];
5461 [progress_ setSpeed:0];
5463 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5465 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5466 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5467 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5470 [self updateProgress];
5476 /* Package Cell {{{ */
5477 @interface PackageCell : CyteTableViewCell <
5478 CyteTableViewCellDelegate
5482 _H<NSString> description_;
5484 _H<NSString> source_;
5486 _H<UIImage> placard_;
5490 - (PackageCell *) init;
5491 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5493 - (void) drawContentRect:(CGRect)rect;
5497 @implementation PackageCell
5499 - (PackageCell *) init {
5500 CGRect frame(CGRectMake(0, 0, 320, 74));
5501 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5502 UIView *content([self contentView]);
5503 CGRect bounds([content bounds]);
5505 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5506 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5507 [content addSubview:content_];
5509 [content_ setDelegate:self];
5510 [content_ setOpaque:YES];
5514 - (NSString *) accessibilityLabel {
5515 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5518 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5519 summarized_ = summary;
5529 [content_ setBackgroundColor:[UIColor whiteColor]];
5533 Source *source = [package source];
5535 icon_ = [package icon];
5537 if (NSString *name = [package name])
5538 name_ = [NSString stringWithString:name];
5540 NSString *description(nil);
5542 if (description == nil && IsWildcat_)
5543 description = [package longDescription];
5544 if (description == nil)
5545 description = [package shortDescription];
5547 if (description != nil)
5548 description_ = [NSString stringWithString:description];
5550 commercial_ = [package isCommercial];
5552 NSString *label = nil;
5553 bool trusted = false;
5555 if (source != nil) {
5556 label = [source label];
5557 trusted = [source trusted];
5558 } else if ([[package id] isEqualToString:@"firmware"])
5559 label = UCLocalize("APPLE");
5561 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5563 NSString *from(label);
5565 NSString *section = [package simpleSection];
5566 if (section != nil && ![section isEqualToString:label]) {
5567 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5568 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5571 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5573 if (NSString *purpose = [package primaryPurpose])
5574 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5579 if (NSString *mode = [package mode]) {
5580 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5581 color = RemovingColor_;
5582 //placard = @"removing";
5584 color = InstallingColor_;
5585 //placard = @"installing";
5588 // XXX: the removing/installing placards are not @2x
5591 color = [UIColor whiteColor];
5593 if ([package installed] != nil)
5594 placard = @"installed";
5599 [content_ setBackgroundColor:color];
5602 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5605 [self setNeedsDisplay];
5606 [content_ setNeedsDisplay];
5609 - (void) drawSummaryContentRect:(CGRect)rect {
5610 bool highlighted(highlighted_);
5611 float width([self bounds].size.width);
5615 rect.size = [(UIImage *) icon_ size];
5617 while (rect.size.width > 16 || rect.size.height > 16) {
5618 rect.size.width /= 2;
5619 rect.size.height /= 2;
5622 rect.origin.x = 18 - rect.size.width / 2;
5623 rect.origin.y = 18 - rect.size.height / 2;
5625 [icon_ drawInRect:rect];
5628 if (badge_ != nil) {
5630 rect.size = [(UIImage *) badge_ size];
5632 rect.size.width /= 4;
5633 rect.size.height /= 4;
5635 rect.origin.x = 23 - rect.size.width / 2;
5636 rect.origin.y = 23 - rect.size.height / 2;
5638 [badge_ drawInRect:rect];
5645 UISetColor(commercial_ ? Purple_ : Black_);
5646 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5648 if (placard_ != nil)
5649 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5652 - (void) drawNormalContentRect:(CGRect)rect {
5653 bool highlighted(highlighted_);
5654 float width([self bounds].size.width);
5658 rect.size = [(UIImage *) icon_ size];
5660 while (rect.size.width > 32 || rect.size.height > 32) {
5661 rect.size.width /= 2;
5662 rect.size.height /= 2;
5665 rect.origin.x = 25 - rect.size.width / 2;
5666 rect.origin.y = 25 - rect.size.height / 2;
5668 [icon_ drawInRect:rect];
5671 if (badge_ != nil) {
5673 rect.size = [(UIImage *) badge_ size];
5675 rect.size.width /= 2;
5676 rect.size.height /= 2;
5678 rect.origin.x = 36 - rect.size.width / 2;
5679 rect.origin.y = 36 - rect.size.height / 2;
5681 [badge_ drawInRect:rect];
5688 UISetColor(commercial_ ? Purple_ : Black_);
5689 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5690 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5693 UISetColor(commercial_ ? Purplish_ : Gray_);
5694 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5696 if (placard_ != nil)
5697 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5700 - (void) drawContentRect:(CGRect)rect {
5702 [self drawSummaryContentRect:rect];
5704 [self drawNormalContentRect:rect];
5709 /* Section Cell {{{ */
5710 @interface SectionCell : CyteTableViewCell <
5711 CyteTableViewCellDelegate
5713 _H<NSString> basic_;
5714 _H<NSString> section_;
5716 _H<NSString> count_;
5718 _H<UISwitch> switch_;
5722 - (void) setSection:(Section *)section editing:(BOOL)editing;
5726 @implementation SectionCell
5728 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5729 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5730 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5731 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5732 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5734 UIView *content([self contentView]);
5735 CGRect bounds([content bounds]);
5737 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5738 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5739 [content addSubview:content_];
5740 [content_ setBackgroundColor:[UIColor whiteColor]];
5742 [content_ setDelegate:self];
5746 - (void) onSwitch:(id)sender {
5747 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5748 if (metadata == nil) {
5749 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5750 [Sections_ setObject:metadata forKey:basic_];
5753 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5757 - (void) setSection:(Section *)section editing:(BOOL)editing {
5758 if (editing != editing_) {
5760 [switch_ removeFromSuperview];
5762 [self addSubview:switch_];
5771 if (section == nil) {
5772 name_ = UCLocalize("ALL_PACKAGES");
5775 basic_ = [section name];
5776 section_ = [section localized];
5778 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5779 count_ = [NSString stringWithFormat:@"%d", [section count]];
5782 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5785 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5786 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5788 [content_ setNeedsDisplay];
5791 - (void) setFrame:(CGRect)frame {
5792 [super setFrame:frame];
5794 CGRect rect([switch_ frame]);
5795 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5798 - (NSString *) accessibilityLabel {
5802 - (void) drawContentRect:(CGRect)rect {
5803 bool highlighted(highlighted_ && !editing_);
5805 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5810 float width(rect.size.width);
5816 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5818 CGSize size = [count_ sizeWithFont:Font14_];
5822 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5828 /* File Table {{{ */
5829 @interface FileTable : CyteViewController <
5830 UITableViewDataSource,
5833 _transient Database *database_;
5834 _H<Package> package_;
5836 _H<NSMutableArray> files_;
5837 _H<UITableView, 2> list_;
5840 - (id) initWithDatabase:(Database *)database;
5841 - (void) setPackage:(Package *)package;
5845 @implementation FileTable
5847 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5848 return files_ == nil ? 0 : [files_ count];
5851 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5855 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5856 static NSString *reuseIdentifier = @"Cell";
5858 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5860 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5861 [cell setFont:[UIFont systemFontOfSize:16]];
5863 [cell setText:[files_ objectAtIndex:indexPath.row]];
5864 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5869 - (NSURL *) navigationURL {
5870 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5874 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5875 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5876 [list_ setRowHeight:24.0f];
5877 [(UITableView *) list_ setDataSource:self];
5878 [list_ setDelegate:self];
5879 [self setView:list_];
5882 - (void) viewDidLoad {
5883 [super viewDidLoad];
5885 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5888 - (void) releaseSubviews {
5894 [super releaseSubviews];
5897 - (id) initWithDatabase:(Database *)database {
5898 if ((self = [super init]) != nil) {
5899 database_ = database;
5903 - (void) setPackage:(Package *)package {
5907 files_ = [NSMutableArray arrayWithCapacity:32];
5909 if (package != nil) {
5911 name_ = [package id];
5913 if (NSArray *files = [package files])
5914 [files_ addObjectsFromArray:files];
5916 if ([files_ count] != 0) {
5917 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5918 [files_ removeObjectAtIndex:0];
5919 [files_ sortUsingSelector:@selector(compareByPath:)];
5921 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5922 [stack addObject:@"/"];
5924 for (int i(0), e([files_ count]); i != e; ++i) {
5925 NSString *file = [files_ objectAtIndex:i];
5926 while (![file hasPrefix:[stack lastObject]])
5927 [stack removeLastObject];
5928 NSString *directory = [stack lastObject];
5929 [stack addObject:[file stringByAppendingString:@"/"]];
5930 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5931 ([stack count] - 2) * 3, "",
5932 [file substringFromIndex:[directory length]]
5941 - (void) reloadData {
5944 [self setPackage:[database_ packageWithName:name_]];
5949 /* Package Controller {{{ */
5950 @interface CYPackageController : CydiaWebViewController <
5951 UIActionSheetDelegate
5953 _transient Database *database_;
5954 _H<Package> package_;
5957 _H<NSMutableArray> buttons_;
5958 _H<UIBarButtonItem> button_;
5961 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5965 @implementation CYPackageController
5967 - (NSURL *) navigationURL {
5968 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5971 /* XXX: this is not safe at all... localization of /fail/ */
5972 - (void) _clickButtonWithName:(NSString *)name {
5973 if ([name isEqualToString:UCLocalize("CLEAR")])
5974 [delegate_ clearPackage:package_];
5975 else if ([name isEqualToString:UCLocalize("INSTALL")])
5976 [delegate_ installPackage:package_];
5977 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5978 [delegate_ installPackage:package_];
5979 else if ([name isEqualToString:UCLocalize("REMOVE")])
5980 [delegate_ removePackage:package_];
5981 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5982 [delegate_ installPackage:package_];
5983 else _assert(false);
5986 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5987 NSString *context([sheet context]);
5989 if ([context isEqualToString:@"modify"]) {
5990 if (button != [sheet cancelButtonIndex]) {
5991 NSString *buttonName = [buttons_ objectAtIndex:button];
5992 [self _clickButtonWithName:buttonName];
5995 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5999 - (bool) _allowJavaScriptPanel {
6004 - (void) _customButtonClicked {
6005 int count([buttons_ count]);
6010 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6012 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6013 [buttons addObjectsFromArray:buttons_];
6015 UIActionSheet *sheet = [[[UIActionSheet alloc]
6018 cancelButtonTitle:nil
6019 destructiveButtonTitle:nil
6020 otherButtonTitles:nil
6023 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6025 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6026 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6028 [sheet setContext:@"modify"];
6030 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6034 // We don't want to allow non-commercial packages to do custom things to the install button,
6035 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6036 - (void) customButtonClicked {
6038 [super customButtonClicked];
6040 [self _customButtonClicked];
6043 - (void) reloadButtonClicked {
6044 // Don't reload a commerical package by tapping the loading button,
6045 // but if it's not an Install button, we should forward it on.
6046 if (![package_ uninstalled])
6047 [self _customButtonClicked];
6050 - (void) applyLoadingTitle {
6051 // Don't show "Loading" as the title. Ever.
6054 - (UIBarButtonItem *) rightButton {
6059 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6060 if ((self = [super init]) != nil) {
6061 database_ = database;
6062 buttons_ = [NSMutableArray arrayWithCapacity:4];
6063 name_ = name == nil ? @"" : [NSString stringWithString:name];
6064 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6068 - (void) reloadData {
6071 package_ = [database_ packageWithName:name_];
6073 [buttons_ removeAllObjects];
6075 if (package_ != nil) {
6076 [(Package *) package_ parse];
6078 commercial_ = [package_ isCommercial];
6080 if ([package_ mode] != nil)
6081 [buttons_ addObject:UCLocalize("CLEAR")];
6082 if ([package_ source] == nil);
6083 else if ([package_ upgradableAndEssential:NO])
6084 [buttons_ addObject:UCLocalize("UPGRADE")];
6085 else if ([package_ uninstalled])
6086 [buttons_ addObject:UCLocalize("INSTALL")];
6088 [buttons_ addObject:UCLocalize("REINSTALL")];
6089 if (![package_ uninstalled])
6090 [buttons_ addObject:UCLocalize("REMOVE")];
6094 switch ([buttons_ count]) {
6095 case 0: title = nil; break;
6096 case 1: title = [buttons_ objectAtIndex:0]; break;
6097 default: title = UCLocalize("MODIFY"); break;
6100 button_ = [[[UIBarButtonItem alloc]
6102 style:UIBarButtonItemStylePlain
6104 action:@selector(customButtonClicked)
6108 - (bool) isLoading {
6109 return commercial_ ? [super isLoading] : false;
6115 /* Package List Controller {{{ */
6116 @interface PackageListController : CyteViewController <
6117 UITableViewDataSource,
6120 _transient Database *database_;
6122 _H<NSArray> packages_;
6123 _H<NSMutableArray> sections_;
6124 _H<UITableView, 2> list_;
6125 _H<NSMutableArray> index_;
6126 _H<NSMutableDictionary> indices_;
6127 _H<NSString> title_;
6128 unsigned reloading_;
6131 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6132 - (void) setDelegate:(id)delegate;
6133 - (void) resetCursor;
6138 @implementation PackageListController
6140 - (NSURL *) referrerURL {
6141 return [self navigationURL];
6144 - (bool) isSummarized {
6148 - (bool) showsSections {
6152 - (void) deselectWithAnimation:(BOOL)animated {
6153 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6156 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6157 CGRect base = [[self view] bounds];
6158 base.size.height -= bounds.size.height;
6159 base.origin = [list_ frame].origin;
6161 [UIView beginAnimations:nil context:NULL];
6162 [UIView setAnimationBeginsFromCurrentState:YES];
6163 [UIView setAnimationCurve:curve];
6164 [UIView setAnimationDuration:duration];
6165 [list_ setFrame:base];
6166 [UIView commitAnimations];
6169 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6170 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6173 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6174 [self resizeForKeyboardBounds:bounds duration:0];
6177 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6178 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6179 *curve = UIViewAnimationCurveEaseInOut;
6181 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6183 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6186 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6189 - (void) keyboardWillShow:(NSNotification *)notification {
6192 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6193 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6195 NSTimeInterval duration;
6196 UIViewAnimationCurve curve;
6197 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6199 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);
6200 UIViewController *base = self;
6201 while ([base parentViewController] != nil)
6202 base = [base parentViewController];
6203 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6204 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6206 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6207 intersection.size.height += CYStatusBarHeight();
6209 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6212 - (void) keyboardWillHide:(NSNotification *)notification {
6213 NSTimeInterval duration;
6214 UIViewAnimationCurve curve;
6215 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6217 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6220 - (void) viewWillAppear:(BOOL)animated {
6221 [super viewWillAppear:animated];
6223 [self resizeForKeyboardBounds:CGRectZero];
6224 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6225 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6228 - (void) viewWillDisappear:(BOOL)animated {
6229 [super viewWillDisappear:animated];
6231 [self resizeForKeyboardBounds:CGRectZero];
6232 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6233 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6236 - (void) viewDidAppear:(BOOL)animated {
6237 [super viewDidAppear:animated];
6238 [self deselectWithAnimation:animated];
6241 - (void) didSelectPackage:(Package *)package {
6242 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6243 [view setDelegate:delegate_];
6244 [[self navigationController] pushViewController:view animated:YES];
6247 #if TryIndexedCollation
6248 + (BOOL) hasIndexedCollation {
6249 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6253 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6254 NSInteger count([sections_ count]);
6255 return count == 0 ? 1 : count;
6258 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6259 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6261 return [[sections_ objectAtIndex:section] name];
6264 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6265 if ([sections_ count] == 0)
6267 return [[sections_ objectAtIndex:section] count];
6270 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6271 @synchronized (database_) {
6272 if ([database_ era] != era_)
6275 Section *section([sections_ objectAtIndex:[path section]]);
6276 NSInteger row([path row]);
6277 Package *package([packages_ objectAtIndex:([section row] + row)]);
6278 return [[package retain] autorelease];
6281 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6282 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6284 cell = [[[PackageCell alloc] init] autorelease];
6286 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6287 [cell setPackage:package asSummary:[self isSummarized]];
6291 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6292 Package *package([self packageAtIndexPath:path]);
6293 package = [database_ packageWithName:[package id]];
6294 [self didSelectPackage:package];
6297 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6298 if (![self showsSections])
6304 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6305 #if TryIndexedCollation
6306 if ([[self class] hasIndexedCollation]) {
6307 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6314 - (void) updateHeight {
6315 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6318 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6319 if ((self = [super init]) != nil) {
6320 database_ = database;
6321 title_ = [title copy];
6322 [[self navigationItem] setTitle:title_];
6327 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6328 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6329 [self setView:view];
6331 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6332 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6333 [view addSubview:list_];
6335 // XXX: is 20 the most optimal number here?
6336 [list_ setSectionIndexMinimumDisplayRowCount:20];
6338 [(UITableView *) list_ setDataSource:self];
6339 [list_ setDelegate:self];
6341 [self updateHeight];
6344 - (void) releaseSubviews {
6352 [super releaseSubviews];
6355 - (void) setDelegate:(id)delegate {
6356 delegate_ = delegate;
6359 - (bool) shouldYield {
6363 - (bool) shouldBlock {
6367 - (NSMutableArray *) _reloadPackages {
6368 @synchronized (database_) {
6369 era_ = [database_ era];
6370 NSArray *packages([database_ packages]);
6372 return [NSMutableArray arrayWithArray:packages];
6375 - (void) _reloadData {
6376 if (reloading_ != 0) {
6384 if ([self shouldYield]) {
6388 if (![self shouldBlock])
6391 hud = [delegate_ addProgressHUD];
6392 [hud setText:UCLocalize("LOADING")];
6396 packages = [self yieldToSelector:@selector(_reloadPackages)];
6399 [delegate_ removeProgressHUD:hud];
6400 } while (reloading_ == 2);
6402 packages = [self _reloadPackages];
6405 @synchronized (database_) {
6406 if (era_ != [database_ era])
6410 packages_ = packages;
6412 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6413 sections_ = [NSMutableArray arrayWithCapacity:16];
6415 Section *section = nil;
6417 #if TryIndexedCollation
6418 if ([[self class] hasIndexedCollation]) {
6419 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6421 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6422 NSArray *titles = [collation sectionIndexTitles];
6425 _profile(PackageTable$reloadData$Section)
6426 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6430 _profile(PackageTable$reloadData$Section$Package)
6431 package = [packages_ objectAtIndex:offset];
6432 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6435 while (secidx < index) {
6438 _profile(PackageTable$reloadData$Section$Allocate)
6439 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6442 _profile(PackageTable$reloadData$Section$Add)
6443 [sections_ addObject:section];
6447 [section addToCount];
6453 index_ = [NSMutableArray arrayWithCapacity:32];
6455 bool sectioned([self showsSections]);
6457 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6458 [sections_ addObject:section];
6461 _profile(PackageTable$reloadData$Section)
6462 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6466 _profile(PackageTable$reloadData$Section$Package)
6467 package = [packages_ objectAtIndex:offset];
6468 index = [package index];
6471 if (sectioned && (section == nil || [section index] != index)) {
6472 _profile(PackageTable$reloadData$Section$Allocate)
6473 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6476 [index_ addObject:[section name]];
6477 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6479 _profile(PackageTable$reloadData$Section$Add)
6480 [sections_ addObject:section];
6484 [section addToCount];
6489 [self updateHeight];
6491 _profile(PackageTable$reloadData$List)
6492 [(UITableView *) list_ setDataSource:self];
6497 - (void) reloadData {
6500 if ([self shouldYield])
6501 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6506 - (void) resetCursor {
6507 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6510 - (void) clearData {
6511 [self updateHeight];
6513 [list_ setDataSource:nil];
6521 /* Filtered Package List Controller {{{ */
6522 @interface FilteredPackageListController : PackageListController {
6525 _H<NSObject> object_;
6528 - (void) setObject:(id)object;
6529 - (void) setObject:(id)object forFilter:(SEL)filter;
6532 - (void) setFilter:(SEL)filter;
6534 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6538 @implementation FilteredPackageListController
6544 - (void) setFilter:(SEL)filter {
6545 @synchronized (self) {
6548 /* XXX: this is an unsafe optimization of doomy hell */
6549 Method method(class_getInstanceMethod([Package class], filter));
6550 _assert(method != NULL);
6551 imp_ = method_getImplementation(method);
6552 _assert(imp_ != NULL);
6555 - (void) setObject:(id)object {
6556 @synchronized (self) {
6560 - (void) setObject:(id)object forFilter:(SEL)filter {
6561 @synchronized (self) {
6562 [self setFilter:filter];
6563 [self setObject:object];
6566 - (NSMutableArray *) _reloadPackages {
6567 @synchronized (database_) {
6568 era_ = [database_ era];
6569 NSArray *packages([database_ packages]);
6571 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6575 _H<NSObject> object;
6577 @synchronized (self) {
6583 _profile(PackageTable$reloadData$Filter)
6584 for (Package *package in packages)
6585 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6586 [filtered addObject:package];
6592 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6593 if ((self = [super initWithDatabase:database title:title]) != nil) {
6594 [self setFilter:filter];
6595 [self setObject:object];
6602 /* Home Controller {{{ */
6603 @interface HomeController : CydiaWebViewController {
6604 CFRunLoopRef runloop_;
6605 SCNetworkReachabilityRef reachability_;
6610 @implementation HomeController
6612 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6613 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6617 if ((self = [super init]) != nil) {
6618 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6621 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6622 if (reachability_ != NULL) {
6623 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6624 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6626 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6627 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6634 if (reachability_ != NULL && runloop_ != NULL)
6635 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6639 - (NSURL *) navigationURL {
6640 return [NSURL URLWithString:@"cydia://home"];
6643 - (void) aboutButtonClicked {
6644 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6646 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6647 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6648 [alert setCancelButtonIndex:0];
6651 @"Copyright \u00a9 2008-2011\n"
6654 "Jay Freeman (saurik)\n"
6655 "saurik@saurik.com\n"
6656 "http://www.saurik.com/"
6662 - (UIBarButtonItem *) leftButton {
6663 return [[[UIBarButtonItem alloc]
6664 initWithTitle:UCLocalize("ABOUT")
6665 style:UIBarButtonItemStylePlain
6667 action:@selector(aboutButtonClicked)
6673 /* Manage Controller {{{ */
6674 @interface ManageController : CydiaWebViewController {
6677 - (void) queueStatusDidChange;
6681 @implementation ManageController
6684 if ((self = [super init]) != nil) {
6685 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6689 - (NSURL *) navigationURL {
6690 return [NSURL URLWithString:@"cydia://manage"];
6693 - (UIBarButtonItem *) leftButton {
6694 return [[[UIBarButtonItem alloc]
6695 initWithTitle:UCLocalize("SETTINGS")
6696 style:UIBarButtonItemStylePlain
6698 action:@selector(settingsButtonClicked)
6702 - (void) settingsButtonClicked {
6703 [delegate_ showSettings];
6706 - (void) queueButtonClicked {
6710 - (UIBarButtonItem *) rightButton {
6711 return Queuing_ ? [[[UIBarButtonItem alloc]
6712 initWithTitle:UCLocalize("QUEUE")
6713 style:UIBarButtonItemStyleDone
6715 action:@selector(queueButtonClicked)
6716 ] autorelease] : nil;
6719 - (void) queueStatusDidChange {
6720 [self applyRightButton];
6723 - (bool) isLoading {
6724 return !Queuing_ && [super isLoading];
6730 /* Refresh Bar {{{ */
6731 @interface RefreshBar : UINavigationBar {
6732 _H<UIProgressIndicator> indicator_;
6733 _H<UITextLabel> prompt_;
6734 _H<UIProgressBar> progress_;
6735 _H<UINavigationButton> cancel_;
6740 @implementation RefreshBar
6742 - (void) positionViews {
6743 CGRect frame = [cancel_ frame];
6744 frame.size = [cancel_ sizeThatFits:frame.size];
6745 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6746 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6747 [cancel_ setFrame:frame];
6749 CGSize prgsize = {75, 100};
6751 [self frame].size.width - prgsize.width - 10,
6752 ([self frame].size.height - prgsize.height) / 2
6754 [progress_ setFrame:prgrect];
6756 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6757 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6758 CGRect indrect = {{indoffset, indoffset}, indsize};
6759 [indicator_ setFrame:indrect];
6761 CGSize prmsize = {215, indsize.height + 4};
6763 indoffset * 2 + indsize.width,
6764 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6766 [prompt_ setFrame:prmrect];
6769 - (void) setFrame:(CGRect)frame {
6770 [super setFrame:frame];
6771 [self positionViews];
6774 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6775 if ((self = [super initWithFrame:frame]) != nil) {
6776 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6778 [self setBarStyle:UIBarStyleBlack];
6780 UIBarStyle barstyle([self _barStyle:NO]);
6781 bool ugly(barstyle == UIBarStyleDefault);
6783 UIProgressIndicatorStyle style = ugly ?
6784 UIProgressIndicatorStyleMediumBrown :
6785 UIProgressIndicatorStyleMediumWhite;
6787 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6788 [(UIProgressIndicator *) indicator_ setStyle:style];
6789 [indicator_ startAnimation];
6790 [self addSubview:indicator_];
6792 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6793 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6794 [prompt_ setBackgroundColor:[UIColor clearColor]];
6795 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6796 [self addSubview:prompt_];
6798 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6799 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6800 [(UIProgressBar *) progress_ setStyle:0];
6801 [self addSubview:progress_];
6803 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6804 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6805 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6806 [cancel_ setBarStyle:barstyle];
6808 [self positionViews];
6812 - (void) setCancellable:(bool)cancellable {
6814 [self addSubview:cancel_];
6816 [cancel_ removeFromSuperview];
6820 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6821 [progress_ setProgress:0];
6825 [self setCancellable:NO];
6828 - (void) setPrompt:(NSString *)prompt {
6829 [prompt_ setText:prompt];
6832 - (void) setProgress:(float)progress {
6833 [progress_ setProgress:progress];
6839 /* Cydia Navigation Controller Interface {{{ */
6840 @interface UINavigationController (Cydia)
6842 - (NSArray *) navigationURLCollection;
6843 - (void) unloadData;
6848 /* Cydia Tab Bar Controller {{{ */
6849 @interface CYTabBarController : UITabBarController <
6850 UITabBarControllerDelegate,
6853 _transient Database *database_;
6854 _H<RefreshBar, 1> refreshbar_;
6858 // XXX: ok, "updatedelegate_"?...
6859 _transient NSObject<CydiaDelegate> *updatedelegate_;
6861 _H<UIViewController> remembered_;
6862 _transient UIViewController *transient_;
6865 - (NSArray *) navigationURLCollection;
6866 - (void) dropBar:(BOOL)animated;
6867 - (void) beginUpdate;
6868 - (void) raiseBar:(BOOL)animated;
6870 - (void) unloadData;
6874 @implementation CYTabBarController
6876 - (void) didReceiveMemoryWarning {
6877 [super didReceiveMemoryWarning];
6879 // presenting a UINavigationController on 2.x does not update its transitionView
6880 // it thereby will not allow its topViewController to be unloaded by memory pressure
6881 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6882 UIViewController *selected([self selectedViewController]);
6883 for (UINavigationController *controller in [self viewControllers])
6884 if (controller != selected)
6885 if (UIViewController *top = [controller topViewController])
6890 - (void) setUnselectedViewController:(UIViewController *)transient {
6891 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6892 if (transient != nil) {
6893 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6894 [self setSelectedIndex:0];
6898 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6899 if (transient != nil) {
6900 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6901 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6902 transient = navigation;
6904 if (transient_ == nil)
6905 remembered_ = [controllers objectAtIndex:0];
6906 transient_ = transient;
6907 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6908 [controllers replaceObjectAtIndex:0 withObject:transient_];
6909 [self setSelectedIndex:0];
6910 [self setViewControllers:controllers];
6911 [self concealTabBarSelection];
6912 } else if (remembered_ != nil) {
6913 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6914 transient_ = transient;
6915 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6917 [self setViewControllers:controllers];
6918 [self revealTabBarSelection];
6922 - (UIViewController *) unselectedViewController {
6926 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6927 if ([self unselectedViewController])
6928 [self setUnselectedViewController:nil];
6930 // presenting a UINavigationController on 2.x does not update its transitionView
6931 // if this view was unloaded, the tranitionView may currently be presenting nothing
6932 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6933 UINavigationController *navigation((UINavigationController *) viewController);
6934 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6935 [navigation popViewControllerAnimated:NO];
6939 - (NSArray *) navigationURLCollection {
6940 NSMutableArray *items([NSMutableArray array]);
6942 // XXX: Should this deal with transient view controllers?
6943 for (id navigation in [self viewControllers]) {
6944 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6946 [items addObject:stack];
6952 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6953 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6954 [self setUnselectedViewController:nil];
6956 [super dismissModalViewControllerAnimated:YES];
6959 - (void) unloadData {
6962 for (UINavigationController *controller in [self viewControllers])
6963 [controller unloadData];
6965 if (UIViewController *selected = [self selectedViewController])
6966 [selected reloadData];
6968 if (UIViewController *unselected = [self unselectedViewController]) {
6969 [unselected unloadData];
6970 [unselected reloadData];
6975 [[NSNotificationCenter defaultCenter] removeObserver:self];
6980 - (id) initWithDatabase:(Database *)database {
6981 if ((self = [super init]) != nil) {
6982 database_ = database;
6983 [self setDelegate:self];
6985 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6986 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6988 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6992 - (void) setUpdate:(NSDate *)date {
6996 - (void) beginUpdate {
6997 [(RefreshBar *) refreshbar_ start];
7000 [updatedelegate_ retainNetworkActivityIndicator];
7004 detachNewThreadSelector:@selector(performUpdate)
7010 - (void) performUpdate {
7011 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7014 status.setDelegate(self);
7015 [database_ updateWithStatus:status];
7018 performSelectorOnMainThread:@selector(completeUpdate)
7026 - (void) stopUpdateWithSelector:(SEL)selector {
7028 [updatedelegate_ releaseNetworkActivityIndicator];
7030 [self raiseBar:YES];
7033 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7036 - (void) completeUpdate {
7039 [self stopUpdateWithSelector:@selector(reloadData)];
7042 - (void) cancelUpdate {
7043 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7046 - (void) cancelPressed {
7047 [self cancelUpdate];
7054 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7055 [refreshbar_ setPrompt:[event compoundMessage]];
7058 - (bool) isProgressCancelled {
7062 - (void) setProgressCancellable:(NSNumber *)cancellable {
7063 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7066 - (void) setProgressPercent:(NSNumber *)percent {
7067 [refreshbar_ setProgress:[percent floatValue]];
7070 - (void) setProgressStatus:(NSDictionary *)status {
7072 [self setProgressPercent:[status objectForKey:@"Percent"]];
7075 - (void) setUpdateDelegate:(id)delegate {
7076 updatedelegate_ = delegate;
7079 - (UIView *) transitionView {
7080 if ([self respondsToSelector:@selector(_transitionView)])
7081 return [self _transitionView];
7083 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7086 - (void) dropBar:(BOOL)animated {
7091 UIView *transition([self transitionView]);
7092 [[self view] addSubview:refreshbar_];
7094 CGRect barframe([refreshbar_ frame]);
7096 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7097 barframe.origin.y = CYStatusBarHeight();
7099 barframe.origin.y = 0;
7101 [refreshbar_ setFrame:barframe];
7104 [UIView beginAnimations:nil context:NULL];
7106 CGRect viewframe = [transition frame];
7107 viewframe.origin.y += barframe.size.height;
7108 viewframe.size.height -= barframe.size.height;
7109 [transition setFrame:viewframe];
7112 [UIView commitAnimations];
7114 // Ensure bar has the proper width for our view, it might have changed
7115 barframe.size.width = viewframe.size.width;
7116 [refreshbar_ setFrame:barframe];
7119 - (void) raiseBar:(BOOL)animated {
7124 UIView *transition([self transitionView]);
7125 [refreshbar_ removeFromSuperview];
7127 CGRect barframe([refreshbar_ frame]);
7130 [UIView beginAnimations:nil context:NULL];
7132 CGRect viewframe = [transition frame];
7133 viewframe.origin.y -= barframe.size.height;
7134 viewframe.size.height += barframe.size.height;
7135 [transition setFrame:viewframe];
7138 [UIView commitAnimations];
7141 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7142 bool dropped(dropped_);
7147 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7153 - (void) statusBarFrameChanged:(NSNotification *)notification {
7163 /* Cydia Navigation Controller Implementation {{{ */
7164 @implementation UINavigationController (Cydia)
7166 - (NSArray *) navigationURLCollection {
7167 NSMutableArray *stack([NSMutableArray array]);
7169 for (CyteViewController *controller in [self viewControllers]) {
7170 NSString *url = [[controller navigationURL] absoluteString];
7172 [stack addObject:url];
7178 - (void) reloadData {
7181 UIViewController *visible([self visibleViewController]);
7183 [visible reloadData];
7185 // on the iPad, this view controller is ALSO visible. :(
7187 if (UIViewController *top = [self topViewController])
7192 - (void) unloadData {
7193 for (CyteViewController *page in [self viewControllers])
7202 /* Cydia:// Protocol {{{ */
7203 @interface CydiaURLProtocol : NSURLProtocol {
7208 @implementation CydiaURLProtocol
7210 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7211 NSURL *url([request URL]);
7215 NSString *scheme([[url scheme] lowercaseString]);
7216 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7218 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7224 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7228 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7229 id<NSURLProtocolClient> client([self client]);
7231 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7233 NSData *data(UIImagePNGRepresentation(icon));
7235 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7236 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7237 [client URLProtocol:self didLoadData:data];
7238 [client URLProtocolDidFinishLoading:self];
7242 - (void) startLoading {
7243 id<NSURLProtocolClient> client([self client]);
7244 NSURLRequest *request([self request]);
7246 NSURL *url([request URL]);
7247 NSString *href([url absoluteString]);
7248 NSString *scheme([[url scheme] lowercaseString]);
7252 if ([scheme isEqualToString:@"cydia"])
7253 path = [href substringFromIndex:8];
7254 else if ([scheme isEqualToString:@"about"])
7255 path = [href substringFromIndex:12];
7256 else _assert(false);
7258 NSRange slash([path rangeOfString:@"/"]);
7261 if (slash.location == NSNotFound) {
7265 command = [path substringToIndex:slash.location];
7266 path = [path substringFromIndex:(slash.location + 1)];
7269 Database *database([Database sharedInstance]);
7271 if ([command isEqualToString:@"package-icon"]) {
7274 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7275 Package *package([database packageWithName:path]);
7279 UIImage *icon([package icon]);
7280 [self _returnPNGWithImage:icon forRequest:request];
7281 } else if ([command isEqualToString:@"uikit-image"]) {
7284 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7285 UIImage *icon(_UIImageWithName(path));
7286 [self _returnPNGWithImage:icon forRequest:request];
7287 } else if ([command isEqualToString:@"section-icon"]) {
7290 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7291 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7293 icon = [UIImage applicationImageNamed:@"unknown.png"];
7294 [self _returnPNGWithImage:icon forRequest:request];
7296 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7300 - (void) stopLoading {
7306 /* Section Controller {{{ */
7307 @interface SectionController : FilteredPackageListController {
7308 _H<IndirectDelegate, 1> indirect_;
7309 _H<CydiaObject> cydia_;
7310 _H<NSString> section_;
7311 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7314 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7318 @implementation SectionController
7320 - (NSURL *) referrerURL {
7321 NSString *name = section_;
7325 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7328 - (NSURL *) navigationURL {
7329 NSString *name = section_;
7333 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7336 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7339 title = UCLocalize("ALL_PACKAGES");
7340 else if (![name isEqual:@""])
7341 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7343 title = UCLocalize("NO_SECTION");
7345 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7346 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7347 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7352 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7353 return [super numberOfSectionsInTableView:list] + 1;
7356 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7357 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7360 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7361 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7364 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7365 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7368 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7369 if ([path section] != 0)
7370 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7372 return promoted_[[path row]];
7375 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7376 if ([path section] != 0)
7377 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7380 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7381 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7382 return section == 0 ? 0 : section + 1;
7385 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7386 NSURL *url([request URL]);
7390 if ([frame isEqualToString:@"_open"])
7391 [delegate_ openURL:url];
7393 WebFrame *frame(nil);
7394 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7395 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7397 frame = [view mainFrame];
7399 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7401 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7402 [controller setDelegate:delegate_];
7403 [[self navigationController] pushViewController:controller animated:YES];
7409 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7410 return [CydiaWebViewController requestWithHeaders:request];
7413 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7414 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7420 // XXX: this code is horrible. I mean, wtf Jay?
7421 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7422 promoted_.resize(1);
7424 for (unsigned i(0); i != promoted_.size(); ++i) {
7425 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7426 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7427 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7430 cachePolicy:NSURLRequestUseProtocolCachePolicy
7434 [promoted setDelegate:self];
7435 promoted_[i] = promoted;
7440 - (void) setDelegate:(id)delegate {
7441 [super setDelegate:delegate];
7442 [cydia_ setDelegate:delegate];
7445 - (void) releaseSubviews {
7447 [super releaseSubviews];
7452 /* Sections Controller {{{ */
7453 @interface SectionsController : CyteViewController <
7454 UITableViewDataSource,
7457 _transient Database *database_;
7458 _H<NSMutableArray> sections_;
7459 _H<NSMutableArray> filtered_;
7460 _H<UITableView, 2> list_;
7463 - (id) initWithDatabase:(Database *)database;
7464 - (void) editButtonClicked;
7468 @implementation SectionsController
7470 - (NSURL *) navigationURL {
7471 return [NSURL URLWithString:@"cydia://sections"];
7474 - (void) updateNavigationItem {
7475 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7476 if ([sections_ count] == 0) {
7477 [[self navigationItem] setRightBarButtonItem:nil];
7479 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7480 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7482 action:@selector(editButtonClicked)
7483 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7487 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7488 [super setEditing:editing animated:animated];
7493 [delegate_ updateData];
7495 [self updateNavigationItem];
7498 - (void) viewDidAppear:(BOOL)animated {
7499 [super viewDidAppear:animated];
7500 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7503 - (void) viewWillDisappear:(BOOL)animated {
7504 [super viewWillDisappear:animated];
7505 [self setEditing:NO];
7508 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7509 Section *section = nil;
7510 int index = [indexPath row];
7511 if (![self isEditing]) {
7514 section = [filtered_ objectAtIndex:index];
7516 section = [sections_ objectAtIndex:index];
7521 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7522 if ([self isEditing])
7523 return [sections_ count];
7525 return [filtered_ count] + 1;
7528 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7532 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7533 static NSString *reuseIdentifier = @"SectionCell";
7535 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7537 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7539 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7544 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7545 if ([self isEditing])
7548 Section *section = [self sectionAtIndexPath:indexPath];
7550 SectionController *controller = [[[SectionController alloc]
7551 initWithDatabase:database_
7552 section:[section name]
7554 [controller setDelegate:delegate_];
7556 [[self navigationController] pushViewController:controller animated:YES];
7560 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7561 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7562 [list_ setRowHeight:45.0f];
7563 [(UITableView *) list_ setDataSource:self];
7564 [list_ setDelegate:self];
7565 [self setView:list_];
7568 - (void) viewDidLoad {
7569 [super viewDidLoad];
7571 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7574 - (void) releaseSubviews {
7580 [super releaseSubviews];
7583 - (id) initWithDatabase:(Database *)database {
7584 if ((self = [super init]) != nil) {
7585 database_ = database;
7589 - (void) reloadData {
7592 NSArray *packages = [database_ packages];
7594 sections_ = [NSMutableArray arrayWithCapacity:16];
7595 filtered_ = [NSMutableArray arrayWithCapacity:16];
7597 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7600 for (Package *package in packages) {
7601 NSString *name([package section]);
7602 NSString *key(name == nil ? @"" : name);
7606 _profile(SectionsView$reloadData$Section)
7607 section = [sections objectForKey:key];
7608 if (section == nil) {
7609 _profile(SectionsView$reloadData$Section$Allocate)
7610 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7611 [sections setObject:section forKey:key];
7616 [section addToCount];
7618 _profile(SectionsView$reloadData$Filter)
7619 if (![package valid] || ![package visible])
7627 [sections_ addObjectsFromArray:[sections allValues]];
7629 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7631 for (Section *section in (id) sections_) {
7632 size_t count([section row]);
7636 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7637 [section setCount:count];
7638 [filtered_ addObject:section];
7641 [self updateNavigationItem];
7646 - (void) editButtonClicked {
7647 [self setEditing:![self isEditing] animated:YES];
7653 /* Changes Controller {{{ */
7654 @interface ChangesController : CyteViewController <
7655 UITableViewDataSource,
7658 _transient Database *database_;
7660 _H<NSArray> packages_;
7661 _H<NSMutableArray> sections_;
7662 _H<UITableView, 2> list_;
7663 _H<CyteWebView, 1> dickbar_;
7665 _H<IndirectDelegate, 1> indirect_;
7666 _H<CydiaObject> cydia_;
7669 - (id) initWithDatabase:(Database *)database;
7673 @implementation ChangesController
7675 - (NSURL *) navigationURL {
7676 return [NSURL URLWithString:@"cydia://changes"];
7679 - (void) viewDidAppear:(BOOL)animated {
7680 [super viewDidAppear:animated];
7681 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7684 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7685 NSInteger count([sections_ count]);
7686 return count == 0 ? 1 : count;
7689 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7690 if ([sections_ count] == 0)
7692 return [[sections_ objectAtIndex:section] name];
7695 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7696 if ([sections_ count] == 0)
7698 return [[sections_ objectAtIndex:section] count];
7701 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7702 @synchronized (database_) {
7703 if ([database_ era] != era_)
7706 NSUInteger sectionIndex([path section]);
7707 if (sectionIndex >= [sections_ count])
7709 Section *section([sections_ objectAtIndex:sectionIndex]);
7710 NSInteger row([path row]);
7711 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7714 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7715 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7717 cell = [[[PackageCell alloc] init] autorelease];
7719 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7720 [cell setPackage:package asSummary:false];
7724 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7725 Package *package([self packageAtIndexPath:path]);
7726 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7727 [view setDelegate:delegate_];
7728 [[self navigationController] pushViewController:view animated:YES];
7732 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7733 NSString *context([alert context]);
7735 if ([context isEqualToString:@"norefresh"])
7736 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7739 - (void) refreshButtonClicked {
7740 if (IsReachable("cydia.saurik.com")) {
7741 [delegate_ beginUpdate];
7742 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7744 UIAlertView *alert = [[[UIAlertView alloc]
7745 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7746 message:@"Host Unreachable" // XXX: Localize
7748 cancelButtonTitle:UCLocalize("OK")
7749 otherButtonTitles:nil
7752 [alert setContext:@"norefresh"];
7757 - (void) upgradeButtonClicked {
7758 [delegate_ distUpgrade];
7759 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7763 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7764 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7765 [self setView:view];
7767 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7768 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7769 [list_ setRowHeight:73];
7770 [(UITableView *) list_ setDataSource:self];
7771 [list_ setDelegate:self];
7772 [view addSubview:list_];
7774 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7775 CGRect dickframe([view bounds]);
7776 dickframe.size.height = 44;
7778 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7779 [dickbar_ setDelegate:self];
7780 [view addSubview:dickbar_];
7782 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7783 [dickbar_ setScalesPageToFit:YES];
7785 UIWebDocumentView *document([dickbar_ _documentView]);
7786 [document setBackgroundColor:[UIColor clearColor]];
7787 [document setDrawsBackground:NO];
7789 WebView *webview([document webView]);
7790 [webview setShouldUpdateWhileOffscreen:NO];
7792 UIScrollView *scroller([dickbar_ scrollView]);
7793 [scroller setScrollingEnabled:NO];
7794 [scroller setFixedBackgroundPattern:YES];
7795 [scroller setBackgroundColor:[UIColor clearColor]];
7797 WebPreferences *preferences([webview preferences]);
7798 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7799 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7800 [preferences setOfflineWebApplicationCacheEnabled:YES];
7802 [dickbar_ loadRequest:[NSURLRequest
7803 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7804 cachePolicy:NSURLRequestUseProtocolCachePolicy
7808 UIEdgeInsets inset = {44, 0, 0, 0};
7809 [list_ setContentInset:inset];
7811 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7815 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7816 NSURL *url([request URL]);
7820 if ([frame isEqualToString:@"_open"])
7821 [delegate_ openURL:url];
7823 WebFrame *frame(nil);
7824 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7825 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7827 frame = [view mainFrame];
7829 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7831 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7832 [controller setDelegate:delegate_];
7833 [[self navigationController] pushViewController:controller animated:YES];
7839 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7840 return [CydiaWebViewController requestWithHeaders:request];
7843 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7844 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7847 - (void) setDelegate:(id)delegate {
7848 [super setDelegate:delegate];
7849 [cydia_ setDelegate:delegate];
7852 - (void) viewDidLoad {
7853 [super viewDidLoad];
7855 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7858 - (void) releaseSubviews {
7865 [super releaseSubviews];
7868 - (id) initWithDatabase:(Database *)database {
7869 if ((self = [super init]) != nil) {
7870 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7871 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7872 database_ = database;
7876 - (NSMutableArray *) _reloadPackages {
7877 @synchronized (database_) {
7878 era_ = [database_ era];
7879 NSArray *packages([database_ packages]);
7881 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7884 _profile(ChangesController$_reloadPackages$Filter)
7885 for (Package *package in packages)
7886 if ([package upgradableAndEssential:YES] || [package visible])
7887 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7890 _profile(ChangesController$_reloadPackages$radixSort)
7891 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7898 - (void) _reloadData {
7903 UIProgressHUD *hud([delegate_ addProgressHUD]);
7904 [hud setText:UCLocalize("LOADING")];
7905 //NSLog(@"HUD:%@::%@", delegate_, hud);
7906 packages = [self yieldToSelector:@selector(_reloadPackages)];
7907 [delegate_ removeProgressHUD:hud];
7909 packages = [self _reloadPackages];
7912 @synchronized (database_) {
7913 if (era_ != [database_ era])
7916 packages_ = packages;
7917 sections_ = [NSMutableArray arrayWithCapacity:16];
7919 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7920 Section *ignored = nil;
7921 Section *section = nil;
7925 bool unseens = false;
7927 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7929 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7930 Package *package = [packages_ objectAtIndex:offset];
7932 BOOL uae = [package upgradableAndEssential:YES];
7936 time_t seen([package seen]);
7938 if (section == nil || last != seen) {
7942 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7945 _profile(ChangesController$reloadData$Allocate)
7946 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7947 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7948 [sections_ addObject:section];
7952 [section addToCount];
7953 } else if ([package ignored]) {
7954 if (ignored == nil) {
7955 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7957 [ignored addToCount];
7960 [upgradable addToCount];
7965 CFRelease(formatter);
7968 Section *last = [sections_ lastObject];
7969 size_t count = [last count];
7970 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7971 [sections_ removeLastObject];
7974 if ([ignored count] != 0)
7975 [sections_ insertObject:ignored atIndex:0];
7977 [sections_ insertObject:upgradable atIndex:0];
7981 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7982 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7983 style:UIBarButtonItemStylePlain
7985 action:@selector(upgradeButtonClicked)
7986 ] autorelease]) animated:YES];
7988 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7989 initWithTitle:UCLocalize("REFRESH")
7990 style:UIBarButtonItemStylePlain
7992 action:@selector(refreshButtonClicked)
7993 ] autorelease]) animated:YES];
7998 - (void) reloadData {
8000 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
8005 /* Search Controller {{{ */
8006 @interface SearchController : FilteredPackageListController <
8009 _H<UISearchBar, 1> search_;
8013 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8014 - (void) reloadData;
8018 @implementation SearchController
8020 - (NSURL *) referrerURL {
8021 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8024 - (NSURL *) navigationURL {
8025 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8026 return [NSURL URLWithString:@"cydia://search"];
8028 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8031 - (NSArray *) termsForQuery:(NSString *)query {
8032 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8033 for (NSString *component in [query componentsSeparatedByString:@" "])
8034 if ([component length] != 0)
8035 [terms addObject:component];
8040 - (void) useSearch {
8041 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8046 - (void) viewWillAppear:(BOOL)animated {
8047 [super viewWillAppear:animated];
8049 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
8053 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8054 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8059 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8060 [search_ resignFirstResponder];
8064 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8065 [search_ setText:@""];
8066 [self searchBarButtonClicked:searchBar];
8069 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8070 [self searchBarButtonClicked:searchBar];
8073 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8074 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8078 - (bool) shouldYield {
8082 - (bool) shouldBlock {
8083 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8086 - (bool) isSummarized {
8087 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8090 - (bool) showsSections {
8094 - (NSMutableArray *) _reloadPackages {
8095 NSMutableArray *packages([super _reloadPackages]);
8096 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8097 [packages radixSortUsingSelector:@selector(rank)];
8101 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8102 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8103 search_ = [[[UISearchBar alloc] init] autorelease];
8104 [search_ setDelegate:self];
8107 [search_ setText:query];
8111 - (void) viewDidAppear:(BOOL)animated {
8112 [super viewDidAppear:animated];
8114 if (!searchloaded_) {
8115 searchloaded_ = YES;
8116 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8117 [search_ layoutSubviews];
8118 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8120 UITextField *textField;
8121 if ([search_ respondsToSelector:@selector(searchField)])
8122 textField = [search_ searchField];
8124 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8126 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8127 [textField setEnablesReturnKeyAutomatically:NO];
8128 [[self navigationItem] setTitleView:textField];
8132 - (void) reloadData {
8133 id object([search_ text]);
8134 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8135 object = [self termsForQuery:object];
8137 [self setObject:object];
8143 - (void) didSelectPackage:(Package *)package {
8144 [search_ resignFirstResponder];
8145 [super didSelectPackage:package];
8150 /* Package Settings Controller {{{ */
8151 @interface PackageSettingsController : CyteViewController <
8152 UITableViewDataSource,
8155 _transient Database *database_;
8157 _H<Package> package_;
8158 _H<UITableView, 2> table_;
8159 _H<UISwitch> subscribedSwitch_;
8160 _H<UISwitch> ignoredSwitch_;
8161 _H<UITableViewCell> subscribedCell_;
8162 _H<UITableViewCell> ignoredCell_;
8165 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8169 @implementation PackageSettingsController
8171 - (NSURL *) navigationURL {
8172 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8175 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8176 if (package_ == nil)
8179 if ([package_ installed] == nil)
8185 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8186 if (package_ == nil)
8189 // both sections contain just one item right now.
8193 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8197 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8199 return UCLocalize("SHOW_ALL_CHANGES_EX");
8201 return UCLocalize("IGNORE_UPGRADES_EX");
8204 - (void) onSubscribed:(id)control {
8205 bool value([control isOn]);
8206 if (package_ == nil)
8208 if ([package_ setSubscribed:value])
8209 [delegate_ updateData];
8212 - (void) _updateIgnored {
8213 const char *package([name_ UTF8String]);
8214 bool on([ignoredSwitch_ isOn]);
8216 pid_t pid(ExecFork());
8218 FILE *dpkg(popen("dpkg --set-selections", "w"));
8219 fwrite(package, strlen(package), 1, dpkg);
8222 fwrite(" hold\n", 6, 1, dpkg);
8224 fwrite(" install\n", 9, 1, dpkg);
8235 - (void) onIgnored:(id)control {
8236 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8237 [invocation setTarget:self];
8238 [invocation setSelector:@selector(_updateIgnored)];
8240 [delegate_ reloadDataWithInvocation:invocation];
8243 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8244 if (package_ == nil)
8247 switch ([indexPath section]) {
8248 case 0: return subscribedCell_;
8249 case 1: return ignoredCell_;
8258 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8259 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8260 [self setView:view];
8262 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8263 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8264 [(UITableView *) table_ setDataSource:self];
8265 [table_ setDelegate:self];
8266 [view addSubview:table_];
8268 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8269 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8270 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8272 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8273 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8274 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8276 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8277 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8278 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8279 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8281 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8282 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8283 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8284 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8287 - (void) viewDidLoad {
8288 [super viewDidLoad];
8290 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8293 - (void) releaseSubviews {
8295 subscribedCell_ = nil;
8297 ignoredSwitch_ = nil;
8298 subscribedSwitch_ = nil;
8300 [super releaseSubviews];
8303 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8304 if ((self = [super init]) != nil) {
8305 database_ = database;
8310 - (void) reloadData {
8313 package_ = [database_ packageWithName:name_];
8315 if (package_ != nil) {
8316 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8317 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8318 } // XXX: what now, G?
8320 [table_ reloadData];
8326 /* Installed Controller {{{ */
8327 @interface InstalledController : FilteredPackageListController {
8331 - (id) initWithDatabase:(Database *)database;
8333 - (void) updateRoleButton;
8334 - (void) queueStatusDidChange;
8338 @implementation InstalledController
8340 - (NSURL *) referrerURL {
8341 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8344 - (NSURL *) navigationURL {
8345 return [NSURL URLWithString:@"cydia://installed"];
8348 - (id) initWithDatabase:(Database *)database {
8349 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8350 [self updateRoleButton];
8351 [self queueStatusDidChange];
8356 - (void) queueButtonClicked {
8361 - (void) queueStatusDidChange {
8365 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8366 initWithTitle:UCLocalize("QUEUE")
8367 style:UIBarButtonItemStyleDone
8369 action:@selector(queueButtonClicked)
8372 [[self navigationItem] setLeftBarButtonItem:nil];
8378 - (void) updateRoleButton {
8379 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8380 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8381 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8382 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8384 action:@selector(roleButtonClicked)
8388 - (void) roleButtonClicked {
8389 [self setObject:[NSNumber numberWithBool:expert_]];
8393 [self updateRoleButton];
8399 /* Source Cell {{{ */
8400 @interface SourceCell : CyteTableViewCell <
8401 CyteTableViewCellDelegate
8405 _H<NSString> origin_;
8406 _H<NSString> label_;
8409 - (void) setSource:(Source *)source;
8413 @implementation SourceCell
8415 - (void) _setImage:(NSArray *)data {
8416 if ([url_ isEqual:[data objectAtIndex:0]]) {
8417 icon_ = [data objectAtIndex:1];
8418 [content_ setNeedsDisplay];
8422 - (void) _setSource:(NSURL *) url {
8423 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8425 if (NSData *data = [NSURLConnection
8426 sendSynchronousRequest:[NSURLRequest
8428 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8432 returningResponse:NULL
8435 if (UIImage *image = [UIImage imageWithData:data])
8436 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8441 - (void) setSource:(Source *)source {
8442 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8444 origin_ = [source name];
8445 label_ = [source rooturi];
8447 [content_ setNeedsDisplay];
8449 url_ = [source iconURL];
8450 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8453 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8454 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8455 UIView *content([self contentView]);
8456 CGRect bounds([content bounds]);
8458 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8459 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8460 [content_ setBackgroundColor:[UIColor whiteColor]];
8461 [content addSubview:content_];
8463 [content_ setDelegate:self];
8464 [content_ setOpaque:YES];
8466 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8470 - (NSString *) accessibilityLabel {
8474 - (void) drawContentRect:(CGRect)rect {
8475 bool highlighted(highlighted_);
8476 float width(rect.size.width);
8480 rect.size = [(UIImage *) icon_ size];
8482 while (rect.size.width > 32 || rect.size.height > 32) {
8483 rect.size.width /= 2;
8484 rect.size.height /= 2;
8487 rect.origin.x = 25 - rect.size.width / 2;
8488 rect.origin.y = 25 - rect.size.height / 2;
8490 [icon_ drawInRect:rect];
8498 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8502 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8507 /* Source Controller {{{ */
8508 @interface SourceController : FilteredPackageListController {
8509 _transient Source *source_;
8513 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8517 @implementation SourceController
8519 - (NSURL *) referrerURL {
8520 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8523 - (NSURL *) navigationURL {
8524 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8527 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8528 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8530 key_ = [source key];
8534 - (void) reloadData {
8535 source_ = [database_ sourceWithKey:key_];
8536 key_ = [source_ key];
8537 [self setObject:source_];
8539 [[self navigationItem] setTitle:[source_ label]];
8546 /* Sources Controller {{{ */
8547 @interface SourcesController : CyteViewController <
8548 UITableViewDataSource,
8551 _transient Database *database_;
8554 _H<UITableView, 2> list_;
8555 _H<NSMutableArray> sources_;
8559 _H<UIProgressHUD> hud_;
8562 //NSURLConnection *installer_;
8563 NSURLConnection *trivial_;
8564 NSURLConnection *trivial_bz2_;
8565 NSURLConnection *trivial_gz_;
8566 //NSURLConnection *automatic_;
8571 - (id) initWithDatabase:(Database *)database;
8572 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8576 @implementation SourcesController
8578 - (void) _releaseConnection:(NSURLConnection *)connection {
8579 if (connection != nil) {
8580 [connection cancel];
8581 //[connection setDelegate:nil];
8582 [connection release];
8587 //[self _releaseConnection:installer_];
8588 [self _releaseConnection:trivial_];
8589 [self _releaseConnection:trivial_gz_];
8590 [self _releaseConnection:trivial_bz2_];
8591 //[self _releaseConnection:automatic_];
8596 - (NSURL *) navigationURL {
8597 return [NSURL URLWithString:@"cydia://sources"];
8600 - (void) viewDidAppear:(BOOL)animated {
8601 [super viewDidAppear:animated];
8602 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8605 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8609 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8613 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8614 return [sources_ count];
8617 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8618 @synchronized (database_) {
8619 if ([database_ era] != era_)
8622 NSUInteger index([indexPath row]);
8623 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8626 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8627 static NSString *cellIdentifier = @"SourceCell";
8629 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8630 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8631 [cell setSource:[self sourceAtIndexPath:indexPath]];
8632 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8637 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8638 Source *source = [self sourceAtIndexPath:indexPath];
8639 if (source == nil) return;
8641 SourceController *controller = [[[SourceController alloc]
8642 initWithDatabase:database_
8646 [controller setDelegate:delegate_];
8648 [[self navigationController] pushViewController:controller animated:YES];
8651 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8652 Source *source = [self sourceAtIndexPath:indexPath];
8653 return [source record] != nil;
8656 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8657 if (editingStyle == UITableViewCellEditingStyleDelete) {
8658 Source *source = [self sourceAtIndexPath:indexPath];
8659 if (source == nil) return;
8661 [Sources_ removeObjectForKey:[source key]];
8662 [delegate_ _saveConfig];
8663 [delegate_ reloadDataWithInvocation:nil];
8668 [delegate_ addTrivialSource:href_];
8671 [delegate_ syncData];
8674 - (NSString *) getWarning {
8675 NSString *href(href_);
8676 NSRange colon([href rangeOfString:@"://"]);
8677 if (colon.location != NSNotFound)
8678 href = [href substringFromIndex:(colon.location + 3)];
8679 href = [href stringByAddingPercentEscapes];
8680 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8682 NSURL *url([NSURL URLWithString:href]);
8684 NSStringEncoding encoding;
8685 NSError *error(nil);
8687 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8688 return [warning length] == 0 ? nil : warning;
8692 - (void) _endConnection:(NSURLConnection *)connection {
8693 // XXX: the memory management in this method is horribly awkward
8695 NSURLConnection **field = NULL;
8696 if (connection == trivial_)
8698 else if (connection == trivial_bz2_)
8699 field = &trivial_bz2_;
8700 else if (connection == trivial_gz_)
8701 field = &trivial_gz_;
8702 _assert(field != NULL);
8703 [connection release];
8708 trivial_bz2_ == nil &&
8711 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8713 [delegate_ releaseNetworkActivityIndicator];
8715 [delegate_ removeProgressHUD:hud_];
8719 if (warning != nil) {
8720 UIAlertView *alert = [[[UIAlertView alloc]
8721 initWithTitle:UCLocalize("SOURCE_WARNING")
8724 cancelButtonTitle:UCLocalize("CANCEL")
8726 UCLocalize("ADD_ANYWAY"),
8730 [alert setContext:@"warning"];
8731 [alert setNumberOfRows:1];
8734 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8740 } else if (error_ != nil) {
8741 UIAlertView *alert = [[[UIAlertView alloc]
8742 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8743 message:[error_ localizedDescription]
8745 cancelButtonTitle:UCLocalize("OK")
8746 otherButtonTitles:nil
8749 [alert setContext:@"urlerror"];
8754 UIAlertView *alert = [[[UIAlertView alloc]
8755 initWithTitle:UCLocalize("NOT_REPOSITORY")
8756 message:UCLocalize("NOT_REPOSITORY_EX")
8758 cancelButtonTitle:UCLocalize("OK")
8759 otherButtonTitles:nil
8762 [alert setContext:@"trivial"];
8772 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8773 switch ([response statusCode]) {
8779 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8780 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8782 [self _endConnection:connection];
8785 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8786 [self _endConnection:connection];
8789 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8790 NSURL *url([NSURL URLWithString:href]);
8792 NSMutableURLRequest *request = [NSMutableURLRequest
8794 cachePolicy:NSURLRequestUseProtocolCachePolicy
8798 [request setHTTPMethod:method];
8800 if (Machine_ != NULL)
8801 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8803 if ([url isCydiaSecure]) {
8804 if (UniqueID_ != nil) {
8805 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8806 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8810 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8813 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8814 NSString *context([alert context]);
8816 if ([context isEqualToString:@"source"]) {
8819 NSString *href = [[alert textField] text];
8821 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8823 if (![href hasSuffix:@"/"])
8824 href_ = [href stringByAppendingString:@"/"];
8828 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8829 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8830 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8831 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8835 // XXX: this is stupid
8836 hud_ = [delegate_ addProgressHUD];
8837 [hud_ setText:UCLocalize("VERIFYING_URL")];
8838 [delegate_ retainNetworkActivityIndicator];
8847 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8848 } else if ([context isEqualToString:@"trivial"])
8849 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8850 else if ([context isEqualToString:@"urlerror"])
8851 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8852 else if ([context isEqualToString:@"warning"]) {
8855 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8864 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8869 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8870 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8871 [list_ setRowHeight:53];
8872 [(UITableView *) list_ setDataSource:self];
8873 [list_ setDelegate:self];
8874 [self setView:list_];
8877 - (void) viewDidLoad {
8878 [super viewDidLoad];
8880 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8881 [self updateButtonsForEditingStatusAnimated:NO];
8884 - (void) viewWillDisappear:(BOOL)animated {
8885 [super viewWillAppear:animated];
8887 [list_ setEditing:NO];
8888 [self updateButtonsForEditingStatusAnimated:NO];
8891 - (void) releaseSubviews {
8896 [super releaseSubviews];
8899 - (id) initWithDatabase:(Database *)database {
8900 if ((self = [super init]) != nil) {
8901 database_ = database;
8905 - (void) reloadData {
8908 @synchronized (database_) {
8909 era_ = [database_ era];
8912 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8915 sources_ = [NSMutableArray arrayWithCapacity:16];
8916 [sources_ addObjectsFromArray:[database_ sources]];
8918 [sources_ sortUsingSelector:@selector(compareByName:)];
8921 int count([sources_ count]);
8923 for (int i = 0; i != count; i++) {
8924 if ([[sources_ objectAtIndex:i] record] == nil)
8932 - (void) showAddSourcePrompt {
8933 UIAlertView *alert = [[[UIAlertView alloc]
8934 initWithTitle:UCLocalize("ENTER_APT_URL")
8937 cancelButtonTitle:UCLocalize("CANCEL")
8939 UCLocalize("ADD_SOURCE"),
8943 [alert setContext:@"source"];
8945 [alert setNumberOfRows:1];
8946 [alert addTextFieldWithValue:@"http://" label:@""];
8948 UITextInputTraits *traits = [[alert textField] textInputTraits];
8949 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8950 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8951 [traits setKeyboardType:UIKeyboardTypeURL];
8952 // XXX: UIReturnKeyDone
8953 [traits setReturnKeyType:UIReturnKeyNext];
8958 - (void) addButtonClicked {
8959 [self showAddSourcePrompt];
8962 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8963 BOOL editing([list_ isEditing]);
8965 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8966 initWithTitle:UCLocalize("ADD")
8967 style:UIBarButtonItemStylePlain
8969 action:@selector(addButtonClicked)
8970 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8972 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8973 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8974 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8976 action:@selector(editButtonClicked)
8977 ] autorelease] animated:animated];
8979 if (IsWildcat_ && !editing)
8980 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8981 initWithTitle:UCLocalize("SETTINGS")
8982 style:UIBarButtonItemStylePlain
8984 action:@selector(settingsButtonClicked)
8988 - (void) settingsButtonClicked {
8989 [delegate_ showSettings];
8992 - (void) editButtonClicked {
8993 [list_ setEditing:![list_ isEditing] animated:YES];
8994 [self updateButtonsForEditingStatusAnimated:YES];
9000 /* Settings Controller {{{ */
9001 @interface SettingsController : CyteViewController <
9002 UITableViewDataSource,
9005 _transient Database *database_;
9006 // XXX: ok, "roledelegate_"?...
9007 _transient id roledelegate_;
9008 _H<UITableView, 2> table_;
9009 _H<UISegmentedControl> segment_;
9010 _H<UIView> container_;
9013 - (void) showDoneButton;
9014 - (void) resizeSegmentedControl;
9018 @implementation SettingsController
9021 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9022 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9023 [table_ setDelegate:self];
9024 [(UITableView *) table_ setDataSource:self];
9025 [self setView:table_];
9027 NSArray *items = [NSArray arrayWithObjects:
9029 UCLocalize("HACKER"),
9030 UCLocalize("DEVELOPER"),
9032 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9033 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9034 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9035 [container_ addSubview:segment_];
9038 - (void) viewDidLoad {
9039 [super viewDidLoad];
9041 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9044 if ([Role_ isEqualToString:@"User"]) index = 0;
9045 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9046 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9048 [segment_ setSelectedSegmentIndex:index];
9049 [self showDoneButton];
9052 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9053 [self resizeSegmentedControl];
9056 - (void) releaseSubviews {
9061 [super releaseSubviews];
9064 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9065 if ((self = [super init]) != nil) {
9066 database_ = database;
9067 roledelegate_ = delegate;
9071 - (void) resizeSegmentedControl {
9072 CGFloat width = [[self view] frame].size.width;
9073 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9076 - (void) viewWillAppear:(BOOL)animated {
9077 [super viewWillAppear:animated];
9079 [self resizeSegmentedControl];
9082 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9083 [self resizeSegmentedControl];
9086 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9087 [self resizeSegmentedControl];
9091 NSString *role(nil);
9093 switch ([segment_ selectedSegmentIndex]) {
9094 case 0: role = @"User"; break;
9095 case 1: role = @"Hacker"; break;
9096 case 2: role = @"Developer"; break;
9101 if (![role isEqualToString:Role_]) {
9102 bool rolling(Role_ == nil);
9105 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9109 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9113 [roledelegate_ loadData];
9115 [roledelegate_ updateData];
9119 - (void) segmentChanged:(UISegmentedControl *)control {
9120 [self showDoneButton];
9123 - (void) saveAndClose {
9126 [[self navigationItem] setRightBarButtonItem:nil];
9127 [[self navigationController] dismissModalViewControllerAnimated:YES];
9130 - (void) doneButtonClicked {
9131 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9132 [spinner startAnimating];
9133 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9134 [[self navigationItem] setRightBarButtonItem:spinItem];
9136 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9139 - (void) showDoneButton {
9140 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9141 initWithTitle:UCLocalize("DONE")
9142 style:UIBarButtonItemStyleDone
9144 action:@selector(doneButtonClicked)
9145 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9148 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9149 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9153 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9157 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9158 return nil; // This method is required by the protocol.
9161 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9163 return UCLocalize("ROLE_EX");
9165 return [NSString stringWithFormat:
9166 @"%@: %@\n%@: %@\n%@: %@",
9167 UCLocalize("USER"), UCLocalize("USER_EX"),
9168 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9169 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9174 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9175 return section == 3 ? 44.0f : 0;
9178 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9179 return section == 3 ? container_ : nil;
9182 - (void) reloadData {
9185 [table_ reloadData];
9190 /* Stash Controller {{{ */
9191 @interface StashController : CyteViewController {
9192 _H<UIActivityIndicatorView> spinner_;
9193 _H<UILabel> status_;
9194 _H<UILabel> caption_;
9199 @implementation StashController
9202 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9203 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9204 [self setView:view];
9206 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9208 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9209 CGRect spinrect = [spinner_ frame];
9210 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9211 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9212 [spinner_ setFrame:spinrect];
9213 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9214 [view addSubview:spinner_];
9215 [spinner_ startAnimating];
9218 captrect.size.width = [[self view] frame].size.width;
9219 captrect.size.height = 40.0f;
9220 captrect.origin.x = 0;
9221 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9222 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9223 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9224 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9225 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9226 [caption_ setTextColor:[UIColor whiteColor]];
9227 [caption_ setBackgroundColor:[UIColor clearColor]];
9228 [caption_ setShadowColor:[UIColor blackColor]];
9229 [caption_ setTextAlignment:UITextAlignmentCenter];
9230 [view addSubview:caption_];
9233 statusrect.size.width = [[self view] frame].size.width;
9234 statusrect.size.height = 30.0f;
9235 statusrect.origin.x = 0;
9236 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9237 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9238 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9239 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9240 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9241 [status_ setTextColor:[UIColor whiteColor]];
9242 [status_ setBackgroundColor:[UIColor clearColor]];
9243 [status_ setShadowColor:[UIColor blackColor]];
9244 [status_ setTextAlignment:UITextAlignmentCenter];
9245 [view addSubview:status_];
9248 - (void) releaseSubviews {
9253 [super releaseSubviews];
9259 @interface CYURLCache : SDURLCache {
9264 @implementation CYURLCache
9266 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9269 else if ([event isEqualToString:@"no-cache"])
9271 else if ([event isEqualToString:@"store"])
9273 else if ([event isEqualToString:@"invalid"])
9275 else if ([event isEqualToString:@"memory"])
9277 else if ([event isEqualToString:@"disk"])
9279 else if ([event isEqualToString:@"miss"])
9282 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9286 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9287 if (NSURLResponse *response = [cached response])
9288 if (NSString *mime = [response MIMEType])
9289 if ([mime isEqualToString:@"text/cache-manifest"]) {
9290 NSURL *url([response URL]);
9293 NSLog(@"###: %@", [url absoluteString]);
9296 @synchronized (HostConfig_) {
9297 [CachedURLs_ addObject:url];
9301 [super storeCachedResponse:cached forRequest:request];
9306 @interface Cydia : UIApplication <
9307 ConfirmationControllerDelegate,
9310 UINavigationControllerDelegate,
9311 UITabBarControllerDelegate
9313 _H<UIWindow> window_;
9314 _H<CYTabBarController> tabbar_;
9315 _H<CydiaLoadingViewController> emulated_;
9317 _H<NSMutableArray> essential_;
9318 _H<NSMutableArray> broken_;
9320 Database *database_;
9322 _H<NSURL> starturl_;
9327 _H<StashController> stash_;
9336 @implementation Cydia
9338 - (void) beginUpdate {
9339 [tabbar_ beginUpdate];
9343 return [tabbar_ updating];
9347 if ([broken_ count] != 0) {
9348 int count = [broken_ count];
9350 UIAlertView *alert = [[[UIAlertView alloc]
9351 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9352 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9354 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9356 UCLocalize("TEMPORARY_IGNORE"),
9360 [alert setContext:@"fixhalf"];
9361 [alert setNumberOfRows:2];
9363 } else if (!Ignored_ && [essential_ count] != 0) {
9364 int count = [essential_ count];
9366 UIAlertView *alert = [[[UIAlertView alloc]
9367 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9368 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9370 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9372 UCLocalize("UPGRADE_ESSENTIAL"),
9373 UCLocalize("COMPLETE_UPGRADE"),
9377 [alert setContext:@"upgrade"];
9382 - (void) returnToCydia {
9386 - (void) _saveConfig {
9387 @synchronized (database_) {
9394 NSString *error(nil);
9396 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9398 NSError *error(nil);
9399 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9400 NSLog(@"failure to save metadata data: %@", error);
9405 NSLog(@"failure to serialize metadata: %@", error);
9409 CydiaWriteSources();
9412 // Navigation controller for the queuing badge.
9413 - (UINavigationController *) queueNavigationController {
9414 NSArray *controllers = [tabbar_ viewControllers];
9415 return [controllers objectAtIndex:3];
9418 - (void) unloadData {
9419 [tabbar_ unloadData];
9422 - (void) _updateData {
9426 UINavigationController *navigation = [self queueNavigationController];
9428 id queuedelegate = nil;
9429 if ([[navigation viewControllers] count] > 0)
9430 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9432 [queuedelegate queueStatusDidChange];
9433 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9436 - (void) _refreshIfPossible:(NSDate *)update {
9437 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9439 bool recently = false;
9440 if (update != nil) {
9441 NSTimeInterval interval([update timeIntervalSinceNow]);
9442 if (interval <= 0 && interval > -(15*60))
9446 // Don't automatic refresh if:
9447 // - We already refreshed recently.
9448 // - We already auto-refreshed this launch.
9449 // - Auto-refresh is disabled.
9450 if (recently || loaded_ || ManualRefresh) {
9451 // If we are cancelling, we need to make sure it knows it's already loaded.
9454 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9456 // We are going to load, so remember that.
9459 // If we can reach the server, auto-refresh!
9460 if (IsReachable("cydia.saurik.com"))
9461 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9467 - (void) refreshIfPossible {
9468 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9471 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9472 @synchronized (self) {
9473 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9474 [hud setText:UCLocalize("RELOADING_DATA")];
9476 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9480 [essential_ removeAllObjects];
9481 [broken_ removeAllObjects];
9483 NSArray *packages([database_ packages]);
9484 for (Package *package in packages) {
9486 [broken_ addObject:package];
9487 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9488 if ([package essential] && [package installed] != nil)
9489 [essential_ addObject:package];
9494 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9497 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9498 [changesItem setBadgeValue:badge];
9499 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9500 [self setApplicationIconBadgeNumber:changes];
9503 [changesItem setBadgeValue:nil];
9504 [changesItem setAnimatedBadge:NO];
9505 [self setApplicationIconBadgeNumber:0];
9511 [self removeProgressHUD:hud];
9514 - (void) updateData {
9518 - (void) updateDataAndLoad {
9520 if ([database_ progressDelegate] == nil)
9526 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9529 - (void) disemulate {
9530 if (emulated_ == nil)
9533 [window_ addSubview:[tabbar_ view]];
9534 [[emulated_ view] removeFromSuperview];
9536 [window_ setUserInteractionEnabled:YES];
9539 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9540 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9542 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9544 UIViewController *parent;
9545 if (emulated_ == nil)
9554 [parent presentModalViewController:navigation animated:YES];
9557 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9558 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9560 if (navigation != nil)
9561 [navigation pushViewController:progress animated:YES];
9563 [self presentModalViewController:progress force:YES];
9565 [progress invoke:invocation withTitle:title];
9569 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9570 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9573 - (void) repairWithInvocation:(NSInvocation *)invocation {
9575 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9579 - (void) repairWithSelector:(SEL)selector {
9580 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9583 - (void) reloadData {
9584 [self reloadDataWithInvocation:nil];
9585 if ([database_ progressDelegate] == nil)
9591 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9594 - (void) addSource:(NSDictionary *) source {
9595 CydiaAddSource(source);
9598 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9599 CydiaAddSource(href, distribution, sections);
9602 - (void) addTrivialSource:(NSString *)href {
9603 CydiaAddSource(href, @"./");
9606 - (void) updateValues {
9611 pkgProblemResolver *resolver = [database_ resolver];
9613 resolver->InstallProtect();
9614 if (!resolver->Resolve(true))
9619 // XXX: this is a really crappy way of doing this.
9620 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9621 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9622 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9623 if ([tabbar_ updating])
9624 [tabbar_ cancelUpdate];
9626 if (![database_ prepare])
9629 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9630 [page setDelegate:self];
9631 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9634 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9635 [tabbar_ presentModalViewController:confirm_ animated:YES];
9641 @synchronized (self) {
9646 - (void) clearPackage:(Package *)package {
9647 @synchronized (self) {
9654 - (void) installPackages:(NSArray *)packages {
9655 @synchronized (self) {
9656 for (Package *package in packages)
9663 - (void) installPackage:(Package *)package {
9664 @synchronized (self) {
9671 - (void) removePackage:(Package *)package {
9672 @synchronized (self) {
9679 - (void) distUpgrade {
9680 @synchronized (self) {
9681 if (![database_ upgrade])
9688 [database_ perform];
9689 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9692 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9695 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9699 - (void) showSettings {
9700 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9703 - (void) retainNetworkActivityIndicator {
9704 if (activity_++ == 0)
9705 [self setNetworkActivityIndicatorVisible:YES];
9708 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9712 - (void) releaseNetworkActivityIndicator {
9713 if (--activity_ == 0)
9714 [self setNetworkActivityIndicatorVisible:NO];
9717 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9722 - (void) cancelAndClear:(bool)clear {
9723 @synchronized (self) {
9735 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9736 NSString *context([alert context]);
9738 if ([context isEqualToString:@"conffile"]) {
9739 FILE *input = [database_ input];
9740 if (button == [alert cancelButtonIndex])
9741 fprintf(input, "N\n");
9742 else if (button == [alert firstOtherButtonIndex])
9743 fprintf(input, "Y\n");
9746 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9747 } else if ([context isEqualToString:@"fixhalf"]) {
9748 if (button == [alert cancelButtonIndex]) {
9749 @synchronized (self) {
9750 for (Package *broken in (id) broken_) {
9753 NSString *id = [broken id];
9754 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9755 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9756 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9757 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9763 } else if (button == [alert firstOtherButtonIndex]) {
9764 [broken_ removeAllObjects];
9768 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9769 } else if ([context isEqualToString:@"upgrade"]) {
9770 if (button == [alert firstOtherButtonIndex]) {
9771 @synchronized (self) {
9772 for (Package *essential in (id) essential_)
9773 [essential install];
9778 } else if (button == [alert firstOtherButtonIndex] + 1) {
9780 } else if (button == [alert cancelButtonIndex]) {
9784 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9788 - (void) system:(NSString *)command {
9789 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9792 system([command UTF8String]);
9798 - (void) applicationWillSuspend {
9800 [super applicationWillSuspend];
9803 - (BOOL) isSafeToSuspend {
9806 NSLog(@"isSafeToSuspend: locked_ != 0");
9811 // Use external process status API internally.
9812 // This is probably a really bad idea.
9813 // XXX: what is the point of this? does this solve anything at all?
9814 uint64_t status = 0;
9816 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9817 notify_get_state(notify_token, &status);
9818 notify_cancel(notify_token);
9823 NSLog(@"isSafeToSuspend: status != 0");
9829 NSLog(@"isSafeToSuspend: -> true");
9834 - (void) applicationSuspend:(__GSEvent *)event {
9835 if ([self isSafeToSuspend])
9836 [super applicationSuspend:event];
9839 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9840 if ([self isSafeToSuspend])
9841 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9844 - (void) _setSuspended:(BOOL)value {
9845 if ([self isSafeToSuspend])
9846 [super _setSuspended:value];
9849 - (UIProgressHUD *) addProgressHUD {
9850 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9851 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9853 [window_ setUserInteractionEnabled:NO];
9855 UIViewController *target(tabbar_);
9856 if (UIViewController *modal = [target modalViewController])
9859 [hud showInView:[target view]];
9865 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9868 [hud removeFromSuperview];
9869 [window_ setUserInteractionEnabled:YES];
9872 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9873 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9876 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9877 NSString *scheme([[url scheme] lowercaseString]);
9878 if ([[url absoluteString] length] <= [scheme length] + 3)
9880 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9881 NSArray *components([path componentsSeparatedByString:@"/"]);
9883 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9884 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9885 if (controller != nil)
9886 [controller setDelegate:self];
9890 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9893 NSString *base([components objectAtIndex:0]);
9895 CyteViewController *controller = nil;
9897 if ([base isEqualToString:@"url"]) {
9898 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9899 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9900 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9901 } else if (!external && [components count] == 1) {
9902 if ([base isEqualToString:@"manage"]) {
9903 controller = [[[ManageController alloc] init] autorelease];
9906 if ([base isEqualToString:@"storage"]) {
9907 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9910 if ([base isEqualToString:@"sources"]) {
9911 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9914 if ([base isEqualToString:@"home"]) {
9915 controller = [[[HomeController alloc] init] autorelease];
9918 if ([base isEqualToString:@"sections"]) {
9919 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9922 if ([base isEqualToString:@"search"]) {
9923 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9926 if ([base isEqualToString:@"changes"]) {
9927 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9930 if ([base isEqualToString:@"installed"]) {
9931 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9933 } else if ([components count] == 2) {
9934 NSString *argument = [components objectAtIndex:1];
9936 if ([base isEqualToString:@"package"]) {
9937 controller = [self pageForPackage:argument withReferrer:referrer];
9940 if (!external && [base isEqualToString:@"search"]) {
9941 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9944 if (!external && [base isEqualToString:@"sections"]) {
9945 if ([argument isEqualToString:@"all"])
9947 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9950 if (!external && [base isEqualToString:@"sources"]) {
9951 if ([argument isEqualToString:@"add"]) {
9952 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9953 [(SourcesController *)controller showAddSourcePrompt];
9955 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9956 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9960 if (!external && [base isEqualToString:@"launch"]) {
9961 [self launchApplicationWithIdentifier:argument suspended:NO];
9964 } else if (!external && [components count] == 3) {
9965 NSString *arg1 = [components objectAtIndex:1];
9966 NSString *arg2 = [components objectAtIndex:2];
9968 if ([base isEqualToString:@"package"]) {
9969 if ([arg2 isEqualToString:@"settings"]) {
9970 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9971 } else if ([arg2 isEqualToString:@"files"]) {
9972 if (Package *package = [database_ packageWithName:arg1]) {
9973 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9974 [(FileTable *)controller setPackage:package];
9980 [controller setDelegate:self];
9984 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9985 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9988 [tabbar_ setUnselectedViewController:page];
9993 - (void) applicationOpenURL:(NSURL *)url {
9994 [super applicationOpenURL:url];
9999 [self openCydiaURL:url forExternal:YES];
10002 - (void) applicationWillResignActive:(UIApplication *)application {
10003 // Stop refreshing if you get a phone call or lock the device.
10004 if ([tabbar_ updating])
10005 [tabbar_ cancelUpdate];
10007 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
10008 [super applicationWillResignActive:application];
10011 - (void) saveState {
10012 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
10013 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10014 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10017 [self _saveConfig];
10020 - (void) applicationWillTerminate:(UIApplication *)application {
10024 - (void) setConfigurationData:(NSString *)data {
10025 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10027 if (!conffile_r(data)) {
10028 lprintf("E:invalid conffile\n");
10032 NSString *ofile = conffile_r[1];
10033 //NSString *nfile = conffile_r[2];
10035 UIAlertView *alert = [[[UIAlertView alloc]
10036 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10037 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10039 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10041 UCLocalize("ACCEPT_NEW_COPY"),
10042 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10046 [alert setContext:@"conffile"];
10047 [alert setNumberOfRows:2];
10051 - (void) addStashController {
10053 stash_ = [[[StashController alloc] init] autorelease];
10054 [window_ addSubview:[stash_ view]];
10057 - (void) removeStashController {
10058 [[stash_ view] removeFromSuperview];
10064 [self setIdleTimerDisabled:YES];
10066 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10067 UpdateExternalStatus(1);
10068 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10069 UpdateExternalStatus(0);
10071 [self removeStashController];
10073 pid_t pid(ExecFork());
10075 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10076 perror("launchctl stop");
10083 - (void) setupViewControllers {
10084 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10086 NSMutableArray *items([NSMutableArray arrayWithObjects:
10087 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10088 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10089 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10090 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10094 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10095 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10097 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10100 NSMutableArray *controllers([NSMutableArray array]);
10101 for (UITabBarItem *item in items) {
10102 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10103 [controller setTabBarItem:item];
10104 [controllers addObject:controller];
10106 [tabbar_ setViewControllers:controllers];
10108 [tabbar_ setUpdateDelegate:self];
10111 - (void) _sendMemoryWarningNotification {
10112 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10113 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10115 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10118 - (void) _sendMemoryWarningNotifications {
10120 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10126 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10128 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10131 - (void) applicationDidFinishLaunching:(id)unused {
10132 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10135 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10136 [self setApplicationSupportsShakeToEdit:NO];
10138 @synchronized (HostConfig_) {
10139 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10142 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10143 initWithMemoryCapacity:524288
10144 diskCapacity:10485760
10145 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
10148 [CydiaWebViewController _initialize];
10150 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10152 // this would disallow http{,s} URLs from accessing this data
10153 //[WebView registerURLSchemeAsLocal:@"cydia"];
10155 Font12_ = [UIFont systemFontOfSize:12];
10156 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10157 Font14_ = [UIFont systemFontOfSize:14];
10158 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10159 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10161 essential_ = [NSMutableArray arrayWithCapacity:4];
10162 broken_ = [NSMutableArray arrayWithCapacity:4];
10164 // XXX: I really need this thing... like, seriously... I'm sorry
10165 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10167 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10168 [window_ orderFront:self];
10169 [window_ makeKey:self];
10170 [window_ setHidden:NO];
10173 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
10174 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
10175 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
10176 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
10177 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
10178 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
10179 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
10180 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
10181 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
10184 [self addStashController];
10185 // XXX: this would be much cleaner as a yieldToSelector:
10186 // that way the removeStashController could happen right here inline
10187 // we also could no longer require the useless stash_ field anymore
10188 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10192 database_ = [Database sharedInstance];
10193 [database_ setDelegate:self];
10195 [window_ setUserInteractionEnabled:NO];
10196 [self setupViewControllers];
10198 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10199 [window_ addSubview:[emulated_ view]];
10201 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10205 - (NSArray *) defaultStartPages {
10206 NSMutableArray *standard = [NSMutableArray array];
10207 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10208 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10209 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10211 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10213 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10214 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10216 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10220 - (void) loadData {
10222 if (Role_ == nil) {
10223 [window_ setUserInteractionEnabled:YES];
10224 [self showSettings];
10227 if ([emulated_ modalViewController] != nil)
10228 [emulated_ dismissModalViewControllerAnimated:YES];
10229 [window_ setUserInteractionEnabled:NO];
10232 [self reloadDataWithInvocation:nil];
10233 [self refreshIfPossible];
10238 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10239 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
10240 int standardIndex = 0;
10241 NSArray *standard = [self defaultStartPages];
10248 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10249 if (valid && closed != nil) {
10250 NSTimeInterval interval([closed timeIntervalSinceNow]);
10251 // XXX: Is 30 minutes the optimal time here?
10252 if (interval <= -(30*60))
10256 if (valid && [saved count] != [standard count])
10260 for (unsigned int i = 0; i < [standard count]; i++) {
10261 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10262 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10263 // but it's good enough for now.
10264 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10271 NSArray *items = nil;
10273 [tabbar_ setSelectedIndex:savedIndex];
10276 [tabbar_ setSelectedIndex:standardIndex];
10280 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10281 NSArray *stack = [items objectAtIndex:tab];
10282 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10283 NSMutableArray *current = [NSMutableArray array];
10285 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10286 NSString *addr = [stack objectAtIndex:nav];
10287 NSURL *url = [NSURL URLWithString:addr];
10288 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10290 [current addObject:page];
10293 [navigation setViewControllers:current];
10296 // (Try to) show the startup URL.
10297 if (starturl_ != nil) {
10298 [self openCydiaURL:starturl_ forExternal:NO];
10303 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10304 if (item != nil && IsWildcat_) {
10305 [sheet showFromBarButtonItem:item animated:YES];
10307 [sheet showInView:window_];
10311 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10312 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10313 [progress setTitle:task];
10314 [progress addProgressEvent:event];
10317 - (void) addProgressEventForTask:(NSArray *)data {
10318 CydiaProgressEvent *event([data objectAtIndex:0]);
10319 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10320 [self addProgressEvent:event forTask:task];
10323 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10324 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10330 id Alloc_(id self, SEL selector) {
10331 id object = alloc_(self, selector);
10332 lprintf("[%s]A-%p\n", self->isa->name, object);
10337 id Dealloc_(id self, SEL selector) {
10338 id object = dealloc_(self, selector);
10339 lprintf("[%s]D-%p\n", self->isa->name, object);
10343 Class $WebDefaultUIKitDelegate;
10345 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10346 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10347 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10348 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10351 static NSSet *MobilizedFiles_;
10353 static NSURL *MobilizeURL(NSURL *url) {
10354 NSString *path([url path]);
10355 if ([path hasPrefix:@"/var/root/"]) {
10356 NSString *file([path substringFromIndex:10]);
10357 if ([MobilizedFiles_ containsObject:file])
10358 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10364 Class $CFXPreferencesPropertyListSource;
10365 @class CFXPreferencesPropertyListSource;
10367 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10368 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10369 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10370 url = MobilizeURL(url);
10371 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10372 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10378 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10379 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10380 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10381 url = MobilizeURL(url);
10382 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10383 //NSLog(@"%@ %@", [url absoluteString], value);
10389 Class $NSURLConnection;
10391 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10392 NSMutableURLRequest *copy([request mutableCopy]);
10394 NSURL *url([copy URL]);
10396 NSString *host([url host]);
10397 NSString *scheme([[url scheme] lowercaseString]);
10399 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10401 @synchronized (HostConfig_) {
10402 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10403 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10404 [copy setHTTPShouldUsePipelining:YES];
10406 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10407 if ([control isEqualToString:@"max-age=0"])
10408 if ([CachedURLs_ containsObject:url]) {
10410 NSLog(@"~~~: %@", url);
10413 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10415 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10416 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10417 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10421 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10427 static CGSize $WAKWindow$screenSize(WAKWindow self, SEL _cmd) {
10428 CGSize size([[UIScreen mainScreen] bounds].size);
10429 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10430 if ([$WAKWindow hasLandscapeOrientation])
10431 std::swap(size.width, size.height);*/
10435 int main(int argc, char *argv[]) {
10436 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10440 UpdateExternalStatus(0);
10442 if (Class $UIDevice = objc_getClass("UIDevice")) {
10443 UIDevice *device([$UIDevice currentDevice]);
10444 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10446 IsWildcat_ = false;
10448 UIScreen *screen([UIScreen mainScreen]);
10449 if ([screen respondsToSelector:@selector(scale)])
10450 ScreenScale_ = [screen scale];
10454 UIDevice *device([UIDevice currentDevice]);
10455 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10456 Idiom_ = @"iphone";
10458 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10459 if (idiom == UIUserInterfaceIdiomPhone)
10460 Idiom_ = @"iphone";
10461 else if (idiom == UIUserInterfaceIdiomPad)
10464 NSLog(@"unknown UIUserInterfaceIdiom!");
10467 Pcre pattern("^([0-9]+\\.[0-9]+)");
10469 if (pattern([device systemVersion]))
10470 Firmware_ = pattern[1];
10471 if (pattern(Cydia_))
10472 Major_ = pattern[1];
10474 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10476 HostConfig_ = [[[NSObject alloc] init] autorelease];
10477 @synchronized (HostConfig_) {
10478 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10479 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10480 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10481 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10482 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10485 NSString *ui(@"ui/ios");
10487 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10488 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10489 UI_ = CydiaURL(ui);
10491 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10493 MobilizedFiles_ = [NSMutableSet setWithObjects:
10494 @"Library/Preferences/com.apple.Accessibility.plist",
10495 @"Library/Preferences/com.apple.preferences.sounds.plist",
10498 /* Library Hacks {{{ */
10499 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10501 $WAKWindow = objc_getClass("WAKWindow");
10502 if ($WAKWindow != NULL)
10503 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10504 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10506 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10508 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10509 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10510 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10511 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10514 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10515 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10516 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10517 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10520 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10521 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10522 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10523 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10524 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10527 $NSURLConnection = objc_getClass("NSURLConnection");
10528 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10529 if (NSURLConnection$init$ != NULL) {
10530 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10531 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10534 /* Set Locale {{{ */
10535 Locale_ = CFLocaleCopyCurrent();
10536 Languages_ = [NSLocale preferredLanguages];
10538 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10539 //NSLog(@"%@", [Languages_ description]);
10542 if (Locale_ != NULL)
10543 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10544 else if (Languages_ != nil && [Languages_ count] != 0)
10545 lang = [[Languages_ objectAtIndex:0] UTF8String];
10547 // XXX: consider just setting to C and then falling through?
10550 if (lang != NULL) {
10551 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10552 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10555 NSLog(@"Setting Language: %s", lang);
10557 if (lang != NULL) {
10558 setenv("LANG", lang, true);
10559 std::setlocale(LC_ALL, lang);
10563 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10565 /* Parse Arguments {{{ */
10566 bool substrate(false);
10572 for (int argi(1); argi != argc; ++argi)
10573 if (strcmp(argv[argi], "--") == 0) {
10575 argv[argi] = argv[0];
10581 for (int argi(1); argi != arge; ++argi)
10582 if (strcmp(args[argi], "--substrate") == 0)
10585 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10589 App_ = [[NSBundle mainBundle] bundlePath];
10595 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10596 alloc_ = alloc->method_imp;
10597 alloc->method_imp = (IMP) &Alloc_;*/
10599 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10600 dealloc_ = dealloc->method_imp;
10601 dealloc->method_imp = (IMP) &Dealloc_;*/
10603 /* System Information {{{ */
10607 size = sizeof(maxproc);
10608 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10609 perror("sysctlbyname(\"kern.maxproc\", ?)");
10610 else if (maxproc < 64) {
10612 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10613 perror("sysctlbyname(\"kern.maxproc\", #)");
10616 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10617 char *osversion = new char[size];
10618 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10619 perror("sysctlbyname(\"kern.osversion\", ?)");
10621 System_ = [NSString stringWithUTF8String:osversion];
10623 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10624 char *machine = new char[size];
10625 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10626 perror("sysctlbyname(\"hw.machine\", ?)");
10628 Machine_ = machine;
10630 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10631 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10632 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10634 UniqueID_ = [device uniqueIdentifier];
10636 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10637 Product_ = [info objectForKey:@"SafariProductVersion"];
10638 Safari_ = [info objectForKey:@"CFBundleVersion"];
10641 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10643 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10644 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10645 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10646 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10647 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10648 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10650 UserAgent_ = agent;
10652 /* Load Database {{{ */
10654 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10656 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10658 if (Metadata_ == NULL)
10659 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10661 Settings_ = [Metadata_ objectForKey:@"Settings"];
10663 Packages_ = [Metadata_ objectForKey:@"Packages"];
10665 Values_ = [Metadata_ objectForKey:@"Values"];
10666 Sections_ = [Metadata_ objectForKey:@"Sections"];
10667 Sources_ = [Metadata_ objectForKey:@"Sources"];
10669 Token_ = [Metadata_ objectForKey:@"Token"];
10671 Version_ = [Metadata_ objectForKey:@"Version"];
10674 if (Settings_ != nil)
10675 Role_ = [Settings_ objectForKey:@"Role"];
10677 if (Values_ == nil) {
10678 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10679 [Metadata_ setObject:Values_ forKey:@"Values"];
10682 if (Sections_ == nil) {
10683 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10684 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10687 if (Sources_ == nil) {
10688 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10689 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10692 if (Version_ == nil) {
10693 Version_ = [NSNumber numberWithUnsignedInt:0];
10694 [Metadata_ setObject:Version_ forKey:@"Version"];
10697 if ([Version_ unsignedIntValue] == 0) {
10698 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10699 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10700 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10701 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10703 Version_ = [NSNumber numberWithUnsignedInt:1];
10704 [Metadata_ setObject:Version_ forKey:@"Version"];
10706 [Metadata_ removeObjectForKey:@"LastUpdate"];
10712 CydiaWriteSources();
10715 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10718 if (Packages_ != nil) {
10720 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10724 [Metadata_ removeObjectForKey:@"Packages"];
10730 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10732 #define MobileSubstrate_(name) \
10733 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10734 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10735 if (handle == NULL) \
10736 NSLog(@"%s", dlerror()); \
10739 MobileSubstrate_(Activator)
10740 MobileSubstrate_(libstatusbar)
10741 MobileSubstrate_(SimulatedKeyEvents)
10742 MobileSubstrate_(WinterBoard)
10744 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10745 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10747 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10749 if (access("/User", F_OK) != 0 || version != 5) {
10751 system("/usr/libexec/cydia/firmware.sh");
10755 _assert([[NSFileManager defaultManager]
10756 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10757 withIntermediateDirectories:YES
10762 if (access("/tmp/cydia.chk", F_OK) == 0) {
10763 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10764 _assert(errno == ENOENT);
10765 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10766 _assert(errno == ENOENT);
10769 /* APT Initialization {{{ */
10770 _assert(pkgInitConfig(*_config));
10771 _assert(pkgInitSystem(*_config, _system));
10774 _config->Set("APT::Acquire::Translation", lang);
10776 // XXX: this timeout might be important :(
10777 //_config->Set("Acquire::http::Timeout", 15);
10779 _config->Set("Acquire::http::MaxParallel", 3);
10781 /* Color Choices {{{ */
10782 space_ = CGColorSpaceCreateDeviceRGB();
10784 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10785 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10786 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10787 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10788 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10789 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10790 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10791 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10792 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10794 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10795 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10797 /* UIKit Configuration {{{ */
10798 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10799 if ($GSFontSetUseLegacyFontMetrics != NULL)
10800 $GSFontSetUseLegacyFontMetrics(YES);
10802 // XXX: I have a feeling this was important
10803 //UIKeyboardDisableAutomaticAppearance();
10806 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10807 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10809 ShowPromoted_ = fast;
10810 PulseInterval_ = fast ? 50000 : 500000;
10812 Colon_ = UCLocalize("COLON_DELIMITED");
10813 Elision_ = UCLocalize("ELISION");
10814 Error_ = UCLocalize("ERROR");
10815 Warning_ = UCLocalize("WARNING");
10818 AprilFools_ = true;
10820 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10821 AprilFools_ = date.month == 4 && date.day == 1;
10825 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10827 CGColorSpaceRelease(space_);
10828 CFRelease(Locale_);