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 *host([url host]);
4637 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4638 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4639 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4640 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4645 @synchronized (HostConfig_) {
4646 bridged = [BridgedHosts_ containsObject:host];
4647 token = [TokenHosts_ containsObject:host];
4650 if ([url isCydiaSecure]) {
4652 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4653 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4655 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4656 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4663 - (void) setDelegate:(id)delegate {
4664 [super setDelegate:delegate];
4665 [cydia_ setDelegate:delegate];
4668 - (NSString *) applicationNameForUserAgent {
4673 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4674 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4680 @interface AppCacheController : CydiaWebViewController {
4685 @implementation AppCacheController
4687 - (void) didReceiveMemoryWarning {
4688 // XXX: this doesn't work
4691 - (bool) retainsNetworkActivityIndicator {
4699 @interface NSObject (CydiaScript)
4700 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4703 @implementation NSObject (CydiaScript)
4705 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4711 @implementation NSArray (CydiaScript)
4713 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4714 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4715 for (size_t i(0), e([self count]); i != e; ++i)
4716 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4722 @implementation NSDictionary (CydiaScript)
4724 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4725 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4727 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4734 /* Confirmation Controller {{{ */
4735 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4736 if (!iterator.end())
4737 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4738 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4740 pkgCache::PkgIterator package(dep.TargetPkg());
4743 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4750 @protocol ConfirmationControllerDelegate
4751 - (void) cancelAndClear:(bool)clear;
4752 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4756 @interface ConfirmationController : CydiaWebViewController {
4757 _transient Database *database_;
4759 _H<UIAlertView> essential_;
4761 _H<NSDictionary> changes_;
4762 _H<NSMutableArray> issues_;
4763 _H<NSDictionary> sizes_;
4768 - (id) initWithDatabase:(Database *)database;
4772 @implementation ConfirmationController
4776 RestartSubstrate_ = true;
4777 [delegate_ confirmWithNavigationController:[self navigationController]];
4780 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4781 NSString *context([alert context]);
4783 if ([context isEqualToString:@"remove"]) {
4784 if (button == [alert cancelButtonIndex])
4785 [self dismissModalViewControllerAnimated:YES];
4786 else if (button == [alert firstOtherButtonIndex]) {
4790 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4791 } else if ([context isEqualToString:@"unable"]) {
4792 [self dismissModalViewControllerAnimated:YES];
4793 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4795 [super alertView:alert clickedButtonAtIndex:button];
4799 - (void) _doContinue {
4800 [delegate_ cancelAndClear:NO];
4801 [self dismissModalViewControllerAnimated:YES];
4804 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4805 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4809 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4810 [super webView:view didClearWindowObject:window forFrame:frame];
4812 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4813 (id) changes_, @"changes",
4814 (id) issues_, @"issues",
4815 (id) sizes_, @"sizes",
4817 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4820 - (id) initWithDatabase:(Database *)database {
4821 if ((self = [super init]) != nil) {
4822 database_ = database;
4824 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4825 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4826 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4827 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4828 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4832 pkgCacheFile &cache([database_ cache]);
4833 NSArray *packages([database_ packages]);
4834 pkgDepCache::Policy *policy([database_ policy]);
4836 issues_ = [NSMutableArray arrayWithCapacity:4];
4838 for (Package *package in packages) {
4839 pkgCache::PkgIterator iterator([package iterator]);
4840 NSString *name([package id]);
4842 if ([package broken]) {
4843 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4845 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4847 reasons, @"reasons",
4850 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4854 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4855 pkgCache::DepIterator start;
4856 pkgCache::DepIterator end;
4857 dep.GlobOr(start, end); // ++dep
4859 if (!cache->IsImportantDep(end))
4861 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4864 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4866 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4867 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4868 clauses, @"clauses",
4872 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4874 pkgCache::PkgIterator target(start.TargetPkg());
4875 if (target->ProvidesList != 0)
4876 reason = @"missing";
4878 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4880 reason = @"installed";
4881 installed = [NSString stringWithUTF8String:ver.VerStr()];
4882 } else if (!cache[target].CandidateVerIter(cache).end())
4883 reason = @"uninstalled";
4884 else if (target->ProvidesList == 0)
4885 reason = @"uninstallable";
4887 reason = @"virtual";
4890 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4891 [NSString stringWithUTF8String:start.CompType()], @"operator",
4892 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4895 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4896 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4897 version, @"version",
4899 installed, @"installed",
4902 // yes, seriously. (wtf?)
4910 pkgDepCache::StateCache &state(cache[iterator]);
4912 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4914 if (state.NewInstall())
4915 [installs addObject:name];
4916 // XXX: else if (state.Install())
4917 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4918 [reinstalls addObject:name];
4919 // XXX: move before previous if
4920 else if (state.Upgrade())
4921 [upgrades addObject:name];
4922 else if (state.Downgrade())
4923 [downgrades addObject:name];
4924 else if (!state.Delete())
4925 // XXX: _assert(state.Keep());
4927 else if (special_r(name))
4928 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4929 [NSNull null], @"package",
4930 [NSArray arrayWithObjects:
4931 [NSDictionary dictionaryWithObjectsAndKeys:
4932 @"Conflicts", @"relationship",
4933 [NSArray arrayWithObjects:
4934 [NSDictionary dictionaryWithObjectsAndKeys:
4936 [NSNull null], @"version",
4937 @"installed", @"reason",
4944 if ([package essential])
4946 [removes addObject:name];
4949 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4950 substrate_ |= DepSubstrate(iterator.CurrentVer());
4955 else if (Advanced_) {
4956 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4958 essential_ = [[[UIAlertView alloc]
4959 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4960 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4962 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4964 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4968 [essential_ setContext:@"remove"];
4970 essential_ = [[[UIAlertView alloc]
4971 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4972 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4974 cancelButtonTitle:UCLocalize("OKAY")
4975 otherButtonTitles:nil
4978 [essential_ setContext:@"unable"];
4981 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4982 installs, @"installs",
4983 reinstalls, @"reinstalls",
4984 upgrades, @"upgrades",
4985 downgrades, @"downgrades",
4986 removes, @"removes",
4989 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4990 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4991 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4994 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4998 - (UIBarButtonItem *) leftButton {
4999 return [[[UIBarButtonItem alloc]
5000 initWithTitle:UCLocalize("CANCEL")
5001 style:UIBarButtonItemStylePlain
5003 action:@selector(cancelButtonClicked)
5008 - (void) applyRightButton {
5009 if ([issues_ count] == 0 && ![self isLoading])
5010 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5011 initWithTitle:UCLocalize("CONFIRM")
5012 style:UIBarButtonItemStyleDone
5014 action:@selector(confirmButtonClicked)
5017 [[self navigationItem] setRightBarButtonItem:nil];
5021 - (void) cancelButtonClicked {
5022 [delegate_ cancelAndClear:YES];
5023 [self dismissModalViewControllerAnimated:YES];
5027 - (void) confirmButtonClicked {
5028 if (essential_ != nil)
5038 /* Progress Data {{{ */
5039 @interface CydiaProgressData : NSObject {
5040 _transient id delegate_;
5049 _H<NSMutableArray> events_;
5050 _H<NSString> title_;
5052 _H<NSString> status_;
5053 _H<NSString> finish_;
5058 @implementation CydiaProgressData
5060 + (NSArray *) _attributeKeys {
5061 return [NSArray arrayWithObjects:
5073 - (NSArray *) attributeKeys {
5074 return [[self class] _attributeKeys];
5077 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5078 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5082 if ((self = [super init]) != nil) {
5083 events_ = [NSMutableArray arrayWithCapacity:32];
5087 - (void) setDelegate:(id)delegate {
5088 delegate_ = delegate;
5091 - (void) setPercent:(float)value {
5095 - (NSNumber *) percent {
5096 return [NSNumber numberWithFloat:percent_];
5099 - (void) setCurrent:(float)value {
5103 - (NSNumber *) current {
5104 return [NSNumber numberWithFloat:current_];
5107 - (void) setTotal:(float)value {
5111 - (NSNumber *) total {
5112 return [NSNumber numberWithFloat:total_];
5115 - (void) setSpeed:(float)value {
5119 - (NSNumber *) speed {
5120 return [NSNumber numberWithFloat:speed_];
5123 - (NSArray *) events {
5127 - (void) removeAllEvents {
5128 [events_ removeAllObjects];
5131 - (void) addEvent:(CydiaProgressEvent *)event {
5132 [events_ addObject:event];
5135 - (void) setTitle:(NSString *)text {
5139 - (NSString *) title {
5143 - (void) setFinish:(NSString *)text {
5147 - (NSString *) finish {
5148 return (id) finish_ ?: [NSNull null];
5151 - (void) setRunning:(bool)running {
5155 - (NSNumber *) running {
5156 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5161 /* Progress Controller {{{ */
5162 @interface ProgressController : CydiaWebViewController <
5165 _transient Database *database_;
5166 _H<CydiaProgressData, 1> progress_;
5170 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5172 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5174 - (void) setTitle:(NSString *)title;
5175 - (void) setCancellable:(bool)cancellable;
5179 @implementation ProgressController
5182 [database_ setProgressDelegate:nil];
5186 - (UIBarButtonItem *) leftButton {
5187 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5188 initWithTitle:UCLocalize("CANCEL")
5189 style:UIBarButtonItemStylePlain
5191 action:@selector(cancel)
5192 ] autorelease] : nil;
5195 - (void) updateCancel {
5196 [super applyLeftButton];
5199 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5200 if ((self = [super init]) != nil) {
5201 database_ = database;
5202 delegate_ = delegate;
5204 [database_ setProgressDelegate:self];
5206 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5207 [progress_ setDelegate:self];
5209 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5211 [scroller_ setBackgroundColor:[UIColor blackColor]];
5213 [[self navigationItem] setHidesBackButton:YES];
5215 [self updateCancel];
5219 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5220 [super webView:view didClearWindowObject:window forFrame:frame];
5221 [window setValue:progress_ forKey:@"cydiaProgress"];
5224 - (void) updateProgress {
5225 [self dispatchEvent:@"CydiaProgressUpdate"];
5228 - (void) viewWillAppear:(BOOL)animated {
5229 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5230 [super viewWillAppear:animated];
5233 - (void) reloadSpringBoard {
5234 pid_t pid(ExecFork());
5236 pid_t pid(ExecFork());
5238 execl("/usr/bin/sbreload", "sbreload", NULL);
5249 system("/usr/bin/killall SpringBoard");
5253 UpdateExternalStatus(0);
5256 [delegate_ saveState];
5260 [delegate_ returnToCydia];
5264 [delegate_ terminateWithSuccess];
5265 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5266 [delegate_ suspendWithAnimation:YES];
5268 [delegate_ suspend];*/
5280 UIProgressHUD *hud([delegate_ addProgressHUD]);
5281 [hud setText:UCLocalize("LOADING")];
5282 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5288 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5289 SBReboot(SBSSpringBoardServerPort());
5291 reboot2(RB_AUTOBOOT);
5298 - (void) setTitle:(NSString *)title {
5299 [progress_ setTitle:title];
5300 [self updateProgress];
5303 - (UIBarButtonItem *) rightButton {
5304 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5305 initWithTitle:UCLocalize("CLOSE")
5306 style:UIBarButtonItemStylePlain
5308 action:@selector(close)
5314 system("su -c /usr/bin/uicache mobile");
5318 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5319 UpdateExternalStatus(1);
5321 [progress_ setRunning:true];
5322 [self setTitle:title];
5323 // implicit updateProgress
5325 SHA1SumValue notifyconf; {
5327 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5330 MMap mmap(file, MMap::ReadOnly);
5332 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5333 notifyconf = sha1.Result();
5337 SHA1SumValue springlist; {
5339 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5342 MMap mmap(file, MMap::ReadOnly);
5344 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5345 springlist = sha1.Result();
5349 if (invocation != nil) {
5350 [invocation yieldToSelector:@selector(invoke)];
5351 [self setTitle:@"COMPLETE"];
5356 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5359 MMap mmap(file, MMap::ReadOnly);
5361 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5362 if (!(notifyconf == sha1.Result()))
5369 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5372 MMap mmap(file, MMap::ReadOnly);
5374 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5375 if (!(springlist == sha1.Result()))
5381 if (RestartSubstrate_)
5385 RestartSubstrate_ = false;
5388 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5389 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5390 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5391 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5392 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5395 UIProgressHUD *hud([delegate_ addProgressHUD]);
5396 [hud setText:UCLocalize("LOADING")];
5397 [self yieldToSelector:@selector(uicache)];
5398 [delegate_ removeProgressHUD:hud];
5400 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5402 [progress_ setRunning:false];
5403 [self updateProgress];
5405 [self applyRightButton];
5408 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5409 [progress_ addEvent:event];
5410 [self updateProgress];
5413 - (bool) isProgressCancelled {
5414 return cancel_ == 2;
5419 [self updateCancel];
5422 - (void) setCancellable:(bool)cancellable {
5423 unsigned cancel(cancel_);
5427 else if (cancel_ == 0)
5430 if (cancel != cancel_)
5431 [self updateCancel];
5434 - (void) setProgressCancellable:(NSNumber *)cancellable {
5435 [self setCancellable:[cancellable boolValue]];
5438 - (void) setProgressPercent:(NSNumber *)percent {
5439 [progress_ setPercent:[percent floatValue]];
5440 [self updateProgress];
5443 - (void) setProgressStatus:(NSDictionary *)status {
5444 if (status == nil) {
5445 [progress_ setCurrent:0];
5446 [progress_ setTotal:0];
5447 [progress_ setSpeed:0];
5449 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5451 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5452 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5453 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5456 [self updateProgress];
5462 /* Package Cell {{{ */
5463 @interface PackageCell : CyteTableViewCell <
5464 CyteTableViewCellDelegate
5468 _H<NSString> description_;
5470 _H<NSString> source_;
5472 _H<UIImage> placard_;
5476 - (PackageCell *) init;
5477 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5479 - (void) drawContentRect:(CGRect)rect;
5483 @implementation PackageCell
5485 - (PackageCell *) init {
5486 CGRect frame(CGRectMake(0, 0, 320, 74));
5487 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5488 UIView *content([self contentView]);
5489 CGRect bounds([content bounds]);
5491 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5492 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5493 [content addSubview:content_];
5495 [content_ setDelegate:self];
5496 [content_ setOpaque:YES];
5500 - (NSString *) accessibilityLabel {
5501 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5504 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5505 summarized_ = summary;
5515 [content_ setBackgroundColor:[UIColor whiteColor]];
5519 Source *source = [package source];
5521 icon_ = [package icon];
5523 if (NSString *name = [package name])
5524 name_ = [NSString stringWithString:name];
5526 NSString *description(nil);
5528 if (description == nil && IsWildcat_)
5529 description = [package longDescription];
5530 if (description == nil)
5531 description = [package shortDescription];
5533 if (description != nil)
5534 description_ = [NSString stringWithString:description];
5536 commercial_ = [package isCommercial];
5538 NSString *label = nil;
5539 bool trusted = false;
5541 if (source != nil) {
5542 label = [source label];
5543 trusted = [source trusted];
5544 } else if ([[package id] isEqualToString:@"firmware"])
5545 label = UCLocalize("APPLE");
5547 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5549 NSString *from(label);
5551 NSString *section = [package simpleSection];
5552 if (section != nil && ![section isEqualToString:label]) {
5553 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5554 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5557 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5559 if (NSString *purpose = [package primaryPurpose])
5560 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5565 if (NSString *mode = [package mode]) {
5566 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5567 color = RemovingColor_;
5568 //placard = @"removing";
5570 color = InstallingColor_;
5571 //placard = @"installing";
5574 // XXX: the removing/installing placards are not @2x
5577 color = [UIColor whiteColor];
5579 if ([package installed] != nil)
5580 placard = @"installed";
5585 [content_ setBackgroundColor:color];
5588 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5591 [self setNeedsDisplay];
5592 [content_ setNeedsDisplay];
5595 - (void) drawSummaryContentRect:(CGRect)rect {
5596 bool highlighted(highlighted_);
5597 float width([self bounds].size.width);
5601 rect.size = [(UIImage *) icon_ size];
5603 while (rect.size.width > 16 || rect.size.height > 16) {
5604 rect.size.width /= 2;
5605 rect.size.height /= 2;
5608 rect.origin.x = 18 - rect.size.width / 2;
5609 rect.origin.y = 18 - rect.size.height / 2;
5611 [icon_ drawInRect:rect];
5614 if (badge_ != nil) {
5616 rect.size = [(UIImage *) badge_ size];
5618 rect.size.width /= 4;
5619 rect.size.height /= 4;
5621 rect.origin.x = 23 - rect.size.width / 2;
5622 rect.origin.y = 23 - rect.size.height / 2;
5624 [badge_ drawInRect:rect];
5631 UISetColor(commercial_ ? Purple_ : Black_);
5632 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5634 if (placard_ != nil)
5635 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5638 - (void) drawNormalContentRect:(CGRect)rect {
5639 bool highlighted(highlighted_);
5640 float width([self bounds].size.width);
5644 rect.size = [(UIImage *) icon_ size];
5646 while (rect.size.width > 32 || rect.size.height > 32) {
5647 rect.size.width /= 2;
5648 rect.size.height /= 2;
5651 rect.origin.x = 25 - rect.size.width / 2;
5652 rect.origin.y = 25 - rect.size.height / 2;
5654 [icon_ drawInRect:rect];
5657 if (badge_ != nil) {
5659 rect.size = [(UIImage *) badge_ size];
5661 rect.size.width /= 2;
5662 rect.size.height /= 2;
5664 rect.origin.x = 36 - rect.size.width / 2;
5665 rect.origin.y = 36 - rect.size.height / 2;
5667 [badge_ drawInRect:rect];
5674 UISetColor(commercial_ ? Purple_ : Black_);
5675 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5676 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5679 UISetColor(commercial_ ? Purplish_ : Gray_);
5680 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5682 if (placard_ != nil)
5683 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5686 - (void) drawContentRect:(CGRect)rect {
5688 [self drawSummaryContentRect:rect];
5690 [self drawNormalContentRect:rect];
5695 /* Section Cell {{{ */
5696 @interface SectionCell : CyteTableViewCell <
5697 CyteTableViewCellDelegate
5699 _H<NSString> basic_;
5700 _H<NSString> section_;
5702 _H<NSString> count_;
5704 _H<UISwitch> switch_;
5708 - (void) setSection:(Section *)section editing:(BOOL)editing;
5712 @implementation SectionCell
5714 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5715 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5716 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5717 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5718 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5720 UIView *content([self contentView]);
5721 CGRect bounds([content bounds]);
5723 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5724 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5725 [content addSubview:content_];
5726 [content_ setBackgroundColor:[UIColor whiteColor]];
5728 [content_ setDelegate:self];
5732 - (void) onSwitch:(id)sender {
5733 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5734 if (metadata == nil) {
5735 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5736 [Sections_ setObject:metadata forKey:basic_];
5739 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5743 - (void) setSection:(Section *)section editing:(BOOL)editing {
5744 if (editing != editing_) {
5746 [switch_ removeFromSuperview];
5748 [self addSubview:switch_];
5757 if (section == nil) {
5758 name_ = UCLocalize("ALL_PACKAGES");
5761 basic_ = [section name];
5762 section_ = [section localized];
5764 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5765 count_ = [NSString stringWithFormat:@"%d", [section count]];
5768 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5771 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5772 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5774 [content_ setNeedsDisplay];
5777 - (void) setFrame:(CGRect)frame {
5778 [super setFrame:frame];
5780 CGRect rect([switch_ frame]);
5781 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5784 - (NSString *) accessibilityLabel {
5788 - (void) drawContentRect:(CGRect)rect {
5789 bool highlighted(highlighted_ && !editing_);
5791 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5796 float width(rect.size.width);
5802 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5804 CGSize size = [count_ sizeWithFont:Font14_];
5808 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5814 /* File Table {{{ */
5815 @interface FileTable : CyteViewController <
5816 UITableViewDataSource,
5819 _transient Database *database_;
5820 _H<Package> package_;
5822 _H<NSMutableArray> files_;
5823 _H<UITableView, 2> list_;
5826 - (id) initWithDatabase:(Database *)database;
5827 - (void) setPackage:(Package *)package;
5831 @implementation FileTable
5833 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5834 return files_ == nil ? 0 : [files_ count];
5837 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5841 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5842 static NSString *reuseIdentifier = @"Cell";
5844 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5846 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5847 [cell setFont:[UIFont systemFontOfSize:16]];
5849 [cell setText:[files_ objectAtIndex:indexPath.row]];
5850 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5855 - (NSURL *) navigationURL {
5856 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5860 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5861 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5862 [list_ setRowHeight:24.0f];
5863 [(UITableView *) list_ setDataSource:self];
5864 [list_ setDelegate:self];
5865 [self setView:list_];
5868 - (void) viewDidLoad {
5869 [super viewDidLoad];
5871 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5874 - (void) releaseSubviews {
5880 [super releaseSubviews];
5883 - (id) initWithDatabase:(Database *)database {
5884 if ((self = [super init]) != nil) {
5885 database_ = database;
5889 - (void) setPackage:(Package *)package {
5893 files_ = [NSMutableArray arrayWithCapacity:32];
5895 if (package != nil) {
5897 name_ = [package id];
5899 if (NSArray *files = [package files])
5900 [files_ addObjectsFromArray:files];
5902 if ([files_ count] != 0) {
5903 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5904 [files_ removeObjectAtIndex:0];
5905 [files_ sortUsingSelector:@selector(compareByPath:)];
5907 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5908 [stack addObject:@"/"];
5910 for (int i(0), e([files_ count]); i != e; ++i) {
5911 NSString *file = [files_ objectAtIndex:i];
5912 while (![file hasPrefix:[stack lastObject]])
5913 [stack removeLastObject];
5914 NSString *directory = [stack lastObject];
5915 [stack addObject:[file stringByAppendingString:@"/"]];
5916 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5917 ([stack count] - 2) * 3, "",
5918 [file substringFromIndex:[directory length]]
5927 - (void) reloadData {
5930 [self setPackage:[database_ packageWithName:name_]];
5935 /* Package Controller {{{ */
5936 @interface CYPackageController : CydiaWebViewController <
5937 UIActionSheetDelegate
5939 _transient Database *database_;
5940 _H<Package> package_;
5943 _H<NSMutableArray> buttons_;
5944 _H<UIBarButtonItem> button_;
5947 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5951 @implementation CYPackageController
5953 - (NSURL *) navigationURL {
5954 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5957 /* XXX: this is not safe at all... localization of /fail/ */
5958 - (void) _clickButtonWithName:(NSString *)name {
5959 if ([name isEqualToString:UCLocalize("CLEAR")])
5960 [delegate_ clearPackage:package_];
5961 else if ([name isEqualToString:UCLocalize("INSTALL")])
5962 [delegate_ installPackage:package_];
5963 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5964 [delegate_ installPackage:package_];
5965 else if ([name isEqualToString:UCLocalize("REMOVE")])
5966 [delegate_ removePackage:package_];
5967 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5968 [delegate_ installPackage:package_];
5969 else _assert(false);
5972 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5973 NSString *context([sheet context]);
5975 if ([context isEqualToString:@"modify"]) {
5976 if (button != [sheet cancelButtonIndex]) {
5977 NSString *buttonName = [buttons_ objectAtIndex:button];
5978 [self _clickButtonWithName:buttonName];
5981 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5985 - (bool) _allowJavaScriptPanel {
5990 - (void) _customButtonClicked {
5991 int count([buttons_ count]);
5996 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5998 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5999 [buttons addObjectsFromArray:buttons_];
6001 UIActionSheet *sheet = [[[UIActionSheet alloc]
6004 cancelButtonTitle:nil
6005 destructiveButtonTitle:nil
6006 otherButtonTitles:nil
6009 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6011 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6012 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6014 [sheet setContext:@"modify"];
6016 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6020 // We don't want to allow non-commercial packages to do custom things to the install button,
6021 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6022 - (void) customButtonClicked {
6024 [super customButtonClicked];
6026 [self _customButtonClicked];
6029 - (void) reloadButtonClicked {
6030 // Don't reload a commerical package by tapping the loading button,
6031 // but if it's not an Install button, we should forward it on.
6032 if (![package_ uninstalled])
6033 [self _customButtonClicked];
6036 - (void) applyLoadingTitle {
6037 // Don't show "Loading" as the title. Ever.
6040 - (UIBarButtonItem *) rightButton {
6045 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6046 if ((self = [super init]) != nil) {
6047 database_ = database;
6048 buttons_ = [NSMutableArray arrayWithCapacity:4];
6049 name_ = name == nil ? @"" : [NSString stringWithString:name];
6050 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6054 - (void) reloadData {
6057 package_ = [database_ packageWithName:name_];
6059 [buttons_ removeAllObjects];
6061 if (package_ != nil) {
6062 [(Package *) package_ parse];
6064 commercial_ = [package_ isCommercial];
6066 if ([package_ mode] != nil)
6067 [buttons_ addObject:UCLocalize("CLEAR")];
6068 if ([package_ source] == nil);
6069 else if ([package_ upgradableAndEssential:NO])
6070 [buttons_ addObject:UCLocalize("UPGRADE")];
6071 else if ([package_ uninstalled])
6072 [buttons_ addObject:UCLocalize("INSTALL")];
6074 [buttons_ addObject:UCLocalize("REINSTALL")];
6075 if (![package_ uninstalled])
6076 [buttons_ addObject:UCLocalize("REMOVE")];
6080 switch ([buttons_ count]) {
6081 case 0: title = nil; break;
6082 case 1: title = [buttons_ objectAtIndex:0]; break;
6083 default: title = UCLocalize("MODIFY"); break;
6086 button_ = [[[UIBarButtonItem alloc]
6088 style:UIBarButtonItemStylePlain
6090 action:@selector(customButtonClicked)
6094 - (bool) isLoading {
6095 return commercial_ ? [super isLoading] : false;
6101 /* Package List Controller {{{ */
6102 @interface PackageListController : CyteViewController <
6103 UITableViewDataSource,
6106 _transient Database *database_;
6108 _H<NSArray> packages_;
6109 _H<NSMutableArray> sections_;
6110 _H<UITableView, 2> list_;
6111 _H<NSMutableArray> index_;
6112 _H<NSMutableDictionary> indices_;
6113 _H<NSString> title_;
6114 unsigned reloading_;
6117 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6118 - (void) setDelegate:(id)delegate;
6119 - (void) resetCursor;
6124 @implementation PackageListController
6126 - (NSURL *) referrerURL {
6127 return [self navigationURL];
6130 - (bool) isSummarized {
6134 - (bool) showsSections {
6138 - (void) deselectWithAnimation:(BOOL)animated {
6139 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6142 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6143 CGRect base = [[self view] bounds];
6144 base.size.height -= bounds.size.height;
6145 base.origin = [list_ frame].origin;
6147 [UIView beginAnimations:nil context:NULL];
6148 [UIView setAnimationBeginsFromCurrentState:YES];
6149 [UIView setAnimationCurve:curve];
6150 [UIView setAnimationDuration:duration];
6151 [list_ setFrame:base];
6152 [UIView commitAnimations];
6155 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6156 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6159 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6160 [self resizeForKeyboardBounds:bounds duration:0];
6163 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6164 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6165 *curve = UIViewAnimationCurveEaseInOut;
6167 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6169 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6172 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6175 - (void) keyboardWillShow:(NSNotification *)notification {
6178 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6179 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6181 NSTimeInterval duration;
6182 UIViewAnimationCurve curve;
6183 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6185 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);
6186 UIViewController *base = self;
6187 while ([base parentViewController] != nil)
6188 base = [base parentViewController];
6189 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6190 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6192 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6193 intersection.size.height += CYStatusBarHeight();
6195 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6198 - (void) keyboardWillHide:(NSNotification *)notification {
6199 NSTimeInterval duration;
6200 UIViewAnimationCurve curve;
6201 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6203 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6206 - (void) viewWillAppear:(BOOL)animated {
6207 [super viewWillAppear:animated];
6209 [self resizeForKeyboardBounds:CGRectZero];
6210 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6211 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6214 - (void) viewWillDisappear:(BOOL)animated {
6215 [super viewWillDisappear:animated];
6217 [self resizeForKeyboardBounds:CGRectZero];
6218 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6219 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6222 - (void) viewDidAppear:(BOOL)animated {
6223 [super viewDidAppear:animated];
6224 [self deselectWithAnimation:animated];
6227 - (void) didSelectPackage:(Package *)package {
6228 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6229 [view setDelegate:delegate_];
6230 [[self navigationController] pushViewController:view animated:YES];
6233 #if TryIndexedCollation
6234 + (BOOL) hasIndexedCollation {
6235 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6239 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6240 NSInteger count([sections_ count]);
6241 return count == 0 ? 1 : count;
6244 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6245 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6247 return [[sections_ objectAtIndex:section] name];
6250 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6251 if ([sections_ count] == 0)
6253 return [[sections_ objectAtIndex:section] count];
6256 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6257 @synchronized (database_) {
6258 if ([database_ era] != era_)
6261 Section *section([sections_ objectAtIndex:[path section]]);
6262 NSInteger row([path row]);
6263 Package *package([packages_ objectAtIndex:([section row] + row)]);
6264 return [[package retain] autorelease];
6267 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6268 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6270 cell = [[[PackageCell alloc] init] autorelease];
6272 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6273 [cell setPackage:package asSummary:[self isSummarized]];
6277 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6278 Package *package([self packageAtIndexPath:path]);
6279 package = [database_ packageWithName:[package id]];
6280 [self didSelectPackage:package];
6283 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6284 if (![self showsSections])
6290 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6291 #if TryIndexedCollation
6292 if ([[self class] hasIndexedCollation]) {
6293 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6300 - (void) updateHeight {
6301 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6304 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6305 if ((self = [super init]) != nil) {
6306 database_ = database;
6307 title_ = [title copy];
6308 [[self navigationItem] setTitle:title_];
6313 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6314 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6315 [self setView:view];
6317 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6318 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6319 [view addSubview:list_];
6321 // XXX: is 20 the most optimal number here?
6322 [list_ setSectionIndexMinimumDisplayRowCount:20];
6324 [(UITableView *) list_ setDataSource:self];
6325 [list_ setDelegate:self];
6327 [self updateHeight];
6330 - (void) releaseSubviews {
6338 [super releaseSubviews];
6341 - (void) setDelegate:(id)delegate {
6342 delegate_ = delegate;
6345 - (bool) shouldYield {
6349 - (bool) shouldBlock {
6353 - (NSMutableArray *) _reloadPackages {
6354 @synchronized (database_) {
6355 era_ = [database_ era];
6356 NSArray *packages([database_ packages]);
6358 return [NSMutableArray arrayWithArray:packages];
6361 - (void) _reloadData {
6362 if (reloading_ != 0) {
6370 if ([self shouldYield]) {
6374 if (![self shouldBlock])
6377 hud = [delegate_ addProgressHUD];
6378 [hud setText:UCLocalize("LOADING")];
6382 packages = [self yieldToSelector:@selector(_reloadPackages)];
6385 [delegate_ removeProgressHUD:hud];
6386 } while (reloading_ == 2);
6388 packages = [self _reloadPackages];
6391 @synchronized (database_) {
6392 if (era_ != [database_ era])
6396 packages_ = packages;
6398 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6399 sections_ = [NSMutableArray arrayWithCapacity:16];
6401 Section *section = nil;
6403 #if TryIndexedCollation
6404 if ([[self class] hasIndexedCollation]) {
6405 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6407 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6408 NSArray *titles = [collation sectionIndexTitles];
6411 _profile(PackageTable$reloadData$Section)
6412 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6416 _profile(PackageTable$reloadData$Section$Package)
6417 package = [packages_ objectAtIndex:offset];
6418 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6421 while (secidx < index) {
6424 _profile(PackageTable$reloadData$Section$Allocate)
6425 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6428 _profile(PackageTable$reloadData$Section$Add)
6429 [sections_ addObject:section];
6433 [section addToCount];
6439 index_ = [NSMutableArray arrayWithCapacity:32];
6441 bool sectioned([self showsSections]);
6443 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6444 [sections_ addObject:section];
6447 _profile(PackageTable$reloadData$Section)
6448 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6452 _profile(PackageTable$reloadData$Section$Package)
6453 package = [packages_ objectAtIndex:offset];
6454 index = [package index];
6457 if (sectioned && (section == nil || [section index] != index)) {
6458 _profile(PackageTable$reloadData$Section$Allocate)
6459 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6462 [index_ addObject:[section name]];
6463 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6465 _profile(PackageTable$reloadData$Section$Add)
6466 [sections_ addObject:section];
6470 [section addToCount];
6475 [self updateHeight];
6477 _profile(PackageTable$reloadData$List)
6478 [(UITableView *) list_ setDataSource:self];
6483 - (void) reloadData {
6486 if ([self shouldYield])
6487 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6492 - (void) resetCursor {
6493 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6496 - (void) clearData {
6497 [self updateHeight];
6499 [list_ setDataSource:nil];
6507 /* Filtered Package List Controller {{{ */
6508 @interface FilteredPackageListController : PackageListController {
6511 _H<NSObject> object_;
6514 - (void) setObject:(id)object;
6515 - (void) setObject:(id)object forFilter:(SEL)filter;
6518 - (void) setFilter:(SEL)filter;
6520 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6524 @implementation FilteredPackageListController
6530 - (void) setFilter:(SEL)filter {
6531 @synchronized (self) {
6534 /* XXX: this is an unsafe optimization of doomy hell */
6535 Method method(class_getInstanceMethod([Package class], filter));
6536 _assert(method != NULL);
6537 imp_ = method_getImplementation(method);
6538 _assert(imp_ != NULL);
6541 - (void) setObject:(id)object {
6542 @synchronized (self) {
6546 - (void) setObject:(id)object forFilter:(SEL)filter {
6547 @synchronized (self) {
6548 [self setFilter:filter];
6549 [self setObject:object];
6552 - (NSMutableArray *) _reloadPackages {
6553 @synchronized (database_) {
6554 era_ = [database_ era];
6555 NSArray *packages([database_ packages]);
6557 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6561 _H<NSObject> object;
6563 @synchronized (self) {
6569 _profile(PackageTable$reloadData$Filter)
6570 for (Package *package in packages)
6571 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6572 [filtered addObject:package];
6578 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6579 if ((self = [super initWithDatabase:database title:title]) != nil) {
6580 [self setFilter:filter];
6581 [self setObject:object];
6588 /* Home Controller {{{ */
6589 @interface HomeController : CydiaWebViewController {
6590 CFRunLoopRef runloop_;
6591 SCNetworkReachabilityRef reachability_;
6596 @implementation HomeController
6598 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6599 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6603 if ((self = [super init]) != nil) {
6604 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6607 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6608 if (reachability_ != NULL) {
6609 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6610 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6612 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6613 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6620 if (reachability_ != NULL && runloop_ != NULL)
6621 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6625 - (NSURL *) navigationURL {
6626 return [NSURL URLWithString:@"cydia://home"];
6629 - (void) aboutButtonClicked {
6630 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6632 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6633 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6634 [alert setCancelButtonIndex:0];
6637 @"Copyright \u00a9 2008-2011\n"
6640 "Jay Freeman (saurik)\n"
6641 "saurik@saurik.com\n"
6642 "http://www.saurik.com/"
6648 - (UIBarButtonItem *) leftButton {
6649 return [[[UIBarButtonItem alloc]
6650 initWithTitle:UCLocalize("ABOUT")
6651 style:UIBarButtonItemStylePlain
6653 action:@selector(aboutButtonClicked)
6659 /* Manage Controller {{{ */
6660 @interface ManageController : CydiaWebViewController {
6663 - (void) queueStatusDidChange;
6667 @implementation ManageController
6670 if ((self = [super init]) != nil) {
6671 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6675 - (NSURL *) navigationURL {
6676 return [NSURL URLWithString:@"cydia://manage"];
6679 - (UIBarButtonItem *) leftButton {
6680 return [[[UIBarButtonItem alloc]
6681 initWithTitle:UCLocalize("SETTINGS")
6682 style:UIBarButtonItemStylePlain
6684 action:@selector(settingsButtonClicked)
6688 - (void) settingsButtonClicked {
6689 [delegate_ showSettings];
6692 - (void) queueButtonClicked {
6696 - (UIBarButtonItem *) rightButton {
6697 return Queuing_ ? [[[UIBarButtonItem alloc]
6698 initWithTitle:UCLocalize("QUEUE")
6699 style:UIBarButtonItemStyleDone
6701 action:@selector(queueButtonClicked)
6702 ] autorelease] : nil;
6705 - (void) queueStatusDidChange {
6706 [self applyRightButton];
6709 - (bool) isLoading {
6710 return !Queuing_ && [super isLoading];
6716 /* Refresh Bar {{{ */
6717 @interface RefreshBar : UINavigationBar {
6718 _H<UIProgressIndicator> indicator_;
6719 _H<UITextLabel> prompt_;
6720 _H<UIProgressBar> progress_;
6721 _H<UINavigationButton> cancel_;
6726 @implementation RefreshBar
6728 - (void) positionViews {
6729 CGRect frame = [cancel_ frame];
6730 frame.size = [cancel_ sizeThatFits:frame.size];
6731 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6732 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6733 [cancel_ setFrame:frame];
6735 CGSize prgsize = {75, 100};
6737 [self frame].size.width - prgsize.width - 10,
6738 ([self frame].size.height - prgsize.height) / 2
6740 [progress_ setFrame:prgrect];
6742 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6743 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6744 CGRect indrect = {{indoffset, indoffset}, indsize};
6745 [indicator_ setFrame:indrect];
6747 CGSize prmsize = {215, indsize.height + 4};
6749 indoffset * 2 + indsize.width,
6750 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6752 [prompt_ setFrame:prmrect];
6755 - (void) setFrame:(CGRect)frame {
6756 [super setFrame:frame];
6757 [self positionViews];
6760 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6761 if ((self = [super initWithFrame:frame]) != nil) {
6762 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6764 [self setBarStyle:UIBarStyleBlack];
6766 UIBarStyle barstyle([self _barStyle:NO]);
6767 bool ugly(barstyle == UIBarStyleDefault);
6769 UIProgressIndicatorStyle style = ugly ?
6770 UIProgressIndicatorStyleMediumBrown :
6771 UIProgressIndicatorStyleMediumWhite;
6773 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6774 [(UIProgressIndicator *) indicator_ setStyle:style];
6775 [indicator_ startAnimation];
6776 [self addSubview:indicator_];
6778 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6779 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6780 [prompt_ setBackgroundColor:[UIColor clearColor]];
6781 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6782 [self addSubview:prompt_];
6784 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6785 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6786 [(UIProgressBar *) progress_ setStyle:0];
6787 [self addSubview:progress_];
6789 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6790 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6791 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6792 [cancel_ setBarStyle:barstyle];
6794 [self positionViews];
6798 - (void) setCancellable:(bool)cancellable {
6800 [self addSubview:cancel_];
6802 [cancel_ removeFromSuperview];
6806 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6807 [progress_ setProgress:0];
6811 [self setCancellable:NO];
6814 - (void) setPrompt:(NSString *)prompt {
6815 [prompt_ setText:prompt];
6818 - (void) setProgress:(float)progress {
6819 [progress_ setProgress:progress];
6825 /* Cydia Navigation Controller Interface {{{ */
6826 @interface UINavigationController (Cydia)
6828 - (NSArray *) navigationURLCollection;
6829 - (void) unloadData;
6834 /* Cydia Tab Bar Controller {{{ */
6835 @interface CYTabBarController : UITabBarController <
6836 UITabBarControllerDelegate,
6839 _transient Database *database_;
6840 _H<RefreshBar, 1> refreshbar_;
6844 // XXX: ok, "updatedelegate_"?...
6845 _transient NSObject<CydiaDelegate> *updatedelegate_;
6847 _H<UIViewController> remembered_;
6848 _transient UIViewController *transient_;
6851 - (NSArray *) navigationURLCollection;
6852 - (void) dropBar:(BOOL)animated;
6853 - (void) beginUpdate;
6854 - (void) raiseBar:(BOOL)animated;
6856 - (void) unloadData;
6860 @implementation CYTabBarController
6862 - (void) didReceiveMemoryWarning {
6863 [super didReceiveMemoryWarning];
6865 // presenting a UINavigationController on 2.x does not update its transitionView
6866 // it thereby will not allow its topViewController to be unloaded by memory pressure
6867 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6868 UIViewController *selected([self selectedViewController]);
6869 for (UINavigationController *controller in [self viewControllers])
6870 if (controller != selected)
6871 if (UIViewController *top = [controller topViewController])
6876 - (void) setUnselectedViewController:(UIViewController *)transient {
6877 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6878 if (transient != nil) {
6879 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6880 [self setSelectedIndex:0];
6884 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6885 if (transient != nil) {
6886 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6887 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6888 transient = navigation;
6890 if (transient_ == nil)
6891 remembered_ = [controllers objectAtIndex:0];
6892 transient_ = transient;
6893 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6894 [controllers replaceObjectAtIndex:0 withObject:transient_];
6895 [self setSelectedIndex:0];
6896 [self setViewControllers:controllers];
6897 [self concealTabBarSelection];
6898 } else if (remembered_ != nil) {
6899 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6900 transient_ = transient;
6901 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6903 [self setViewControllers:controllers];
6904 [self revealTabBarSelection];
6908 - (UIViewController *) unselectedViewController {
6912 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6913 if ([self unselectedViewController])
6914 [self setUnselectedViewController:nil];
6916 // presenting a UINavigationController on 2.x does not update its transitionView
6917 // if this view was unloaded, the tranitionView may currently be presenting nothing
6918 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6919 UINavigationController *navigation((UINavigationController *) viewController);
6920 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6921 [navigation popViewControllerAnimated:NO];
6925 - (NSArray *) navigationURLCollection {
6926 NSMutableArray *items([NSMutableArray array]);
6928 // XXX: Should this deal with transient view controllers?
6929 for (id navigation in [self viewControllers]) {
6930 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6932 [items addObject:stack];
6938 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6939 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6940 [self setUnselectedViewController:nil];
6942 [super dismissModalViewControllerAnimated:YES];
6945 - (void) unloadData {
6948 for (UINavigationController *controller in [self viewControllers])
6949 [controller unloadData];
6951 if (UIViewController *selected = [self selectedViewController])
6952 [selected reloadData];
6954 if (UIViewController *unselected = [self unselectedViewController]) {
6955 [unselected unloadData];
6956 [unselected reloadData];
6961 [[NSNotificationCenter defaultCenter] removeObserver:self];
6966 - (id) initWithDatabase:(Database *)database {
6967 if ((self = [super init]) != nil) {
6968 database_ = database;
6969 [self setDelegate:self];
6971 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6972 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6974 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6978 - (void) setUpdate:(NSDate *)date {
6982 - (void) beginUpdate {
6983 [(RefreshBar *) refreshbar_ start];
6986 [updatedelegate_ retainNetworkActivityIndicator];
6990 detachNewThreadSelector:@selector(performUpdate)
6996 - (void) performUpdate {
6997 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7000 status.setDelegate(self);
7001 [database_ updateWithStatus:status];
7004 performSelectorOnMainThread:@selector(completeUpdate)
7012 - (void) stopUpdateWithSelector:(SEL)selector {
7014 [updatedelegate_ releaseNetworkActivityIndicator];
7016 [self raiseBar:YES];
7019 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7022 - (void) completeUpdate {
7025 [self stopUpdateWithSelector:@selector(reloadData)];
7028 - (void) cancelUpdate {
7029 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7032 - (void) cancelPressed {
7033 [self cancelUpdate];
7040 - (void) addProgressEvent:(CydiaProgressEvent *)event {
7041 [refreshbar_ setPrompt:[event compoundMessage]];
7044 - (bool) isProgressCancelled {
7048 - (void) setProgressCancellable:(NSNumber *)cancellable {
7049 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
7052 - (void) setProgressPercent:(NSNumber *)percent {
7053 [refreshbar_ setProgress:[percent floatValue]];
7056 - (void) setProgressStatus:(NSDictionary *)status {
7058 [self setProgressPercent:[status objectForKey:@"Percent"]];
7061 - (void) setUpdateDelegate:(id)delegate {
7062 updatedelegate_ = delegate;
7065 - (UIView *) transitionView {
7066 if ([self respondsToSelector:@selector(_transitionView)])
7067 return [self _transitionView];
7069 return MSHookIvar<id>(self, "_viewControllerTransitionView");
7072 - (void) dropBar:(BOOL)animated {
7077 UIView *transition([self transitionView]);
7078 [[self view] addSubview:refreshbar_];
7080 CGRect barframe([refreshbar_ frame]);
7082 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
7083 barframe.origin.y = CYStatusBarHeight();
7085 barframe.origin.y = 0;
7087 [refreshbar_ setFrame:barframe];
7090 [UIView beginAnimations:nil context:NULL];
7092 CGRect viewframe = [transition frame];
7093 viewframe.origin.y += barframe.size.height;
7094 viewframe.size.height -= barframe.size.height;
7095 [transition setFrame:viewframe];
7098 [UIView commitAnimations];
7100 // Ensure bar has the proper width for our view, it might have changed
7101 barframe.size.width = viewframe.size.width;
7102 [refreshbar_ setFrame:barframe];
7105 - (void) raiseBar:(BOOL)animated {
7110 UIView *transition([self transitionView]);
7111 [refreshbar_ removeFromSuperview];
7113 CGRect barframe([refreshbar_ frame]);
7116 [UIView beginAnimations:nil context:NULL];
7118 CGRect viewframe = [transition frame];
7119 viewframe.origin.y -= barframe.size.height;
7120 viewframe.size.height += barframe.size.height;
7121 [transition setFrame:viewframe];
7124 [UIView commitAnimations];
7127 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7128 bool dropped(dropped_);
7133 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7139 - (void) statusBarFrameChanged:(NSNotification *)notification {
7149 /* Cydia Navigation Controller Implementation {{{ */
7150 @implementation UINavigationController (Cydia)
7152 - (NSArray *) navigationURLCollection {
7153 NSMutableArray *stack([NSMutableArray array]);
7155 for (CyteViewController *controller in [self viewControllers]) {
7156 NSString *url = [[controller navigationURL] absoluteString];
7158 [stack addObject:url];
7164 - (void) reloadData {
7167 UIViewController *visible([self visibleViewController]);
7169 [visible reloadData];
7171 // on the iPad, this view controller is ALSO visible. :(
7173 if (UIViewController *top = [self topViewController])
7178 - (void) unloadData {
7179 for (CyteViewController *page in [self viewControllers])
7188 /* Cydia:// Protocol {{{ */
7189 @interface CydiaURLProtocol : NSURLProtocol {
7194 @implementation CydiaURLProtocol
7196 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7197 NSURL *url([request URL]);
7201 NSString *scheme([[url scheme] lowercaseString]);
7202 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7204 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7210 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7214 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7215 id<NSURLProtocolClient> client([self client]);
7217 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7219 NSData *data(UIImagePNGRepresentation(icon));
7221 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7222 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7223 [client URLProtocol:self didLoadData:data];
7224 [client URLProtocolDidFinishLoading:self];
7228 - (void) startLoading {
7229 id<NSURLProtocolClient> client([self client]);
7230 NSURLRequest *request([self request]);
7232 NSURL *url([request URL]);
7233 NSString *href([url absoluteString]);
7234 NSString *scheme([[url scheme] lowercaseString]);
7238 if ([scheme isEqualToString:@"cydia"])
7239 path = [href substringFromIndex:8];
7240 else if ([scheme isEqualToString:@"about"])
7241 path = [href substringFromIndex:12];
7242 else _assert(false);
7244 NSRange slash([path rangeOfString:@"/"]);
7247 if (slash.location == NSNotFound) {
7251 command = [path substringToIndex:slash.location];
7252 path = [path substringFromIndex:(slash.location + 1)];
7255 Database *database([Database sharedInstance]);
7257 if ([command isEqualToString:@"package-icon"]) {
7260 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7261 Package *package([database packageWithName:path]);
7265 UIImage *icon([package icon]);
7266 [self _returnPNGWithImage:icon forRequest:request];
7267 } else if ([command isEqualToString:@"uikit-image"]) {
7270 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7271 UIImage *icon(_UIImageWithName(path));
7272 [self _returnPNGWithImage:icon forRequest:request];
7273 } else if ([command isEqualToString:@"section-icon"]) {
7276 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7277 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7279 icon = [UIImage applicationImageNamed:@"unknown.png"];
7280 [self _returnPNGWithImage:icon forRequest:request];
7282 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7286 - (void) stopLoading {
7292 /* Section Controller {{{ */
7293 @interface SectionController : FilteredPackageListController {
7294 _H<IndirectDelegate, 1> indirect_;
7295 _H<CydiaObject> cydia_;
7296 _H<NSString> section_;
7297 std::vector< _H<CyteWebViewTableViewCell, 1> > promoted_;
7300 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7304 @implementation SectionController
7306 - (NSURL *) referrerURL {
7307 NSString *name = section_;
7311 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@", UI_, [name stringByAddingPercentEscapesIncludingReserved]]];
7314 - (NSURL *) navigationURL {
7315 NSString *name = section_;
7319 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7322 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7325 title = UCLocalize("ALL_PACKAGES");
7326 else if (![name isEqual:@""])
7327 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7329 title = UCLocalize("NO_SECTION");
7331 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7332 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7333 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7338 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7339 return [super numberOfSectionsInTableView:list] + 1;
7342 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7343 return section == 0 ? nil : [super tableView:list titleForHeaderInSection:(section - 1)];
7346 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7347 return section == 0 ? promoted_.size() : [super tableView:list numberOfRowsInSection:(section - 1)];
7350 + (NSIndexPath *) adjustedIndexPath:(NSIndexPath *)path {
7351 return [NSIndexPath indexPathForRow:[path row] inSection:([path section] - 1)];
7354 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7355 if ([path section] != 0)
7356 return [super tableView:table cellForRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7358 return promoted_[[path row]];
7361 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
7362 if ([path section] != 0)
7363 return [super tableView:table didSelectRowAtIndexPath:[SectionController adjustedIndexPath:path]];
7366 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
7367 NSInteger section([super tableView:tableView sectionForSectionIndexTitle:title atIndex:index]);
7368 return section == 0 ? 0 : section + 1;
7371 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7372 NSURL *url([request URL]);
7376 if ([frame isEqualToString:@"_open"])
7377 [delegate_ openURL:url];
7379 WebFrame *frame(nil);
7380 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7381 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7383 frame = [view mainFrame];
7385 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7387 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7388 [controller setDelegate:delegate_];
7389 [[self navigationController] pushViewController:controller animated:YES];
7395 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7396 return [CydiaWebViewController requestWithHeaders:request];
7399 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7400 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7406 // XXX: this code is horrible. I mean, wtf Jay?
7407 if (ShowPromoted_ && [[Metadata_ objectForKey:@"ShowPromoted"] boolValue]) {
7408 promoted_.resize(1);
7410 for (unsigned i(0); i != promoted_.size(); ++i) {
7411 CyteWebViewTableViewCell *promoted([CyteWebViewTableViewCell cellWithRequest:[NSURLRequest
7412 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sectionhead/%u/%@",
7413 UI_, i, section_ == nil ? @"" : [section_ stringByAddingPercentEscapesIncludingReserved]]
7416 cachePolicy:NSURLRequestUseProtocolCachePolicy
7420 [promoted setDelegate:self];
7421 promoted_[i] = promoted;
7426 - (void) setDelegate:(id)delegate {
7427 [super setDelegate:delegate];
7428 [cydia_ setDelegate:delegate];
7431 - (void) releaseSubviews {
7433 [super releaseSubviews];
7438 /* Sections Controller {{{ */
7439 @interface SectionsController : CyteViewController <
7440 UITableViewDataSource,
7443 _transient Database *database_;
7444 _H<NSMutableArray> sections_;
7445 _H<NSMutableArray> filtered_;
7446 _H<UITableView, 2> list_;
7449 - (id) initWithDatabase:(Database *)database;
7450 - (void) editButtonClicked;
7454 @implementation SectionsController
7456 - (NSURL *) navigationURL {
7457 return [NSURL URLWithString:@"cydia://sections"];
7460 - (void) updateNavigationItem {
7461 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7462 if ([sections_ count] == 0) {
7463 [[self navigationItem] setRightBarButtonItem:nil];
7465 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7466 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7468 action:@selector(editButtonClicked)
7469 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7473 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7474 [super setEditing:editing animated:animated];
7479 [delegate_ updateData];
7481 [self updateNavigationItem];
7484 - (void) viewDidAppear:(BOOL)animated {
7485 [super viewDidAppear:animated];
7486 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7489 - (void) viewWillDisappear:(BOOL)animated {
7490 [super viewWillDisappear:animated];
7491 [self setEditing:NO];
7494 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7495 Section *section = nil;
7496 int index = [indexPath row];
7497 if (![self isEditing]) {
7500 section = [filtered_ objectAtIndex:index];
7502 section = [sections_ objectAtIndex:index];
7507 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7508 if ([self isEditing])
7509 return [sections_ count];
7511 return [filtered_ count] + 1;
7514 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7518 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7519 static NSString *reuseIdentifier = @"SectionCell";
7521 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7523 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7525 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7530 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7531 if ([self isEditing])
7534 Section *section = [self sectionAtIndexPath:indexPath];
7536 SectionController *controller = [[[SectionController alloc]
7537 initWithDatabase:database_
7538 section:[section name]
7540 [controller setDelegate:delegate_];
7542 [[self navigationController] pushViewController:controller animated:YES];
7546 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7547 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7548 [list_ setRowHeight:45.0f];
7549 [(UITableView *) list_ setDataSource:self];
7550 [list_ setDelegate:self];
7551 [self setView:list_];
7554 - (void) viewDidLoad {
7555 [super viewDidLoad];
7557 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7560 - (void) releaseSubviews {
7566 [super releaseSubviews];
7569 - (id) initWithDatabase:(Database *)database {
7570 if ((self = [super init]) != nil) {
7571 database_ = database;
7575 - (void) reloadData {
7578 NSArray *packages = [database_ packages];
7580 sections_ = [NSMutableArray arrayWithCapacity:16];
7581 filtered_ = [NSMutableArray arrayWithCapacity:16];
7583 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7586 for (Package *package in packages) {
7587 NSString *name([package section]);
7588 NSString *key(name == nil ? @"" : name);
7592 _profile(SectionsView$reloadData$Section)
7593 section = [sections objectForKey:key];
7594 if (section == nil) {
7595 _profile(SectionsView$reloadData$Section$Allocate)
7596 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7597 [sections setObject:section forKey:key];
7602 [section addToCount];
7604 _profile(SectionsView$reloadData$Filter)
7605 if (![package valid] || ![package visible])
7613 [sections_ addObjectsFromArray:[sections allValues]];
7615 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7617 for (Section *section in (id) sections_) {
7618 size_t count([section row]);
7622 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7623 [section setCount:count];
7624 [filtered_ addObject:section];
7627 [self updateNavigationItem];
7632 - (void) editButtonClicked {
7633 [self setEditing:![self isEditing] animated:YES];
7639 /* Changes Controller {{{ */
7640 @interface ChangesController : CyteViewController <
7641 UITableViewDataSource,
7644 _transient Database *database_;
7646 _H<NSArray> packages_;
7647 _H<NSMutableArray> sections_;
7648 _H<UITableView, 2> list_;
7649 _H<CyteWebView, 1> dickbar_;
7651 _H<IndirectDelegate, 1> indirect_;
7652 _H<CydiaObject> cydia_;
7655 - (id) initWithDatabase:(Database *)database;
7659 @implementation ChangesController
7661 - (NSURL *) navigationURL {
7662 return [NSURL URLWithString:@"cydia://changes"];
7665 - (void) viewDidAppear:(BOOL)animated {
7666 [super viewDidAppear:animated];
7667 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7670 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7671 NSInteger count([sections_ count]);
7672 return count == 0 ? 1 : count;
7675 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7676 if ([sections_ count] == 0)
7678 return [[sections_ objectAtIndex:section] name];
7681 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7682 if ([sections_ count] == 0)
7684 return [[sections_ objectAtIndex:section] count];
7687 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7688 @synchronized (database_) {
7689 if ([database_ era] != era_)
7692 NSUInteger sectionIndex([path section]);
7693 if (sectionIndex >= [sections_ count])
7695 Section *section([sections_ objectAtIndex:sectionIndex]);
7696 NSInteger row([path row]);
7697 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7700 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7701 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7703 cell = [[[PackageCell alloc] init] autorelease];
7705 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7706 [cell setPackage:package asSummary:false];
7710 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7711 Package *package([self packageAtIndexPath:path]);
7712 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[NSString stringWithFormat:@"%@/#!/changes/", UI_]] autorelease]);
7713 [view setDelegate:delegate_];
7714 [[self navigationController] pushViewController:view animated:YES];
7718 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7719 NSString *context([alert context]);
7721 if ([context isEqualToString:@"norefresh"])
7722 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7725 - (void) refreshButtonClicked {
7726 if (IsReachable("cydia.saurik.com")) {
7727 [delegate_ beginUpdate];
7728 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7730 UIAlertView *alert = [[[UIAlertView alloc]
7731 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
7732 message:@"Host Unreachable" // XXX: Localize
7734 cancelButtonTitle:UCLocalize("OK")
7735 otherButtonTitles:nil
7738 [alert setContext:@"norefresh"];
7743 - (void) upgradeButtonClicked {
7744 [delegate_ distUpgrade];
7745 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7749 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7750 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7751 [self setView:view];
7753 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7754 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7755 [list_ setRowHeight:73];
7756 [(UITableView *) list_ setDataSource:self];
7757 [list_ setDelegate:self];
7758 [view addSubview:list_];
7760 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7761 CGRect dickframe([view bounds]);
7762 dickframe.size.height = 44;
7764 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7765 [dickbar_ setDelegate:self];
7766 [view addSubview:dickbar_];
7768 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7769 [dickbar_ setScalesPageToFit:YES];
7771 UIWebDocumentView *document([dickbar_ _documentView]);
7772 [document setBackgroundColor:[UIColor clearColor]];
7773 [document setDrawsBackground:NO];
7775 WebView *webview([document webView]);
7776 [webview setShouldUpdateWhileOffscreen:NO];
7778 UIScrollView *scroller([dickbar_ scrollView]);
7779 [scroller setScrollingEnabled:NO];
7780 [scroller setFixedBackgroundPattern:YES];
7781 [scroller setBackgroundColor:[UIColor clearColor]];
7783 WebPreferences *preferences([webview preferences]);
7784 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7785 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7786 [preferences setOfflineWebApplicationCacheEnabled:YES];
7788 [dickbar_ loadRequest:[NSURLRequest
7789 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7790 cachePolicy:NSURLRequestUseProtocolCachePolicy
7794 UIEdgeInsets inset = {44, 0, 0, 0};
7795 [list_ setContentInset:inset];
7797 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7801 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7802 NSURL *url([request URL]);
7806 if ([frame isEqualToString:@"_open"])
7807 [delegate_ openURL:url];
7809 WebFrame *frame(nil);
7810 if (NSDictionary *WebActionElement = [action objectForKey:@"WebActionElementKey"])
7811 frame = [WebActionElement objectForKey:@"WebElementFrame"];
7813 frame = [view mainFrame];
7815 WebDataSource *source([frame provisionalDataSource] ?: [frame dataSource]);
7817 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO withReferrer:([request valueForHTTPHeaderField:@"Referer"] ?: [[[source request] URL] absoluteString])] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7818 [controller setDelegate:delegate_];
7819 [[self navigationController] pushViewController:controller animated:YES];
7825 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7826 return [CydiaWebViewController requestWithHeaders:request];
7829 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7830 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7833 - (void) setDelegate:(id)delegate {
7834 [super setDelegate:delegate];
7835 [cydia_ setDelegate:delegate];
7838 - (void) viewDidLoad {
7839 [super viewDidLoad];
7841 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7844 - (void) releaseSubviews {
7851 [super releaseSubviews];
7854 - (id) initWithDatabase:(Database *)database {
7855 if ((self = [super init]) != nil) {
7856 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7857 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7858 database_ = database;
7862 - (NSMutableArray *) _reloadPackages {
7863 @synchronized (database_) {
7864 era_ = [database_ era];
7865 NSArray *packages([database_ packages]);
7867 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7870 _profile(ChangesController$_reloadPackages$Filter)
7871 for (Package *package in packages)
7872 if ([package upgradableAndEssential:YES] || [package visible])
7873 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7876 _profile(ChangesController$_reloadPackages$radixSort)
7877 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7884 - (void) _reloadData {
7889 UIProgressHUD *hud([delegate_ addProgressHUD]);
7890 [hud setText:UCLocalize("LOADING")];
7891 //NSLog(@"HUD:%@::%@", delegate_, hud);
7892 packages = [self yieldToSelector:@selector(_reloadPackages)];
7893 [delegate_ removeProgressHUD:hud];
7895 packages = [self _reloadPackages];
7898 @synchronized (database_) {
7899 if (era_ != [database_ era])
7902 packages_ = packages;
7903 sections_ = [NSMutableArray arrayWithCapacity:16];
7905 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7906 Section *ignored = nil;
7907 Section *section = nil;
7911 bool unseens = false;
7913 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7915 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7916 Package *package = [packages_ objectAtIndex:offset];
7918 BOOL uae = [package upgradableAndEssential:YES];
7922 time_t seen([package seen]);
7924 if (section == nil || last != seen) {
7928 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7931 _profile(ChangesController$reloadData$Allocate)
7932 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7933 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7934 [sections_ addObject:section];
7938 [section addToCount];
7939 } else if ([package ignored]) {
7940 if (ignored == nil) {
7941 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7943 [ignored addToCount];
7946 [upgradable addToCount];
7951 CFRelease(formatter);
7954 Section *last = [sections_ lastObject];
7955 size_t count = [last count];
7956 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7957 [sections_ removeLastObject];
7960 if ([ignored count] != 0)
7961 [sections_ insertObject:ignored atIndex:0];
7963 [sections_ insertObject:upgradable atIndex:0];
7967 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7968 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7969 style:UIBarButtonItemStylePlain
7971 action:@selector(upgradeButtonClicked)
7972 ] autorelease]) animated:YES];
7974 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7975 initWithTitle:UCLocalize("REFRESH")
7976 style:UIBarButtonItemStylePlain
7978 action:@selector(refreshButtonClicked)
7979 ] autorelease]) animated:YES];
7984 - (void) reloadData {
7986 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7991 /* Search Controller {{{ */
7992 @interface SearchController : FilteredPackageListController <
7995 _H<UISearchBar, 1> search_;
7999 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
8000 - (void) reloadData;
8004 @implementation SearchController
8006 - (NSURL *) referrerURL {
8007 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
8010 - (NSURL *) navigationURL {
8011 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
8012 return [NSURL URLWithString:@"cydia://search"];
8014 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
8017 - (NSArray *) termsForQuery:(NSString *)query {
8018 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
8019 for (NSString *component in [query componentsSeparatedByString:@" "])
8020 if ([component length] != 0)
8021 [terms addObject:component];
8026 - (void) useSearch {
8027 [self setObject:[self termsForQuery:[search_ text]] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
8032 - (void) viewWillAppear:(BOOL)animated {
8033 [super viewWillAppear:animated];
8035 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
8039 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
8040 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8045 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
8046 [search_ resignFirstResponder];
8050 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
8051 [search_ setText:@""];
8052 [self searchBarButtonClicked:searchBar];
8055 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
8056 [self searchBarButtonClicked:searchBar];
8059 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
8060 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
8064 - (bool) shouldYield {
8068 - (bool) shouldBlock {
8069 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
8072 - (bool) isSummarized {
8073 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
8076 - (bool) showsSections {
8080 - (NSMutableArray *) _reloadPackages {
8081 NSMutableArray *packages([super _reloadPackages]);
8082 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8083 [packages radixSortUsingSelector:@selector(rank)];
8087 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
8088 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[self termsForQuery:query]])) {
8089 search_ = [[[UISearchBar alloc] init] autorelease];
8090 [search_ setDelegate:self];
8093 [search_ setText:query];
8097 - (void) viewDidAppear:(BOOL)animated {
8098 [super viewDidAppear:animated];
8100 if (!searchloaded_) {
8101 searchloaded_ = YES;
8102 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
8103 [search_ layoutSubviews];
8104 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
8106 UITextField *textField;
8107 if ([search_ respondsToSelector:@selector(searchField)])
8108 textField = [search_ searchField];
8110 textField = MSHookIvar<UITextField *>(search_, "_searchField");
8112 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8113 [textField setEnablesReturnKeyAutomatically:NO];
8114 [[self navigationItem] setTitleView:textField];
8118 - (void) reloadData {
8119 id object([search_ text]);
8120 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
8121 object = [self termsForQuery:object];
8123 [self setObject:object];
8129 - (void) didSelectPackage:(Package *)package {
8130 [search_ resignFirstResponder];
8131 [super didSelectPackage:package];
8136 /* Package Settings Controller {{{ */
8137 @interface PackageSettingsController : CyteViewController <
8138 UITableViewDataSource,
8141 _transient Database *database_;
8143 _H<Package> package_;
8144 _H<UITableView, 2> table_;
8145 _H<UISwitch> subscribedSwitch_;
8146 _H<UISwitch> ignoredSwitch_;
8147 _H<UITableViewCell> subscribedCell_;
8148 _H<UITableViewCell> ignoredCell_;
8151 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
8155 @implementation PackageSettingsController
8157 - (NSURL *) navigationURL {
8158 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
8161 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8162 if (package_ == nil)
8165 if ([package_ installed] == nil)
8171 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8172 if (package_ == nil)
8175 // both sections contain just one item right now.
8179 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8183 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8185 return UCLocalize("SHOW_ALL_CHANGES_EX");
8187 return UCLocalize("IGNORE_UPGRADES_EX");
8190 - (void) onSubscribed:(id)control {
8191 bool value([control isOn]);
8192 if (package_ == nil)
8194 if ([package_ setSubscribed:value])
8195 [delegate_ updateData];
8198 - (void) _updateIgnored {
8199 const char *package([name_ UTF8String]);
8200 bool on([ignoredSwitch_ isOn]);
8202 pid_t pid(ExecFork());
8204 FILE *dpkg(popen("dpkg --set-selections", "w"));
8205 fwrite(package, strlen(package), 1, dpkg);
8208 fwrite(" hold\n", 6, 1, dpkg);
8210 fwrite(" install\n", 9, 1, dpkg);
8221 - (void) onIgnored:(id)control {
8222 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8223 [invocation setTarget:self];
8224 [invocation setSelector:@selector(_updateIgnored)];
8226 [delegate_ reloadDataWithInvocation:invocation];
8229 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8230 if (package_ == nil)
8233 switch ([indexPath section]) {
8234 case 0: return subscribedCell_;
8235 case 1: return ignoredCell_;
8244 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8245 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8246 [self setView:view];
8248 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8249 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8250 [(UITableView *) table_ setDataSource:self];
8251 [table_ setDelegate:self];
8252 [view addSubview:table_];
8254 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8255 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8256 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8258 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8259 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8260 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8262 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8263 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8264 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8265 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8267 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8268 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8269 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8270 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8273 - (void) viewDidLoad {
8274 [super viewDidLoad];
8276 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8279 - (void) releaseSubviews {
8281 subscribedCell_ = nil;
8283 ignoredSwitch_ = nil;
8284 subscribedSwitch_ = nil;
8286 [super releaseSubviews];
8289 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8290 if ((self = [super init]) != nil) {
8291 database_ = database;
8296 - (void) reloadData {
8299 package_ = [database_ packageWithName:name_];
8301 if (package_ != nil) {
8302 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8303 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8304 } // XXX: what now, G?
8306 [table_ reloadData];
8312 /* Installed Controller {{{ */
8313 @interface InstalledController : FilteredPackageListController {
8317 - (id) initWithDatabase:(Database *)database;
8319 - (void) updateRoleButton;
8320 - (void) queueStatusDidChange;
8324 @implementation InstalledController
8326 - (NSURL *) referrerURL {
8327 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8330 - (NSURL *) navigationURL {
8331 return [NSURL URLWithString:@"cydia://installed"];
8334 - (id) initWithDatabase:(Database *)database {
8335 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8336 [self updateRoleButton];
8337 [self queueStatusDidChange];
8342 - (void) queueButtonClicked {
8347 - (void) queueStatusDidChange {
8351 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8352 initWithTitle:UCLocalize("QUEUE")
8353 style:UIBarButtonItemStyleDone
8355 action:@selector(queueButtonClicked)
8358 [[self navigationItem] setLeftBarButtonItem:nil];
8364 - (void) updateRoleButton {
8365 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8366 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8367 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8368 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8370 action:@selector(roleButtonClicked)
8374 - (void) roleButtonClicked {
8375 [self setObject:[NSNumber numberWithBool:expert_]];
8379 [self updateRoleButton];
8385 /* Source Cell {{{ */
8386 @interface SourceCell : CyteTableViewCell <
8387 CyteTableViewCellDelegate
8391 _H<NSString> origin_;
8392 _H<NSString> label_;
8395 - (void) setSource:(Source *)source;
8399 @implementation SourceCell
8401 - (void) _setImage:(NSArray *)data {
8402 if ([url_ isEqual:[data objectAtIndex:0]]) {
8403 icon_ = [data objectAtIndex:1];
8404 [content_ setNeedsDisplay];
8408 - (void) _setSource:(NSURL *) url {
8409 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8411 if (NSData *data = [NSURLConnection
8412 sendSynchronousRequest:[NSURLRequest
8414 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8418 returningResponse:NULL
8421 if (UIImage *image = [UIImage imageWithData:data])
8422 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8427 - (void) setSource:(Source *)source {
8428 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8430 origin_ = [source name];
8431 label_ = [source rooturi];
8433 [content_ setNeedsDisplay];
8435 url_ = [source iconURL];
8436 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8439 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8440 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8441 UIView *content([self contentView]);
8442 CGRect bounds([content bounds]);
8444 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8445 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8446 [content_ setBackgroundColor:[UIColor whiteColor]];
8447 [content addSubview:content_];
8449 [content_ setDelegate:self];
8450 [content_ setOpaque:YES];
8452 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8456 - (NSString *) accessibilityLabel {
8460 - (void) drawContentRect:(CGRect)rect {
8461 bool highlighted(highlighted_);
8462 float width(rect.size.width);
8466 rect.size = [(UIImage *) icon_ size];
8468 while (rect.size.width > 32 || rect.size.height > 32) {
8469 rect.size.width /= 2;
8470 rect.size.height /= 2;
8473 rect.origin.x = 25 - rect.size.width / 2;
8474 rect.origin.y = 25 - rect.size.height / 2;
8476 [icon_ drawInRect:rect];
8484 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8488 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8493 /* Source Controller {{{ */
8494 @interface SourceController : FilteredPackageListController {
8495 _transient Source *source_;
8499 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8503 @implementation SourceController
8505 - (NSURL *) referrerURL {
8506 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sources/%@", UI_, [key_ stringByAddingPercentEscapesIncludingReserved]]];
8509 - (NSURL *) navigationURL {
8510 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8513 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8514 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8516 key_ = [source key];
8520 - (void) reloadData {
8521 source_ = [database_ sourceWithKey:key_];
8522 key_ = [source_ key];
8523 [self setObject:source_];
8525 [[self navigationItem] setTitle:[source_ label]];
8532 /* Sources Controller {{{ */
8533 @interface SourcesController : CyteViewController <
8534 UITableViewDataSource,
8537 _transient Database *database_;
8540 _H<UITableView, 2> list_;
8541 _H<NSMutableArray> sources_;
8545 _H<UIProgressHUD> hud_;
8548 //NSURLConnection *installer_;
8549 NSURLConnection *trivial_;
8550 NSURLConnection *trivial_bz2_;
8551 NSURLConnection *trivial_gz_;
8552 //NSURLConnection *automatic_;
8557 - (id) initWithDatabase:(Database *)database;
8558 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8562 @implementation SourcesController
8564 - (void) _releaseConnection:(NSURLConnection *)connection {
8565 if (connection != nil) {
8566 [connection cancel];
8567 //[connection setDelegate:nil];
8568 [connection release];
8573 //[self _releaseConnection:installer_];
8574 [self _releaseConnection:trivial_];
8575 [self _releaseConnection:trivial_gz_];
8576 [self _releaseConnection:trivial_bz2_];
8577 //[self _releaseConnection:automatic_];
8582 - (NSURL *) navigationURL {
8583 return [NSURL URLWithString:@"cydia://sources"];
8586 - (void) viewDidAppear:(BOOL)animated {
8587 [super viewDidAppear:animated];
8588 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8591 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8595 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8599 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8600 return [sources_ count];
8603 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8604 @synchronized (database_) {
8605 if ([database_ era] != era_)
8608 NSUInteger index([indexPath row]);
8609 return index < [sources_ count] ? [sources_ objectAtIndex:index] : nil;
8612 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8613 static NSString *cellIdentifier = @"SourceCell";
8615 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8616 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8617 [cell setSource:[self sourceAtIndexPath:indexPath]];
8618 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8623 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8624 Source *source = [self sourceAtIndexPath:indexPath];
8625 if (source == nil) return;
8627 SourceController *controller = [[[SourceController alloc]
8628 initWithDatabase:database_
8632 [controller setDelegate:delegate_];
8634 [[self navigationController] pushViewController:controller animated:YES];
8637 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8638 Source *source = [self sourceAtIndexPath:indexPath];
8639 return [source record] != nil;
8642 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8643 if (editingStyle == UITableViewCellEditingStyleDelete) {
8644 Source *source = [self sourceAtIndexPath:indexPath];
8645 if (source == nil) return;
8647 [Sources_ removeObjectForKey:[source key]];
8648 [delegate_ _saveConfig];
8649 [delegate_ reloadDataWithInvocation:nil];
8654 [delegate_ addTrivialSource:href_];
8657 [delegate_ syncData];
8660 - (NSString *) getWarning {
8661 NSString *href(href_);
8662 NSRange colon([href rangeOfString:@"://"]);
8663 if (colon.location != NSNotFound)
8664 href = [href substringFromIndex:(colon.location + 3)];
8665 href = [href stringByAddingPercentEscapes];
8666 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8668 NSURL *url([NSURL URLWithString:href]);
8670 NSStringEncoding encoding;
8671 NSError *error(nil);
8673 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8674 return [warning length] == 0 ? nil : warning;
8678 - (void) _endConnection:(NSURLConnection *)connection {
8679 // XXX: the memory management in this method is horribly awkward
8681 NSURLConnection **field = NULL;
8682 if (connection == trivial_)
8684 else if (connection == trivial_bz2_)
8685 field = &trivial_bz2_;
8686 else if (connection == trivial_gz_)
8687 field = &trivial_gz_;
8688 _assert(field != NULL);
8689 [connection release];
8694 trivial_bz2_ == nil &&
8697 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8699 [delegate_ releaseNetworkActivityIndicator];
8701 [delegate_ removeProgressHUD:hud_];
8705 if (warning != nil) {
8706 UIAlertView *alert = [[[UIAlertView alloc]
8707 initWithTitle:UCLocalize("SOURCE_WARNING")
8710 cancelButtonTitle:UCLocalize("CANCEL")
8712 UCLocalize("ADD_ANYWAY"),
8716 [alert setContext:@"warning"];
8717 [alert setNumberOfRows:1];
8720 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8726 } else if (error_ != nil) {
8727 UIAlertView *alert = [[[UIAlertView alloc]
8728 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8729 message:[error_ localizedDescription]
8731 cancelButtonTitle:UCLocalize("OK")
8732 otherButtonTitles:nil
8735 [alert setContext:@"urlerror"];
8740 UIAlertView *alert = [[[UIAlertView alloc]
8741 initWithTitle:UCLocalize("NOT_REPOSITORY")
8742 message:UCLocalize("NOT_REPOSITORY_EX")
8744 cancelButtonTitle:UCLocalize("OK")
8745 otherButtonTitles:nil
8748 [alert setContext:@"trivial"];
8758 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8759 switch ([response statusCode]) {
8765 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8766 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8768 [self _endConnection:connection];
8771 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8772 [self _endConnection:connection];
8775 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8776 NSURL *url([NSURL URLWithString:href]);
8778 NSMutableURLRequest *request = [NSMutableURLRequest
8780 cachePolicy:NSURLRequestUseProtocolCachePolicy
8781 timeoutInterval:120.0
8784 [request setHTTPMethod:method];
8786 if (Machine_ != NULL)
8787 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8789 if ([url isCydiaSecure]) {
8790 if (UniqueID_ != nil) {
8791 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8792 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8796 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8799 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8800 NSString *context([alert context]);
8802 if ([context isEqualToString:@"source"]) {
8805 NSString *href = [[alert textField] text];
8807 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8809 if (![href hasSuffix:@"/"])
8810 href_ = [href stringByAppendingString:@"/"];
8814 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8815 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8816 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8817 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8821 // XXX: this is stupid
8822 hud_ = [delegate_ addProgressHUD];
8823 [hud_ setText:UCLocalize("VERIFYING_URL")];
8824 [delegate_ retainNetworkActivityIndicator];
8833 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8834 } else if ([context isEqualToString:@"trivial"])
8835 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8836 else if ([context isEqualToString:@"urlerror"])
8837 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8838 else if ([context isEqualToString:@"warning"]) {
8841 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8850 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8855 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8856 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8857 [list_ setRowHeight:53];
8858 [(UITableView *) list_ setDataSource:self];
8859 [list_ setDelegate:self];
8860 [self setView:list_];
8863 - (void) viewDidLoad {
8864 [super viewDidLoad];
8866 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8867 [self updateButtonsForEditingStatusAnimated:NO];
8870 - (void) viewWillDisappear:(BOOL)animated {
8871 [super viewWillAppear:animated];
8873 [list_ setEditing:NO];
8874 [self updateButtonsForEditingStatusAnimated:NO];
8877 - (void) releaseSubviews {
8882 [super releaseSubviews];
8885 - (id) initWithDatabase:(Database *)database {
8886 if ((self = [super init]) != nil) {
8887 database_ = database;
8891 - (void) reloadData {
8894 @synchronized (database_) {
8895 era_ = [database_ era];
8898 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8901 sources_ = [NSMutableArray arrayWithCapacity:16];
8902 [sources_ addObjectsFromArray:[database_ sources]];
8904 [sources_ sortUsingSelector:@selector(compareByName:)];
8907 int count([sources_ count]);
8909 for (int i = 0; i != count; i++) {
8910 if ([[sources_ objectAtIndex:i] record] == nil)
8918 - (void) showAddSourcePrompt {
8919 UIAlertView *alert = [[[UIAlertView alloc]
8920 initWithTitle:UCLocalize("ENTER_APT_URL")
8923 cancelButtonTitle:UCLocalize("CANCEL")
8925 UCLocalize("ADD_SOURCE"),
8929 [alert setContext:@"source"];
8931 [alert setNumberOfRows:1];
8932 [alert addTextFieldWithValue:@"http://" label:@""];
8934 UITextInputTraits *traits = [[alert textField] textInputTraits];
8935 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8936 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8937 [traits setKeyboardType:UIKeyboardTypeURL];
8938 // XXX: UIReturnKeyDone
8939 [traits setReturnKeyType:UIReturnKeyNext];
8944 - (void) addButtonClicked {
8945 [self showAddSourcePrompt];
8948 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8949 BOOL editing([list_ isEditing]);
8951 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8952 initWithTitle:UCLocalize("ADD")
8953 style:UIBarButtonItemStylePlain
8955 action:@selector(addButtonClicked)
8956 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8958 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8959 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8960 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8962 action:@selector(editButtonClicked)
8963 ] autorelease] animated:animated];
8965 if (IsWildcat_ && !editing)
8966 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8967 initWithTitle:UCLocalize("SETTINGS")
8968 style:UIBarButtonItemStylePlain
8970 action:@selector(settingsButtonClicked)
8974 - (void) settingsButtonClicked {
8975 [delegate_ showSettings];
8978 - (void) editButtonClicked {
8979 [list_ setEditing:![list_ isEditing] animated:YES];
8980 [self updateButtonsForEditingStatusAnimated:YES];
8986 /* Settings Controller {{{ */
8987 @interface SettingsController : CyteViewController <
8988 UITableViewDataSource,
8991 _transient Database *database_;
8992 // XXX: ok, "roledelegate_"?...
8993 _transient id roledelegate_;
8994 _H<UITableView, 2> table_;
8995 _H<UISegmentedControl> segment_;
8996 _H<UIView> container_;
8999 - (void) showDoneButton;
9000 - (void) resizeSegmentedControl;
9004 @implementation SettingsController
9007 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
9008 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9009 [table_ setDelegate:self];
9010 [(UITableView *) table_ setDataSource:self];
9011 [self setView:table_];
9013 NSArray *items = [NSArray arrayWithObjects:
9015 UCLocalize("HACKER"),
9016 UCLocalize("DEVELOPER"),
9018 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
9019 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
9020 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
9021 [container_ addSubview:segment_];
9024 - (void) viewDidLoad {
9025 [super viewDidLoad];
9027 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
9030 if ([Role_ isEqualToString:@"User"]) index = 0;
9031 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
9032 if ([Role_ isEqualToString:@"Developer"]) index = 2;
9034 [segment_ setSelectedSegmentIndex:index];
9035 [self showDoneButton];
9038 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
9039 [self resizeSegmentedControl];
9042 - (void) releaseSubviews {
9047 [super releaseSubviews];
9050 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
9051 if ((self = [super init]) != nil) {
9052 database_ = database;
9053 roledelegate_ = delegate;
9057 - (void) resizeSegmentedControl {
9058 CGFloat width = [[self view] frame].size.width;
9059 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
9062 - (void) viewWillAppear:(BOOL)animated {
9063 [super viewWillAppear:animated];
9065 [self resizeSegmentedControl];
9068 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
9069 [self resizeSegmentedControl];
9072 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
9073 [self resizeSegmentedControl];
9077 NSString *role(nil);
9079 switch ([segment_ selectedSegmentIndex]) {
9080 case 0: role = @"User"; break;
9081 case 1: role = @"Hacker"; break;
9082 case 2: role = @"Developer"; break;
9087 if (![role isEqualToString:Role_]) {
9088 bool rolling(Role_ == nil);
9091 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
9095 [Metadata_ setObject:Settings_ forKey:@"Settings"];
9099 [roledelegate_ loadData];
9101 [roledelegate_ updateData];
9105 - (void) segmentChanged:(UISegmentedControl *)control {
9106 [self showDoneButton];
9109 - (void) saveAndClose {
9112 [[self navigationItem] setRightBarButtonItem:nil];
9113 [[self navigationController] dismissModalViewControllerAnimated:YES];
9116 - (void) doneButtonClicked {
9117 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
9118 [spinner startAnimating];
9119 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
9120 [[self navigationItem] setRightBarButtonItem:spinItem];
9122 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
9125 - (void) showDoneButton {
9126 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
9127 initWithTitle:UCLocalize("DONE")
9128 style:UIBarButtonItemStyleDone
9130 action:@selector(doneButtonClicked)
9131 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
9134 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
9135 // XXX: For not having a single cell in the table, this sure is a lot of sections.
9139 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
9143 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
9144 return nil; // This method is required by the protocol.
9147 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
9149 return UCLocalize("ROLE_EX");
9151 return [NSString stringWithFormat:
9152 @"%@: %@\n%@: %@\n%@: %@",
9153 UCLocalize("USER"), UCLocalize("USER_EX"),
9154 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
9155 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
9160 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
9161 return section == 3 ? 44.0f : 0;
9164 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
9165 return section == 3 ? container_ : nil;
9168 - (void) reloadData {
9171 [table_ reloadData];
9176 /* Stash Controller {{{ */
9177 @interface StashController : CyteViewController {
9178 _H<UIActivityIndicatorView> spinner_;
9179 _H<UILabel> status_;
9180 _H<UILabel> caption_;
9185 @implementation StashController
9188 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
9189 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
9190 [self setView:view];
9192 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
9194 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
9195 CGRect spinrect = [spinner_ frame];
9196 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
9197 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
9198 [spinner_ setFrame:spinrect];
9199 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
9200 [view addSubview:spinner_];
9201 [spinner_ startAnimating];
9204 captrect.size.width = [[self view] frame].size.width;
9205 captrect.size.height = 40.0f;
9206 captrect.origin.x = 0;
9207 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
9208 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
9209 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
9210 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9211 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
9212 [caption_ setTextColor:[UIColor whiteColor]];
9213 [caption_ setBackgroundColor:[UIColor clearColor]];
9214 [caption_ setShadowColor:[UIColor blackColor]];
9215 [caption_ setTextAlignment:UITextAlignmentCenter];
9216 [view addSubview:caption_];
9219 statusrect.size.width = [[self view] frame].size.width;
9220 statusrect.size.height = 30.0f;
9221 statusrect.origin.x = 0;
9222 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
9223 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
9224 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
9225 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
9226 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
9227 [status_ setTextColor:[UIColor whiteColor]];
9228 [status_ setBackgroundColor:[UIColor clearColor]];
9229 [status_ setShadowColor:[UIColor blackColor]];
9230 [status_ setTextAlignment:UITextAlignmentCenter];
9231 [view addSubview:status_];
9234 - (void) releaseSubviews {
9239 [super releaseSubviews];
9245 @interface CYURLCache : SDURLCache {
9250 @implementation CYURLCache
9252 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
9255 else if ([event isEqualToString:@"no-cache"])
9257 else if ([event isEqualToString:@"store"])
9259 else if ([event isEqualToString:@"invalid"])
9261 else if ([event isEqualToString:@"memory"])
9263 else if ([event isEqualToString:@"disk"])
9265 else if ([event isEqualToString:@"miss"])
9268 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9272 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9273 if (NSURLResponse *response = [cached response])
9274 if (NSString *mime = [response MIMEType])
9275 if ([mime isEqualToString:@"text/cache-manifest"]) {
9276 NSURL *url([response URL]);
9279 NSLog(@"###: %@", [url absoluteString]);
9282 @synchronized (HostConfig_) {
9283 [CachedURLs_ addObject:url];
9287 [super storeCachedResponse:cached forRequest:request];
9292 @interface Cydia : UIApplication <
9293 ConfirmationControllerDelegate,
9296 UINavigationControllerDelegate,
9297 UITabBarControllerDelegate
9299 _H<UIWindow> window_;
9300 _H<CYTabBarController> tabbar_;
9301 _H<CydiaLoadingViewController> emulated_;
9303 _H<NSMutableArray> essential_;
9304 _H<NSMutableArray> broken_;
9306 Database *database_;
9308 _H<NSURL> starturl_;
9313 _H<StashController> stash_;
9322 @implementation Cydia
9324 - (void) beginUpdate {
9325 [tabbar_ beginUpdate];
9329 return [tabbar_ updating];
9333 if ([broken_ count] != 0) {
9334 int count = [broken_ count];
9336 UIAlertView *alert = [[[UIAlertView alloc]
9337 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9338 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9340 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9342 UCLocalize("TEMPORARY_IGNORE"),
9346 [alert setContext:@"fixhalf"];
9347 [alert setNumberOfRows:2];
9349 } else if (!Ignored_ && [essential_ count] != 0) {
9350 int count = [essential_ count];
9352 UIAlertView *alert = [[[UIAlertView alloc]
9353 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9354 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9356 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9358 UCLocalize("UPGRADE_ESSENTIAL"),
9359 UCLocalize("COMPLETE_UPGRADE"),
9363 [alert setContext:@"upgrade"];
9368 - (void) returnToCydia {
9372 - (void) _saveConfig {
9373 @synchronized (database_) {
9380 NSString *error(nil);
9382 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9384 NSError *error(nil);
9385 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9386 NSLog(@"failure to save metadata data: %@", error);
9391 NSLog(@"failure to serialize metadata: %@", error);
9395 CydiaWriteSources();
9398 // Navigation controller for the queuing badge.
9399 - (UINavigationController *) queueNavigationController {
9400 NSArray *controllers = [tabbar_ viewControllers];
9401 return [controllers objectAtIndex:3];
9404 - (void) unloadData {
9405 [tabbar_ unloadData];
9408 - (void) _updateData {
9412 UINavigationController *navigation = [self queueNavigationController];
9414 id queuedelegate = nil;
9415 if ([[navigation viewControllers] count] > 0)
9416 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9418 [queuedelegate queueStatusDidChange];
9419 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9422 - (void) _refreshIfPossible:(NSDate *)update {
9423 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9425 bool recently = false;
9426 if (update != nil) {
9427 NSTimeInterval interval([update timeIntervalSinceNow]);
9428 if (interval <= 0 && interval > -(15*60))
9432 // Don't automatic refresh if:
9433 // - We already refreshed recently.
9434 // - We already auto-refreshed this launch.
9435 // - Auto-refresh is disabled.
9436 if (recently || loaded_ || ManualRefresh) {
9437 // If we are cancelling, we need to make sure it knows it's already loaded.
9440 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9442 // We are going to load, so remember that.
9445 // If we can reach the server, auto-refresh!
9446 if (IsReachable("cydia.saurik.com"))
9447 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9453 - (void) refreshIfPossible {
9454 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9457 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9458 @synchronized (self) {
9459 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9460 [hud setText:UCLocalize("RELOADING_DATA")];
9462 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9466 [essential_ removeAllObjects];
9467 [broken_ removeAllObjects];
9469 NSArray *packages([database_ packages]);
9470 for (Package *package in packages) {
9472 [broken_ addObject:package];
9473 if ([package upgradableAndEssential:NO] && ![package ignored]) {
9474 if ([package essential])
9475 [essential_ addObject:package];
9480 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9483 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9484 [changesItem setBadgeValue:badge];
9485 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9486 [self setApplicationIconBadgeNumber:changes];
9489 [changesItem setBadgeValue:nil];
9490 [changesItem setAnimatedBadge:NO];
9491 [self setApplicationIconBadgeNumber:0];
9497 [self removeProgressHUD:hud];
9500 - (void) updateData {
9504 - (void) updateDataAndLoad {
9506 if ([database_ progressDelegate] == nil)
9512 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9515 - (void) disemulate {
9516 if (emulated_ == nil)
9519 [window_ addSubview:[tabbar_ view]];
9520 [[emulated_ view] removeFromSuperview];
9522 [window_ setUserInteractionEnabled:YES];
9525 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9526 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9528 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9530 UIViewController *parent;
9531 if (emulated_ == nil)
9540 [parent presentModalViewController:navigation animated:YES];
9543 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9544 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9546 if (navigation != nil)
9547 [navigation pushViewController:progress animated:YES];
9549 [self presentModalViewController:progress force:YES];
9551 [progress invoke:invocation withTitle:title];
9555 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9556 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9559 - (void) repairWithInvocation:(NSInvocation *)invocation {
9561 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9565 - (void) repairWithSelector:(SEL)selector {
9566 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9569 - (void) reloadData {
9570 [self reloadDataWithInvocation:nil];
9571 if ([database_ progressDelegate] == nil)
9577 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9580 - (void) addSource:(NSDictionary *) source {
9581 CydiaAddSource(source);
9584 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9585 CydiaAddSource(href, distribution, sections);
9588 - (void) addTrivialSource:(NSString *)href {
9589 CydiaAddSource(href, @"./");
9592 - (void) updateValues {
9597 pkgProblemResolver *resolver = [database_ resolver];
9599 resolver->InstallProtect();
9600 if (!resolver->Resolve(true))
9605 // XXX: this is a really crappy way of doing this.
9606 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9607 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9608 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9609 if ([tabbar_ updating])
9610 [tabbar_ cancelUpdate];
9612 if (![database_ prepare])
9615 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9616 [page setDelegate:self];
9617 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9620 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9621 [tabbar_ presentModalViewController:confirm_ animated:YES];
9627 @synchronized (self) {
9632 - (void) clearPackage:(Package *)package {
9633 @synchronized (self) {
9640 - (void) installPackages:(NSArray *)packages {
9641 @synchronized (self) {
9642 for (Package *package in packages)
9649 - (void) installPackage:(Package *)package {
9650 @synchronized (self) {
9657 - (void) removePackage:(Package *)package {
9658 @synchronized (self) {
9665 - (void) distUpgrade {
9666 @synchronized (self) {
9667 if (![database_ upgrade])
9674 [database_ perform];
9675 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9678 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9681 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9685 - (void) showSettings {
9686 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9689 - (void) retainNetworkActivityIndicator {
9690 if (activity_++ == 0)
9691 [self setNetworkActivityIndicatorVisible:YES];
9694 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9698 - (void) releaseNetworkActivityIndicator {
9699 if (--activity_ == 0)
9700 [self setNetworkActivityIndicatorVisible:NO];
9703 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9708 - (void) cancelAndClear:(bool)clear {
9709 @synchronized (self) {
9721 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9722 NSString *context([alert context]);
9724 if ([context isEqualToString:@"conffile"]) {
9725 FILE *input = [database_ input];
9726 if (button == [alert cancelButtonIndex])
9727 fprintf(input, "N\n");
9728 else if (button == [alert firstOtherButtonIndex])
9729 fprintf(input, "Y\n");
9732 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9733 } else if ([context isEqualToString:@"fixhalf"]) {
9734 if (button == [alert cancelButtonIndex]) {
9735 @synchronized (self) {
9736 for (Package *broken in (id) broken_) {
9739 NSString *id = [broken id];
9740 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9741 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9742 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9743 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9749 } else if (button == [alert firstOtherButtonIndex]) {
9750 [broken_ removeAllObjects];
9754 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9755 } else if ([context isEqualToString:@"upgrade"]) {
9756 if (button == [alert firstOtherButtonIndex]) {
9757 @synchronized (self) {
9758 for (Package *essential in (id) essential_)
9759 [essential install];
9764 } else if (button == [alert firstOtherButtonIndex] + 1) {
9766 } else if (button == [alert cancelButtonIndex]) {
9770 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9774 - (void) system:(NSString *)command {
9775 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9778 system([command UTF8String]);
9784 - (void) applicationWillSuspend {
9786 [super applicationWillSuspend];
9789 - (BOOL) isSafeToSuspend {
9792 NSLog(@"isSafeToSuspend: locked_ != 0");
9797 // Use external process status API internally.
9798 // This is probably a really bad idea.
9799 // XXX: what is the point of this? does this solve anything at all?
9800 uint64_t status = 0;
9802 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9803 notify_get_state(notify_token, &status);
9804 notify_cancel(notify_token);
9809 NSLog(@"isSafeToSuspend: status != 0");
9815 NSLog(@"isSafeToSuspend: -> true");
9820 - (void) applicationSuspend:(__GSEvent *)event {
9821 if ([self isSafeToSuspend])
9822 [super applicationSuspend:event];
9825 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9826 if ([self isSafeToSuspend])
9827 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9830 - (void) _setSuspended:(BOOL)value {
9831 if ([self isSafeToSuspend])
9832 [super _setSuspended:value];
9835 - (UIProgressHUD *) addProgressHUD {
9836 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9837 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9839 [window_ setUserInteractionEnabled:NO];
9841 UIViewController *target(tabbar_);
9842 if (UIViewController *modal = [target modalViewController])
9845 [hud showInView:[target view]];
9851 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9854 [hud removeFromSuperview];
9855 [window_ setUserInteractionEnabled:YES];
9858 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9859 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9862 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9863 NSString *scheme([[url scheme] lowercaseString]);
9864 if ([[url absoluteString] length] <= [scheme length] + 3)
9866 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9867 NSArray *components([path componentsSeparatedByString:@"/"]);
9869 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9870 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9871 if (controller != nil)
9872 [controller setDelegate:self];
9876 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9879 NSString *base([components objectAtIndex:0]);
9881 CyteViewController *controller = nil;
9883 if ([base isEqualToString:@"url"]) {
9884 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9885 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9886 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9887 } else if (!external && [components count] == 1) {
9888 if ([base isEqualToString:@"manage"]) {
9889 controller = [[[ManageController alloc] init] autorelease];
9892 if ([base isEqualToString:@"storage"]) {
9893 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9896 if ([base isEqualToString:@"sources"]) {
9897 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9900 if ([base isEqualToString:@"home"]) {
9901 controller = [[[HomeController alloc] init] autorelease];
9904 if ([base isEqualToString:@"sections"]) {
9905 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9908 if ([base isEqualToString:@"search"]) {
9909 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9912 if ([base isEqualToString:@"changes"]) {
9913 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9916 if ([base isEqualToString:@"installed"]) {
9917 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9919 } else if ([components count] == 2) {
9920 NSString *argument = [components objectAtIndex:1];
9922 if ([base isEqualToString:@"package"]) {
9923 controller = [self pageForPackage:argument withReferrer:referrer];
9926 if (!external && [base isEqualToString:@"search"]) {
9927 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9930 if (!external && [base isEqualToString:@"sections"]) {
9931 if ([argument isEqualToString:@"all"])
9933 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9936 if (!external && [base isEqualToString:@"sources"]) {
9937 if ([argument isEqualToString:@"add"]) {
9938 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9939 [(SourcesController *)controller showAddSourcePrompt];
9941 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9942 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9946 if (!external && [base isEqualToString:@"launch"]) {
9947 [self launchApplicationWithIdentifier:argument suspended:NO];
9950 } else if (!external && [components count] == 3) {
9951 NSString *arg1 = [components objectAtIndex:1];
9952 NSString *arg2 = [components objectAtIndex:2];
9954 if ([base isEqualToString:@"package"]) {
9955 if ([arg2 isEqualToString:@"settings"]) {
9956 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9957 } else if ([arg2 isEqualToString:@"files"]) {
9958 if (Package *package = [database_ packageWithName:arg1]) {
9959 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9960 [(FileTable *)controller setPackage:package];
9966 [controller setDelegate:self];
9970 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9971 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9974 [tabbar_ setUnselectedViewController:page];
9979 - (void) applicationOpenURL:(NSURL *)url {
9980 [super applicationOpenURL:url];
9985 [self openCydiaURL:url forExternal:YES];
9988 - (void) applicationWillResignActive:(UIApplication *)application {
9989 // Stop refreshing if you get a phone call or lock the device.
9990 if ([tabbar_ updating])
9991 [tabbar_ cancelUpdate];
9993 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9994 [super applicationWillResignActive:application];
9997 - (void) saveState {
9998 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9999 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
10000 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
10003 [self _saveConfig];
10006 - (void) applicationWillTerminate:(UIApplication *)application {
10010 - (void) setConfigurationData:(NSString *)data {
10011 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
10013 if (!conffile_r(data)) {
10014 lprintf("E:invalid conffile\n");
10018 NSString *ofile = conffile_r[1];
10019 //NSString *nfile = conffile_r[2];
10021 UIAlertView *alert = [[[UIAlertView alloc]
10022 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
10023 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
10025 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
10027 UCLocalize("ACCEPT_NEW_COPY"),
10028 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
10032 [alert setContext:@"conffile"];
10033 [alert setNumberOfRows:2];
10037 - (void) addStashController {
10039 stash_ = [[[StashController alloc] init] autorelease];
10040 [window_ addSubview:[stash_ view]];
10043 - (void) removeStashController {
10044 [[stash_ view] removeFromSuperview];
10050 [self setIdleTimerDisabled:YES];
10052 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
10053 UpdateExternalStatus(1);
10054 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
10055 UpdateExternalStatus(0);
10057 [self removeStashController];
10059 pid_t pid(ExecFork());
10061 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
10062 perror("launchctl stop");
10069 - (void) setupViewControllers {
10070 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
10072 NSMutableArray *items([NSMutableArray arrayWithObjects:
10073 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
10074 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
10075 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
10076 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
10080 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
10081 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10083 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
10086 NSMutableArray *controllers([NSMutableArray array]);
10087 for (UITabBarItem *item in items) {
10088 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
10089 [controller setTabBarItem:item];
10090 [controllers addObject:controller];
10092 [tabbar_ setViewControllers:controllers];
10094 [tabbar_ setUpdateDelegate:self];
10097 - (void) _sendMemoryWarningNotification {
10098 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
10099 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
10101 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
10104 - (void) _sendMemoryWarningNotifications {
10106 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
10112 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
10114 [[NSURLCache sharedURLCache] removeAllCachedResponses];
10117 - (void) applicationDidFinishLaunching:(id)unused {
10118 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
10121 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
10122 [self setApplicationSupportsShakeToEdit:NO];
10124 @synchronized (HostConfig_) {
10125 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
10128 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
10129 initWithMemoryCapacity:524288
10130 diskCapacity:10485760
10131 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
10134 [CydiaWebViewController _initialize];
10136 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
10138 // this would disallow http{,s} URLs from accessing this data
10139 //[WebView registerURLSchemeAsLocal:@"cydia"];
10141 Font12_ = [UIFont systemFontOfSize:12];
10142 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
10143 Font14_ = [UIFont systemFontOfSize:14];
10144 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
10145 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
10147 essential_ = [NSMutableArray arrayWithCapacity:4];
10148 broken_ = [NSMutableArray arrayWithCapacity:4];
10150 // XXX: I really need this thing... like, seriously... I'm sorry
10151 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
10153 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
10154 [window_ orderFront:self];
10155 [window_ makeKey:self];
10156 [window_ setHidden:NO];
10159 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
10160 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
10161 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
10162 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
10163 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
10164 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
10165 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
10166 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
10167 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
10170 [self addStashController];
10171 // XXX: this would be much cleaner as a yieldToSelector:
10172 // that way the removeStashController could happen right here inline
10173 // we also could no longer require the useless stash_ field anymore
10174 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
10178 database_ = [Database sharedInstance];
10179 [database_ setDelegate:self];
10181 [window_ setUserInteractionEnabled:NO];
10182 [self setupViewControllers];
10184 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
10185 [window_ addSubview:[emulated_ view]];
10187 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10191 - (NSArray *) defaultStartPages {
10192 NSMutableArray *standard = [NSMutableArray array];
10193 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10194 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
10195 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10197 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
10199 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10200 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10202 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10206 - (void) loadData {
10208 if (Role_ == nil) {
10209 [window_ setUserInteractionEnabled:YES];
10210 [self showSettings];
10213 if ([emulated_ modalViewController] != nil)
10214 [emulated_ dismissModalViewControllerAnimated:YES];
10215 [window_ setUserInteractionEnabled:NO];
10218 [self reloadDataWithInvocation:nil];
10219 [self refreshIfPossible];
10224 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10225 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
10226 int standardIndex = 0;
10227 NSArray *standard = [self defaultStartPages];
10234 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10235 if (valid && closed != nil) {
10236 NSTimeInterval interval([closed timeIntervalSinceNow]);
10237 // XXX: Is 30 minutes the optimal time here?
10238 if (interval <= -(30*60))
10242 if (valid && [saved count] != [standard count])
10246 for (unsigned int i = 0; i < [standard count]; i++) {
10247 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10248 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10249 // but it's good enough for now.
10250 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10257 NSArray *items = nil;
10259 [tabbar_ setSelectedIndex:savedIndex];
10262 [tabbar_ setSelectedIndex:standardIndex];
10266 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10267 NSArray *stack = [items objectAtIndex:tab];
10268 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10269 NSMutableArray *current = [NSMutableArray array];
10271 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10272 NSString *addr = [stack objectAtIndex:nav];
10273 NSURL *url = [NSURL URLWithString:addr];
10274 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10276 [current addObject:page];
10279 [navigation setViewControllers:current];
10282 // (Try to) show the startup URL.
10283 if (starturl_ != nil) {
10284 [self openCydiaURL:starturl_ forExternal:NO];
10289 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10290 if (item != nil && IsWildcat_) {
10291 [sheet showFromBarButtonItem:item animated:YES];
10293 [sheet showInView:window_];
10297 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10298 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10299 [progress setTitle:task];
10300 [progress addProgressEvent:event];
10303 - (void) addProgressEventForTask:(NSArray *)data {
10304 CydiaProgressEvent *event([data objectAtIndex:0]);
10305 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10306 [self addProgressEvent:event forTask:task];
10309 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10310 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10316 id Alloc_(id self, SEL selector) {
10317 id object = alloc_(self, selector);
10318 lprintf("[%s]A-%p\n", self->isa->name, object);
10323 id Dealloc_(id self, SEL selector) {
10324 id object = dealloc_(self, selector);
10325 lprintf("[%s]D-%p\n", self->isa->name, object);
10329 Class $WebDefaultUIKitDelegate;
10331 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10332 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10333 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10334 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10337 static NSSet *MobilizedFiles_;
10339 static NSURL *MobilizeURL(NSURL *url) {
10340 NSString *path([url path]);
10341 if ([path hasPrefix:@"/var/root/"]) {
10342 NSString *file([path substringFromIndex:10]);
10343 if ([MobilizedFiles_ containsObject:file])
10344 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10350 Class $CFXPreferencesPropertyListSource;
10351 @class CFXPreferencesPropertyListSource;
10353 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10354 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10355 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10356 url = MobilizeURL(url);
10357 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10358 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10364 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10365 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10366 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10367 url = MobilizeURL(url);
10368 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10369 //NSLog(@"%@ %@", [url absoluteString], value);
10375 Class $NSURLConnection;
10377 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10378 NSMutableURLRequest *copy([request mutableCopy]);
10380 NSURL *url([copy URL]);
10382 NSString *host([url host]);
10383 NSString *scheme([[url scheme] lowercaseString]);
10385 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10387 @synchronized (HostConfig_) {
10388 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10389 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10390 [copy setHTTPShouldUsePipelining:YES];
10392 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10393 if ([control isEqualToString:@"max-age=0"])
10394 if ([CachedURLs_ containsObject:url]) {
10396 NSLog(@"~~~: %@", url);
10399 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10401 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10402 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10403 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10407 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10413 static CGSize $WAKWindow$screenSize(WAKWindow self, SEL _cmd) {
10414 CGSize size([[UIScreen mainScreen] bounds].size);
10415 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10416 if ([$WAKWindow hasLandscapeOrientation])
10417 std::swap(size.width, size.height);*/
10421 int main(int argc, char *argv[]) {
10422 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10426 UpdateExternalStatus(0);
10428 if (Class $UIDevice = objc_getClass("UIDevice")) {
10429 UIDevice *device([$UIDevice currentDevice]);
10430 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10432 IsWildcat_ = false;
10434 UIScreen *screen([UIScreen mainScreen]);
10435 if ([screen respondsToSelector:@selector(scale)])
10436 ScreenScale_ = [screen scale];
10440 UIDevice *device([UIDevice currentDevice]);
10441 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10442 Idiom_ = @"iphone";
10444 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10445 if (idiom == UIUserInterfaceIdiomPhone)
10446 Idiom_ = @"iphone";
10447 else if (idiom == UIUserInterfaceIdiomPad)
10450 NSLog(@"unknown UIUserInterfaceIdiom!");
10453 Pcre pattern("^([0-9]+\\.[0-9]+)");
10455 if (pattern([device systemVersion]))
10456 Firmware_ = pattern[1];
10457 if (pattern(Cydia_))
10458 Major_ = pattern[1];
10460 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10462 HostConfig_ = [[[NSObject alloc] init] autorelease];
10463 @synchronized (HostConfig_) {
10464 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10465 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10466 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10467 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10468 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10471 NSString *ui(@"ui/ios");
10473 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10474 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10475 UI_ = CydiaURL(ui);
10477 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10479 MobilizedFiles_ = [NSMutableSet setWithObjects:
10480 @"Library/Preferences/com.apple.Accessibility.plist",
10481 @"Library/Preferences/com.apple.preferences.sounds.plist",
10484 /* Library Hacks {{{ */
10485 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10487 $WAKWindow = objc_getClass("WAKWindow");
10488 if ($WAKWindow != NULL)
10489 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10490 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10492 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10494 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10495 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10496 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10497 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10500 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10501 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10502 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10503 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10506 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10507 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10508 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10509 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10510 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10513 $NSURLConnection = objc_getClass("NSURLConnection");
10514 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10515 if (NSURLConnection$init$ != NULL) {
10516 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10517 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10520 /* Set Locale {{{ */
10521 Locale_ = CFLocaleCopyCurrent();
10522 Languages_ = [NSLocale preferredLanguages];
10524 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10525 //NSLog(@"%@", [Languages_ description]);
10528 if (Locale_ != NULL)
10529 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10530 else if (Languages_ != nil && [Languages_ count] != 0)
10531 lang = [[Languages_ objectAtIndex:0] UTF8String];
10533 // XXX: consider just setting to C and then falling through?
10536 if (lang != NULL) {
10537 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10538 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10541 NSLog(@"Setting Language: %s", lang);
10543 if (lang != NULL) {
10544 setenv("LANG", lang, true);
10545 std::setlocale(LC_ALL, lang);
10549 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10551 /* Parse Arguments {{{ */
10552 bool substrate(false);
10558 for (int argi(1); argi != argc; ++argi)
10559 if (strcmp(argv[argi], "--") == 0) {
10561 argv[argi] = argv[0];
10567 for (int argi(1); argi != arge; ++argi)
10568 if (strcmp(args[argi], "--substrate") == 0)
10571 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10575 App_ = [[NSBundle mainBundle] bundlePath];
10581 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10582 alloc_ = alloc->method_imp;
10583 alloc->method_imp = (IMP) &Alloc_;*/
10585 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10586 dealloc_ = dealloc->method_imp;
10587 dealloc->method_imp = (IMP) &Dealloc_;*/
10589 /* System Information {{{ */
10593 size = sizeof(maxproc);
10594 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10595 perror("sysctlbyname(\"kern.maxproc\", ?)");
10596 else if (maxproc < 64) {
10598 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10599 perror("sysctlbyname(\"kern.maxproc\", #)");
10602 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10603 char *osversion = new char[size];
10604 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10605 perror("sysctlbyname(\"kern.osversion\", ?)");
10607 System_ = [NSString stringWithUTF8String:osversion];
10609 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10610 char *machine = new char[size];
10611 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10612 perror("sysctlbyname(\"hw.machine\", ?)");
10614 Machine_ = machine;
10616 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10617 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10618 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10620 UniqueID_ = [device uniqueIdentifier];
10622 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10623 Product_ = [info objectForKey:@"SafariProductVersion"];
10624 Safari_ = [info objectForKey:@"CFBundleVersion"];
10627 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10629 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10630 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10631 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10632 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10633 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10634 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10636 UserAgent_ = agent;
10638 /* Load Database {{{ */
10640 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10642 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10644 if (Metadata_ == NULL)
10645 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10647 Settings_ = [Metadata_ objectForKey:@"Settings"];
10649 Packages_ = [Metadata_ objectForKey:@"Packages"];
10651 Values_ = [Metadata_ objectForKey:@"Values"];
10652 Sections_ = [Metadata_ objectForKey:@"Sections"];
10653 Sources_ = [Metadata_ objectForKey:@"Sources"];
10655 Token_ = [Metadata_ objectForKey:@"Token"];
10657 Version_ = [Metadata_ objectForKey:@"Version"];
10660 if (Settings_ != nil)
10661 Role_ = [Settings_ objectForKey:@"Role"];
10663 if (Values_ == nil) {
10664 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10665 [Metadata_ setObject:Values_ forKey:@"Values"];
10668 if (Sections_ == nil) {
10669 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10670 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10673 if (Sources_ == nil) {
10674 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10675 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10678 if (Version_ == nil) {
10679 Version_ = [NSNumber numberWithUnsignedInt:0];
10680 [Metadata_ setObject:Version_ forKey:@"Version"];
10683 if ([Version_ unsignedIntValue] == 0) {
10684 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10685 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10686 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10687 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10689 Version_ = [NSNumber numberWithUnsignedInt:1];
10690 [Metadata_ setObject:Version_ forKey:@"Version"];
10692 [Metadata_ removeObjectForKey:@"LastUpdate"];
10698 CydiaWriteSources();
10701 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10704 if (Packages_ != nil) {
10706 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10710 [Metadata_ removeObjectForKey:@"Packages"];
10716 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10718 #define MobileSubstrate_(name) \
10719 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10720 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10721 if (handle == NULL) \
10722 NSLog(@"%s", dlerror()); \
10725 MobileSubstrate_(Activator)
10726 MobileSubstrate_(libstatusbar)
10727 MobileSubstrate_(SimulatedKeyEvents)
10728 MobileSubstrate_(WinterBoard)
10730 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10731 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10733 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10735 if (access("/User", F_OK) != 0 || version != 5) {
10737 system("/usr/libexec/cydia/firmware.sh");
10741 _assert([[NSFileManager defaultManager]
10742 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10743 withIntermediateDirectories:YES
10748 if (access("/tmp/cydia.chk", F_OK) == 0) {
10749 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10750 _assert(errno == ENOENT);
10751 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10752 _assert(errno == ENOENT);
10755 /* APT Initialization {{{ */
10756 _assert(pkgInitConfig(*_config));
10757 _assert(pkgInitSystem(*_config, _system));
10760 _config->Set("APT::Acquire::Translation", lang);
10762 // XXX: this timeout might be important :(
10763 //_config->Set("Acquire::http::Timeout", 15);
10765 _config->Set("Acquire::http::MaxParallel", 3);
10767 /* Color Choices {{{ */
10768 space_ = CGColorSpaceCreateDeviceRGB();
10770 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10771 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10772 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10773 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10774 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10775 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10776 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10777 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10778 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10780 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10781 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10783 /* UIKit Configuration {{{ */
10784 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10785 if ($GSFontSetUseLegacyFontMetrics != NULL)
10786 $GSFontSetUseLegacyFontMetrics(YES);
10788 // XXX: I have a feeling this was important
10789 //UIKeyboardDisableAutomaticAppearance();
10792 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, "GSSystemHasCapability"));
10793 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10795 ShowPromoted_ = fast;
10796 PulseInterval_ = fast ? 50000 : 500000;
10798 Colon_ = UCLocalize("COLON_DELIMITED");
10799 Elision_ = UCLocalize("ELISION");
10800 Error_ = UCLocalize("ERROR");
10801 Warning_ = UCLocalize("WARNING");
10804 AprilFools_ = true;
10806 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10807 AprilFools_ = date.month == 4 && date.day == 1;
10811 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10813 CGColorSpaceRelease(space_);
10814 CFRelease(Locale_);