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/PerlCompatibleRegEx.hpp"
130 #include "CyteKit/TableViewCell.h"
131 #include "CyteKit/WebScriptObject-Cyte.h"
132 #include "CyteKit/WebViewController.h"
133 #include "CyteKit/stringWithUTF8Bytes.h"
135 #include "Cydia/MIMEAddress.h"
136 #include "Cydia/LoadingViewController.h"
137 #include "Cydia/ProgressEvent.h"
139 #include "SDURLCache/SDURLCache.h"
146 #define _timestamp ({ \
148 gettimeofday(&tv, NULL); \
149 tv.tv_sec * 1000000 + tv.tv_usec; \
152 typedef std::vector<class ProfileTime *> TimeList;
162 ProfileTime(const char *name) :
166 times_.push_back(this);
169 void AddTime(uint64_t time) {
176 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
188 ProfileTimer(ProfileTime &time) :
195 time_.AddTime(_timestamp - start_);
200 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
202 std::cerr << "========" << std::endl;
205 #define _profile(name) { \
206 static ProfileTime name(#name); \
207 ProfileTimer _ ## name(name);
212 extern NSString *Cydia_;
214 #define lprintf(args...) fprintf(stderr, args)
217 #define TraceLogging (1 && !ForRelease)
218 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
219 #define ProfileTimes (0 && !ForRelease)
220 #define ForSaurik (0 && !ForRelease)
221 #define LogBrowser (0 && !ForRelease)
222 #define TrackResize (0 && !ForRelease)
223 #define ManualRefresh (1 && !ForRelease)
224 #define ShowInternals (0 && !ForRelease)
225 #define AlwaysReload (0 && !ForRelease)
226 #define TryIndexedCollation (0 && !ForRelease)
230 #define _trace(args...)
235 #define _profile(name) {
238 #define PrintTimes() do {} while (false)
241 // Hash Functions/Structures {{{
242 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
250 static NSString *Colon_;
252 static NSString *Error_;
253 static NSString *Warning_;
255 static bool AprilFools_;
257 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
259 static _finline NSString *CydiaURL(NSString *path) {
261 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
262 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
263 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
264 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
265 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
267 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
270 static void ReapZombie(pid_t pid) {
273 if (waitpid(pid, &status, 0) == -1)
279 static _finline void UpdateExternalStatus(uint64_t newStatus) {
281 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
282 notify_set_state(notify_token, newStatus);
283 notify_cancel(notify_token);
285 notify_post("com.saurik.Cydia.status");
288 static CGFloat CYStatusBarHeight() {
289 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
290 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
293 /* NSForcedOrderingSearch doesn't work on the iPhone */
294 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
295 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
296 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
298 /* Insertion Sort {{{ */
300 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
301 const char *ptr = (const char *)list;
303 CFIndex half = count / 2;
304 const char *probe = ptr + elementSize * half;
305 CFComparisonResult cr = comparator(element, probe, context);
306 if (0 == cr) return (probe - (const char *)list) / elementSize;
307 ptr = (cr < 0) ? ptr : probe + elementSize;
308 count = (cr < 0) ? half : (half + (count & 1) - 1);
310 return (ptr - (const char *)list) / elementSize;
313 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
314 const char *ptr = (const char *)list;
316 CFIndex half = count / 2;
317 const char *probe = ptr + elementSize * half;
318 CFComparisonResult cr = comparator(element, probe, context);
319 if (0 == cr) return (probe - (const char *)list) / elementSize;
320 ptr = (cr < 0) ? ptr : probe + elementSize;
321 count = (cr < 0) ? half : (half + (count & 1) - 1);
323 return (ptr - (const char *)list) / elementSize;
326 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
327 if (range.length == 0)
329 const void **values(new const void *[range.length]);
330 CFArrayGetValues(array, range, values);
332 #if HistogramInsertionSort > 0
333 uint32_t total(0), *offsets(new uint32_t[range.length]);
336 for (CFIndex index(1); index != range.length; ++index) {
337 const void *value(values[index]);
338 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
339 CFIndex correct(index);
340 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
341 #if HistogramInsertionSort > 1
342 NSLog(@"%@ < %@", value, values[correct - 1]);
347 if (correct != index) {
348 size_t offset(index - correct);
349 #if HistogramInsertionSort
353 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
355 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
356 values[correct] = value;
360 CFArrayReplaceValues(array, range, values, range.length);
363 #if HistogramInsertionSort > 0
364 for (CFIndex index(0); index != range.length; ++index)
365 if (offsets[index] != 0)
366 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
367 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
374 /* Apple Bug Fixes {{{ */
375 @implementation UIWebDocumentView (Cydia)
377 - (void) _setScrollerOffset:(CGPoint)offset {
378 UIScroller *scroller([self _scroller]);
380 CGSize size([scroller contentSize]);
381 CGSize bounds([scroller bounds].size);
384 max.x = size.width - bounds.width;
385 max.y = size.height - bounds.height;
393 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
394 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
396 [scroller setOffset:offset];
402 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
403 size_t length([self length] - state->state);
406 else if (length > count)
408 for (size_t i(0); i != length; ++i)
409 objects[i] = [self item:state->state++];
410 state->itemsPtr = objects;
411 state->mutationsPtr = (unsigned long *) self;
415 /* Cydia NSString Additions {{{ */
416 @interface NSString (Cydia)
417 - (NSComparisonResult) compareByPath:(NSString *)other;
418 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
421 @implementation NSString (Cydia)
423 - (NSComparisonResult) compareByPath:(NSString *)other {
424 NSString *prefix = [self commonPrefixWithString:other options:0];
425 size_t length = [prefix length];
427 NSRange lrange = NSMakeRange(length, [self length] - length);
428 NSRange rrange = NSMakeRange(length, [other length] - length);
430 lrange = [self rangeOfString:@"/" options:0 range:lrange];
431 rrange = [other rangeOfString:@"/" options:0 range:rrange];
433 NSComparisonResult value;
435 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
436 value = NSOrderedSame;
437 else if (lrange.location == NSNotFound)
438 value = NSOrderedAscending;
439 else if (rrange.location == NSNotFound)
440 value = NSOrderedDescending;
442 value = NSOrderedSame;
444 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
445 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
446 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
447 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
449 NSComparisonResult result = [lpath compare:rpath];
450 return result == NSOrderedSame ? value : result;
453 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
454 return [(id)CFURLCreateStringByAddingPercentEscapes(
459 kCFStringEncodingUTF8
466 /* C++ NSString Wrapper Cache {{{ */
467 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
468 return size == 0 ? NULL :
469 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
470 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
473 static _finline CFStringRef CYStringCreate(const char *data) {
474 return CYStringCreate(data, strlen(data));
483 _finline void clear_() {
484 if (cache_ != NULL) {
491 _finline bool empty() const {
495 _finline size_t size() const {
499 _finline char *data() const {
503 _finline void clear() {
508 _finline CYString() :
515 _finline ~CYString() {
519 void operator =(const CYString &rhs) {
523 if (rhs.cache_ == nil)
526 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
529 void copy(apr_pool_t *pool) {
530 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
531 memcpy(temp, data_, size_);
536 void set(apr_pool_t *pool, const char *data, size_t size) {
542 data_ = const_cast<char *>(data);
550 _finline void set(apr_pool_t *pool, const char *data) {
551 set(pool, data, data == NULL ? 0 : strlen(data));
554 _finline void set(apr_pool_t *pool, const std::string &rhs) {
555 set(pool, rhs.data(), rhs.size());
558 bool operator ==(const CYString &rhs) const {
559 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
562 _finline operator CFStringRef() {
564 cache_ = CYStringCreate(data_, size_);
568 _finline operator id() {
569 return (NSString *) static_cast<CFStringRef>(*this);
572 _finline operator const char *() {
573 return reinterpret_cast<const char *>(data_);
577 /* C++ NSString Algorithm Adapters {{{ */
579 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
582 struct NSStringMapHash :
583 std::unary_function<NSString *, size_t>
585 _finline size_t operator ()(NSString *value) const {
586 return CFStringHashNSString((CFStringRef) value);
590 struct NSStringMapLess :
591 std::binary_function<NSString *, NSString *, bool>
593 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
594 return [lhs compare:rhs] == NSOrderedAscending;
598 struct NSStringMapEqual :
599 std::binary_function<NSString *, NSString *, bool>
601 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
602 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
603 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
604 //[lhs isEqualToString:rhs];
609 /* CoreGraphics Primitives {{{ */
614 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
615 CGFloat color[] = {red, green, blue, alpha};
616 return CGColorCreate(space, color);
625 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
626 color_(Create_(space, red, green, blue, alpha))
628 Set(space, red, green, blue, alpha);
633 CGColorRelease(color_);
640 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
642 color_ = Create_(space, red, green, blue, alpha);
645 operator CGColorRef() {
651 /* Random Global Variables {{{ */
652 static const int PulseInterval_ = 50000;
654 static const NSString *UI_;
657 static bool RestartSubstrate_;
658 static NSArray *Finishes_;
660 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
661 #define NotifyConfig_ "/etc/notify.conf"
663 static bool Queuing_;
665 static CYColor Blue_;
666 static CYColor Blueish_;
667 static CYColor Black_;
669 static CYColor White_;
670 static CYColor Gray_;
671 static CYColor Green_;
672 static CYColor Purple_;
673 static CYColor Purplish_;
675 static UIColor *InstallingColor_;
676 static UIColor *RemovingColor_;
678 static NSString *App_;
680 static BOOL Advanced_;
681 static BOOL Ignored_;
683 static _H<UIFont> Font12_;
684 static _H<UIFont> Font12Bold_;
685 static _H<UIFont> Font14_;
686 static _H<UIFont> Font18Bold_;
687 static _H<UIFont> Font22Bold_;
689 static const char *Machine_ = NULL;
690 static _H<NSString> System_;
691 static NSString *SerialNumber_ = nil;
692 static NSString *ChipID_ = nil;
693 static NSString *BBSNum_ = nil;
694 static _H<NSString> Token_;
695 static NSString *UniqueID_ = nil;
696 static _H<NSString> UserAgent_;
697 static _H<NSString> Product_;
698 static _H<NSString> Safari_;
700 static CFLocaleRef Locale_;
701 static NSArray *Languages_;
702 static CGColorSpaceRef space_;
704 static NSDictionary *SectionMap_;
705 static NSMutableDictionary *Metadata_;
706 static _transient NSMutableDictionary *Settings_;
707 static _transient NSString *Role_;
708 static _transient NSMutableDictionary *Packages_;
709 static _transient NSMutableDictionary *Values_;
710 static _transient NSMutableDictionary *Sections_;
711 _H<NSMutableDictionary> Sources_;
712 static _transient NSNumber *Version_;
717 static CGFloat ScreenScale_;
718 static NSString *Idiom_;
719 static _H<NSString> Firmware_;
720 static NSString *Major_;
722 static _H<NSMutableDictionary> SessionData_;
723 static _H<NSObject> HostConfig_;
724 static _H<NSMutableSet> BridgedHosts_;
725 static _H<NSMutableSet> TokenHosts_;
726 static _H<NSMutableSet> InsecureHosts_;
727 static _H<NSMutableSet> PipelinedHosts_;
728 static _H<NSMutableSet> CachedURLs_;
730 static NSString *kCydiaProgressEventTypeError = @"Error";
731 static NSString *kCydiaProgressEventTypeInformation = @"Information";
732 static NSString *kCydiaProgressEventTypeStatus = @"Status";
733 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
736 /* Display Helpers {{{ */
737 inline float Interpolate(float begin, float end, float fraction) {
738 return (end - begin) * fraction + begin;
741 static _finline const char *StripVersion_(const char *version) {
742 const char *colon(strchr(version, ':'));
743 return colon == NULL ? version : colon + 1;
746 NSString *LocalizeSection(NSString *section) {
747 static Pcre title_r("^(.*?) \\((.*)\\)$");
748 if (title_r(section)) {
749 NSString *parent(title_r[1]);
750 NSString *child(title_r[2]);
752 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
753 LocalizeSection(parent),
754 LocalizeSection(child)
758 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
761 NSString *Simplify(NSString *title) {
762 const char *data = [title UTF8String];
763 size_t size = [title length];
765 static Pcre square_r("^\\[(.*)\\]$");
766 if (square_r(data, size))
767 return Simplify(square_r[1]);
769 static Pcre paren_r("^\\((.*)\\)$");
770 if (paren_r(data, size))
771 return Simplify(paren_r[1]);
773 static Pcre title_r("^(.*?) \\((.*)\\)$");
774 if (title_r(data, size))
775 return Simplify(title_r[1]);
781 NSString *GetLastUpdate() {
782 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
785 return UCLocalize("NEVER_OR_UNKNOWN");
787 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
788 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
790 CFRelease(formatter);
792 return [(NSString *) formatted autorelease];
795 bool isSectionVisible(NSString *section) {
796 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
797 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
798 return hidden == nil || ![hidden boolValue];
801 static NSObject *CYIOGetValue(const char *path, NSString *property) {
802 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
803 if (entry == MACH_PORT_NULL)
806 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
807 IOObjectRelease(entry);
811 return [(id) value autorelease];
814 static NSString *CYHex(NSData *data, bool reverse = false) {
818 size_t length([data length]);
819 uint8_t bytes[length];
820 [data getBytes:bytes];
822 char string[length * 2 + 1];
823 for (size_t i(0); i != length; ++i)
824 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
826 return [NSString stringWithUTF8String:string];
831 /* Delegate Prototypes {{{ */
834 @class CydiaProgressEvent;
836 @protocol DatabaseDelegate
837 - (void) repairWithSelector:(SEL)selector;
838 - (void) setConfigurationData:(NSString *)data;
839 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
842 @class CYPackageController;
844 @protocol CydiaDelegate
845 - (void) returnToCydia;
847 - (void) retainNetworkActivityIndicator;
848 - (void) releaseNetworkActivityIndicator;
849 - (void) clearPackage:(Package *)package;
850 - (void) installPackage:(Package *)package;
851 - (void) installPackages:(NSArray *)packages;
852 - (void) removePackage:(Package *)package;
853 - (void) beginUpdate;
855 - (void) distUpgrade;
859 - (void) addSource:(NSDictionary *)source;
860 - (void) addTrivialSource:(NSString *)href;
861 - (void) showSettings;
862 - (UIProgressHUD *) addProgressHUD;
863 - (void) removeProgressHUD:(UIProgressHUD *)hud;
864 - (CyteViewController *) pageForPackage:(NSString *)name;
865 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
866 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
870 /* Status Delegation {{{ */
872 public pkgAcquireStatus
875 _transient NSObject<ProgressDelegate> *delegate_;
885 void setDelegate(NSObject<ProgressDelegate> *delegate) {
886 delegate_ = delegate;
889 NSObject<ProgressDelegate> *getDelegate() const {
893 virtual bool MediaChange(std::string media, std::string drive) {
897 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
901 virtual void Fetch(pkgAcquire::ItemDesc &item) {
902 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
903 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
904 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
907 virtual void Done(pkgAcquire::ItemDesc &item) {
908 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
909 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
910 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
913 virtual void Fail(pkgAcquire::ItemDesc &item) {
915 item.Owner->Status == pkgAcquire::Item::StatIdle ||
916 item.Owner->Status == pkgAcquire::Item::StatDone
920 std::string &error(item.Owner->ErrorText);
924 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
925 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
928 virtual bool Pulse(pkgAcquire *Owner) {
929 bool value = pkgAcquireStatus::Pulse(Owner);
932 double(CurrentBytes + CurrentItems) /
933 double(TotalBytes + TotalItems)
936 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
937 [NSNumber numberWithDouble:percent], @"Percent",
939 [NSNumber numberWithDouble:CurrentBytes], @"Current",
940 [NSNumber numberWithDouble:TotalBytes], @"Total",
941 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
942 nil] waitUntilDone:YES];
944 if (value && ![delegate_ isProgressCancelled])
952 _finline bool WasCancelled() const {
956 virtual void Start() {
957 pkgAcquireStatus::Start();
958 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
961 virtual void Stop() {
962 pkgAcquireStatus::Stop();
963 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
964 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
968 /* Database Interface {{{ */
969 typedef std::map< unsigned long, _H<Source> > SourceMap;
971 @interface Database : NSObject {
978 pkgDepCache::Policy *policy_;
979 pkgRecords *records_;
980 pkgProblemResolver *resolver_;
981 pkgAcquire *fetcher_;
983 SPtr<pkgPackageManager> manager_;
984 pkgSourceList *list_;
986 SourceMap sourceMap_;
987 _H<NSMutableArray> sourceList_;
989 CFMutableArrayRef packages_;
991 _transient NSObject<DatabaseDelegate> *delegate_;
992 _transient NSObject<ProgressDelegate> *progress_;
1000 std::map<const char *, _H<NSString> > sections_;
1003 + (Database *) sharedInstance;
1006 - (void) _readCydia:(NSNumber *)fd;
1007 - (void) _readStatus:(NSNumber *)fd;
1008 - (void) _readOutput:(NSNumber *)fd;
1012 - (Package *) packageWithName:(NSString *)name;
1014 - (pkgCacheFile &) cache;
1015 - (pkgDepCache::Policy *) policy;
1016 - (pkgRecords *) records;
1017 - (pkgProblemResolver *) resolver;
1018 - (pkgAcquire &) fetcher;
1019 - (pkgSourceList &) list;
1020 - (NSArray *) packages;
1021 - (NSArray *) sources;
1022 - (Source *) sourceWithKey:(NSString *)key;
1023 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1031 - (void) updateWithStatus:(Status &)status;
1033 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1035 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1036 - (NSObject<ProgressDelegate> *) progressDelegate;
1038 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1040 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1044 /* ProgressEvent Implementation {{{ */
1045 @implementation CydiaProgressEvent
1047 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1048 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1051 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1052 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1053 [event setPackage:package];
1057 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1058 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1060 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1061 NSArray *fields([description componentsSeparatedByString:@" "]);
1062 [event setItem:fields];
1064 if ([fields count] > 3) {
1065 [event setPackage:[fields objectAtIndex:2]];
1066 [event setVersion:[fields objectAtIndex:3]];
1069 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1074 + (NSArray *) _attributeKeys {
1075 return [NSArray arrayWithObjects:
1085 - (NSArray *) attributeKeys {
1086 return [[self class] _attributeKeys];
1089 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1090 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1093 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1094 if ((self = [super init]) != nil) {
1100 - (NSString *) message {
1104 - (NSString *) type {
1108 - (NSArray *) item {
1109 return (id) item_ ?: [NSNull null];
1112 - (void) setItem:(NSArray *)item {
1116 - (NSString *) package {
1117 return (id) package_ ?: [NSNull null];
1120 - (void) setPackage:(NSString *)package {
1124 - (NSString *) url {
1125 return (id) url_ ?: [NSNull null];
1128 - (void) setURL:(NSString *)url {
1132 - (void) setVersion:(NSString *)version {
1136 - (NSString *) version {
1137 return (id) version_ ?: [NSNull null];
1140 - (NSString *) compound:(NSString *)value {
1142 NSString *mode(nil); {
1143 NSString *type([self type]);
1144 if ([type isEqualToString:kCydiaProgressEventTypeError])
1145 mode = UCLocalize("ERROR");
1146 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1147 mode = UCLocalize("WARNING");
1151 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1157 - (NSString *) compoundMessage {
1158 return [self compound:[self message]];
1161 - (NSString *) compoundTitle {
1164 if (package_ == nil)
1166 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1167 title = [package name];
1171 return [self compound:title];
1177 // Cytore Definitions {{{
1178 struct PackageValue :
1181 Cytore::Offset<PackageValue> next_;
1183 uint32_t index_ : 23;
1184 uint32_t subscribed_ : 1;
1201 Cytore::Offset<PackageValue> packages_[1 << 16];
1204 static Cytore::File<MetaValue> MetaFile_;
1206 // Cytore Helper Functions {{{
1207 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1208 SplitHash nhash = { hashlittle(name, length) };
1210 PackageValue *metadata;
1212 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1213 offset: if (offset->IsNull()) {
1214 *offset = MetaFile_.New<PackageValue>(length + 1);
1215 metadata = &MetaFile_.Get(*offset);
1217 if (metadata == NULL) {
1221 metadata = new PackageValue();
1222 memset(metadata, 0, sizeof(*metadata));
1225 memcpy(metadata->name_, name, length + 1);
1226 metadata->nhash_ = nhash.u16[1];
1228 metadata = &MetaFile_.Get(*offset);
1230 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1231 offset = &metadata->next_;
1239 static void PackageImport(const void *key, const void *value, void *context) {
1240 bool &fail(*reinterpret_cast<bool *>(context));
1243 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1244 NSLog(@"failed to import package %@", key);
1248 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1249 NSDictionary *package((NSDictionary *) value);
1251 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1252 if ([subscribed boolValue] && !metadata->subscribed_)
1253 metadata->subscribed_ = true;
1255 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1256 time_t time([date timeIntervalSince1970]);
1257 if (metadata->first_ > time || metadata->first_ == 0)
1258 metadata->first_ = time;
1261 NSDate *date([package objectForKey:@"LastSeen"]);
1262 NSString *version([package objectForKey:@"LastVersion"]);
1264 if (date != nil && version != nil) {
1265 time_t time([date timeIntervalSince1970]);
1266 if (metadata->last_ < time || metadata->last_ == 0)
1267 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1268 size_t length(strlen(buffer));
1269 uint16_t vhash(hashlittle(buffer, length));
1271 size_t capped(std::min<size_t>(8, length));
1272 char *latest(buffer + length - capped);
1274 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1275 metadata->vhash_ = vhash;
1277 metadata->last_ = time;
1283 /* Source Class {{{ */
1284 @interface Source : NSObject {
1286 Database *database_;
1289 CYString depiction_;
1290 CYString description_;
1296 CYString distribution_;
1302 _H<NSString> authority_;
1304 CYString defaultIcon_;
1306 _H<NSDictionary> record_;
1310 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1312 - (NSComparisonResult) compareByName:(Source *)source;
1314 - (NSString *) depictionForPackage:(NSString *)package;
1315 - (NSString *) supportForPackage:(NSString *)package;
1317 - (NSDictionary *) record;
1320 - (NSString *) rooturi;
1321 - (NSString *) distribution;
1322 - (NSString *) type;
1325 - (NSString *) host;
1327 - (NSString *) name;
1328 - (NSString *) shortDescription;
1329 - (NSString *) label;
1330 - (NSString *) origin;
1331 - (NSString *) version;
1333 - (NSString *) defaultIcon;
1334 - (NSURL *) iconURL;
1338 @implementation Source
1342 distribution_.clear();
1347 description_.clear();
1353 defaultIcon_.clear();
1360 + (NSString *) webScriptNameForSelector:(SEL)selector {
1362 else if (selector == @selector(addSection:))
1363 return @"addSection";
1364 else if (selector == @selector(getField:))
1366 else if (selector == @selector(removeSection:))
1367 return @"removeSection";
1368 else if (selector == @selector(remove))
1374 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1375 return [self webScriptNameForSelector:selector] == nil;
1378 + (NSArray *) _attributeKeys {
1379 return [NSArray arrayWithObjects:
1390 @"shortDescription",
1397 - (NSArray *) attributeKeys {
1398 return [[self class] _attributeKeys];
1401 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1402 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1405 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1408 trusted_ = index->IsTrusted();
1410 uri_.set(pool, index->GetURI());
1411 distribution_.set(pool, index->GetDist());
1412 type_.set(pool, index->GetType());
1414 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1415 if (dindex != NULL) {
1416 base_.set(pool, dindex->MetaIndexURI(""));
1419 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1422 pkgTagFile tags(&fd);
1424 pkgTagSection section;
1431 {"default-icon", &defaultIcon_},
1432 {"depiction", &depiction_},
1433 {"description", &description_},
1435 {"origin", &origin_},
1436 {"support", &support_},
1437 {"version", &version_},
1440 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1441 const char *start, *end;
1443 if (section.Find(names[i].name_, start, end)) {
1444 CYString &value(*names[i].value_);
1445 value.set(pool, start, end - start);
1451 record_ = [Sources_ objectForKey:[self key]];
1453 NSURL *url([NSURL URLWithString:uri_]);
1457 host_ = [host_ lowercaseString];
1462 authority_ = [url path];
1465 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1466 if ((self = [super init]) != nil) {
1467 era_ = [database era];
1468 database_ = database;
1471 [self setMetaIndex:index inPool:pool];
1475 - (NSString *) getField:(NSString *)name {
1476 @synchronized (database_) {
1477 if ([database_ era] != era_ || index_ == NULL)
1480 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1485 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1490 pkgTagFile tags(&fd);
1492 pkgTagSection section;
1495 const char *start, *end;
1496 if (!section.Find([name UTF8String], start, end))
1497 return (NSString *) [NSNull null];
1499 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1502 - (NSComparisonResult) compareByName:(Source *)source {
1503 NSString *lhs = [self name];
1504 NSString *rhs = [source name];
1506 if ([lhs length] != 0 && [rhs length] != 0) {
1507 unichar lhc = [lhs characterAtIndex:0];
1508 unichar rhc = [rhs characterAtIndex:0];
1510 if (isalpha(lhc) && !isalpha(rhc))
1511 return NSOrderedAscending;
1512 else if (!isalpha(lhc) && isalpha(rhc))
1513 return NSOrderedDescending;
1516 return [lhs compare:rhs options:LaxCompareOptions_];
1519 - (NSString *) depictionForPackage:(NSString *)package {
1520 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1523 - (NSString *) supportForPackage:(NSString *)package {
1524 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1527 - (NSArray *) sections {
1528 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1531 - (void) _addSection:(NSString *)section {
1534 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1535 if (![sections containsObject:section]) {
1536 [sections addObject:section];
1540 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1545 - (bool) addSection:(NSString *)section {
1549 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1553 - (void) _removeSection:(NSString *)section {
1557 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1558 if ([sections containsObject:section]) {
1559 [sections removeObject:section];
1564 - (bool) removeSection:(NSString *)section {
1568 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1573 [Sources_ removeObjectForKey:[self key]];
1578 bool value(record_ != nil);
1579 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1583 - (NSDictionary *) record {
1591 - (NSString *) rooturi {
1595 - (NSString *) distribution {
1596 return distribution_;
1599 - (NSString *) type {
1603 - (NSString *) baseuri {
1604 return base_.empty() ? nil : (id) base_;
1607 - (NSString *) iconuri {
1608 if (NSString *base = [self baseuri])
1609 return [base stringByAppendingString:@"CydiaIcon.png"];
1614 - (NSURL *) iconURL {
1615 if (NSString *uri = [self iconuri])
1616 return [NSURL URLWithString:uri];
1620 - (NSString *) key {
1621 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1624 - (NSString *) host {
1628 - (NSString *) name {
1629 return origin_.empty() ? (id) authority_ : origin_;
1632 - (NSString *) shortDescription {
1633 return description_;
1636 - (NSString *) label {
1637 return label_.empty() ? (id) authority_ : label_;
1640 - (NSString *) origin {
1644 - (NSString *) version {
1648 - (NSString *) defaultIcon {
1649 return defaultIcon_;
1654 /* CydiaOperation Class {{{ */
1655 @interface CydiaOperation : NSObject {
1656 _H<NSString> operator_;
1657 _H<NSString> value_;
1660 - (NSString *) operator;
1661 - (NSString *) value;
1665 @implementation CydiaOperation
1667 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1668 if ((self = [super init]) != nil) {
1669 operator_ = [NSString stringWithUTF8String:_operator];
1670 value_ = [NSString stringWithUTF8String:value];
1674 + (NSArray *) _attributeKeys {
1675 return [NSArray arrayWithObjects:
1681 - (NSArray *) attributeKeys {
1682 return [[self class] _attributeKeys];
1685 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1686 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1689 - (NSString *) operator {
1693 - (NSString *) value {
1699 /* CydiaClause Class {{{ */
1700 @interface CydiaClause : NSObject {
1701 _H<NSString> package_;
1702 _H<CydiaOperation> version_;
1705 - (NSString *) package;
1706 - (CydiaOperation *) version;
1710 @implementation CydiaClause
1712 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1713 if ((self = [super init]) != nil) {
1714 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1716 if (const char *version = dep.TargetVer())
1717 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1719 version_ = (id) [NSNull null];
1723 + (NSArray *) _attributeKeys {
1724 return [NSArray arrayWithObjects:
1730 - (NSArray *) attributeKeys {
1731 return [[self class] _attributeKeys];
1734 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1735 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1738 - (NSString *) package {
1742 - (CydiaOperation *) version {
1748 /* CydiaRelation Class {{{ */
1749 @interface CydiaRelation : NSObject {
1750 _H<NSString> relationship_;
1751 _H<NSMutableArray> clauses_;
1754 - (NSString *) relationship;
1755 - (NSArray *) clauses;
1759 @implementation CydiaRelation
1761 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1762 if ((self = [super init]) != nil) {
1763 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1764 clauses_ = [NSMutableArray arrayWithCapacity:8];
1766 pkgCache::DepIterator start;
1767 pkgCache::DepIterator end;
1768 dep.GlobOr(start, end); // ++dep
1771 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1773 // yes, seriously. (wtf?)
1781 + (NSArray *) _attributeKeys {
1782 return [NSArray arrayWithObjects:
1788 - (NSArray *) attributeKeys {
1789 return [[self class] _attributeKeys];
1792 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1793 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1796 - (NSString *) relationship {
1797 return relationship_;
1800 - (NSArray *) clauses {
1804 - (void) addClause:(CydiaClause *)clause {
1805 [clauses_ addObject:clause];
1810 /* Package Class {{{ */
1811 struct ParsedPackage {
1815 CYString architecture_;
1818 CYString depiction_;
1828 @interface Package : NSObject {
1831 uint32_t essential_ : 1;
1832 uint32_t obsolete_ : 1;
1833 uint32_t ignored_ : 1;
1834 uint32_t pooled_ : 1;
1840 _transient Database *database_;
1842 pkgCache::VerIterator version_;
1843 pkgCache::PkgIterator iterator_;
1844 pkgCache::VerFileIterator file_;
1850 CYString installed_;
1852 const char *section_;
1853 _transient NSString *section$_;
1857 PackageValue *metadata_;
1858 ParsedPackage *parsed_;
1860 _H<NSMutableArray> tags_;
1863 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1864 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1866 - (pkgCache::PkgIterator) iterator;
1869 - (NSString *) section;
1870 - (NSString *) simpleSection;
1872 - (NSString *) longSection;
1873 - (NSString *) shortSection;
1877 - (MIMEAddress *) maintainer;
1879 - (NSString *) longDescription;
1880 - (NSString *) shortDescription;
1883 - (PackageValue *) metadata;
1886 - (bool) subscribed;
1887 - (bool) setSubscribed:(bool)subscribed;
1891 - (NSString *) latest;
1892 - (NSString *) installed;
1893 - (BOOL) uninstalled;
1896 - (BOOL) upgradableAndEssential:(BOOL)essential;
1899 - (BOOL) unfiltered;
1903 - (BOOL) halfConfigured;
1904 - (BOOL) halfInstalled;
1906 - (NSString *) mode;
1909 - (NSString *) name;
1911 - (NSString *) homepage;
1912 - (NSString *) depiction;
1913 - (MIMEAddress *) author;
1915 - (NSString *) support;
1917 - (NSArray *) files;
1918 - (NSArray *) warnings;
1919 - (NSArray *) applications;
1921 - (Source *) source;
1924 - (BOOL) matches:(NSArray *)query;
1926 - (bool) hasSupportingRole;
1927 - (BOOL) hasTag:(NSString *)tag;
1928 - (NSString *) primaryPurpose;
1929 - (NSArray *) purposes;
1930 - (bool) isCommercial;
1932 - (void) setIndex:(size_t)index;
1934 - (CYString &) cyname;
1936 - (uint32_t) compareBySection:(NSArray *)sections;
1941 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1942 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1943 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1944 - (bool) isVisibleInSection:(NSString *)section;
1945 - (bool) isVisibleInSource:(Source *)source;
1949 uint32_t PackageChangesRadix(Package *self, void *) {
1954 uint32_t timestamp : 30;
1955 uint32_t ignored : 1;
1956 uint32_t upgradable : 1;
1960 bool upgradable([self upgradableAndEssential:YES]);
1961 value.bits.upgradable = upgradable ? 1 : 0;
1964 value.bits.timestamp = 0;
1965 value.bits.ignored = [self ignored] ? 0 : 1;
1966 value.bits.upgradable = 1;
1968 value.bits.timestamp = [self seen] >> 2;
1969 value.bits.ignored = 0;
1970 value.bits.upgradable = 0;
1973 return _not(uint32_t) - value.key;
1976 uint32_t PackagePrefixRadix(Package *self, void *context) {
1977 size_t offset(reinterpret_cast<size_t>(context));
1978 CYString &name([self cyname]);
1980 size_t size(name.size());
1983 char *text(name.data());
1986 if (!isdigit(text[0]))
1990 while (size != digits && isdigit(text[digits]))
1998 if (offset == 0 && zeros != 0) {
1999 memset(data, '0', zeros);
2000 memcpy(data + zeros, text, 4 - zeros);
2002 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2003 if (size <= offset - zeros)
2006 text += offset - zeros;
2007 size -= offset - zeros;
2010 memcpy(data, text, 4);
2012 memcpy(data, text, size);
2013 memset(data + size, 0, 4 - size);
2016 for (size_t i(0); i != 4; ++i)
2017 if (isalpha(data[i]))
2025 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2027 /* XXX: ntohl may be more honest */
2028 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2031 CYString &(*PackageName)(Package *self, SEL sel);
2033 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2034 _profile(PackageNameCompare)
2035 CYString &lhi(PackageName(lhs, @selector(cyname)));
2036 CYString &rhi(PackageName(rhs, @selector(cyname)));
2037 CFStringRef lhn(lhi), rhn(rhi);
2040 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2041 else if (rhn == NULL)
2042 return NSOrderedDescending;
2044 _profile(PackageNameCompare$NumbersLast)
2045 if (!lhi.empty() && !rhi.empty()) {
2046 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2047 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2048 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2049 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2050 return lha ? NSOrderedAscending : NSOrderedDescending;
2054 CFIndex length = CFStringGetLength(lhn);
2056 _profile(PackageNameCompare$Compare)
2057 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2062 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2063 return PackageNameCompare(*lhs, *rhs, context);
2066 struct PackageNameOrdering :
2067 std::binary_function<Package *, Package *, bool>
2069 _finline bool operator ()(Package *lhs, Package *rhs) const {
2070 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2074 @implementation Package
2076 - (NSString *) description {
2077 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2082 apr_pool_destroy(pool_);
2083 if (parsed_ != NULL)
2088 + (NSString *) webScriptNameForSelector:(SEL)selector {
2090 else if (selector == @selector(clear))
2092 else if (selector == @selector(getField:))
2094 else if (selector == @selector(hasTag:))
2096 else if (selector == @selector(install))
2098 else if (selector == @selector(remove))
2104 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2105 return [self webScriptNameForSelector:selector] == nil;
2108 + (NSArray *) _attributeKeys {
2109 return [NSArray arrayWithObjects:
2130 @"shortDescription",
2143 - (NSArray *) attributeKeys {
2144 return [[self class] _attributeKeys];
2147 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2148 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2151 - (NSArray *) relations {
2152 @synchronized (database_) {
2153 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2154 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2155 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2159 - (NSString *) architecture {
2161 @synchronized (database_) {
2162 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2165 - (NSString *) getField:(NSString *)name {
2166 @synchronized (database_) {
2167 if ([database_ era] != era_ || file_.end())
2170 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2172 const char *start, *end;
2173 if (!parser.Find([name UTF8String], start, end))
2174 return (NSString *) [NSNull null];
2176 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2180 if (parsed_ != NULL)
2182 @synchronized (database_) {
2183 if ([database_ era] != era_ || file_.end())
2186 ParsedPackage *parsed(new ParsedPackage);
2189 _profile(Package$parse)
2190 pkgRecords::Parser *parser;
2192 _profile(Package$parse$Lookup)
2193 parser = &[database_ records]->Lookup(file_);
2198 _profile(Package$parse$Find)
2203 {"architecture", &parsed->architecture_},
2204 {"icon", &parsed->icon_},
2205 {"depiction", &parsed->depiction_},
2206 {"homepage", &parsed->homepage_},
2207 {"website", &website},
2208 {"bugs", &parsed->bugs_},
2209 {"support", &parsed->support_},
2210 {"sponsor", &parsed->sponsor_},
2211 {"author", &parsed->author_},
2212 {"md5sum", &parsed->md5sum_},
2215 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2216 const char *start, *end;
2218 if (parser->Find(names[i].name_, start, end)) {
2219 CYString &value(*names[i].value_);
2220 _profile(Package$parse$Value)
2221 value.set(pool_, start, end - start);
2227 _profile(Package$parse$Tagline)
2228 const char *start, *end;
2229 if (parser->ShortDesc(start, end)) {
2230 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2233 while (stop != start && stop[-1] == '\r')
2235 parsed->tagline_.set(pool_, start, stop - start);
2239 _profile(Package$parse$Retain)
2240 if (parsed->homepage_.empty())
2241 parsed->homepage_ = website;
2242 if (parsed->homepage_ == parsed->depiction_)
2243 parsed->homepage_.clear();
2248 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2249 if ((self = [super init]) != nil) {
2250 _profile(Package$initWithVersion)
2252 apr_pool_create(&pool_, NULL);
2258 database_ = database;
2259 era_ = [database era];
2263 pkgCache::PkgIterator iterator(version.ParentPkg());
2264 iterator_ = iterator;
2266 _profile(Package$initWithVersion$Version)
2267 if (!version_.end())
2268 file_ = version_.FileList();
2270 pkgCache &cache([database_ cache]);
2271 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2275 _profile(Package$initWithVersion$Cache)
2276 name_.set(NULL, iterator.Display());
2278 latest_.set(NULL, StripVersion_(version_.VerStr()));
2280 pkgCache::VerIterator current(iterator.CurrentVer());
2282 installed_.set(NULL, StripVersion_(current.VerStr()));
2285 _profile(Package$initWithVersion$Tags)
2286 pkgCache::TagIterator tag(iterator.TagList());
2288 tags_ = [NSMutableArray arrayWithCapacity:8];
2290 const char *name(tag.Name());
2291 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2293 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2294 if (strcmp(name + 6, "enduser") == 0)
2296 else if (strcmp(name + 6, "hacker") == 0)
2298 else if (strcmp(name + 6, "developer") == 0)
2300 else if (strcmp(name + 6, "cydia") == 0)
2306 if (strncmp(name, "cydia::", 7) == 0) {
2307 if (strcmp(name + 7, "essential") == 0)
2309 else if (strcmp(name + 7, "obsolete") == 0)
2314 } while (!tag.end());
2318 _profile(Package$initWithVersion$Metadata)
2319 const char *mixed(iterator.Name());
2320 size_t size(strlen(mixed));
2321 char lower[size + 1];
2323 for (size_t i(0); i != size; ++i)
2324 lower[i] = mixed[i] | 0x20;
2327 PackageValue *metadata(PackageFind(lower, size));
2328 metadata_ = metadata;
2330 id_.set(NULL, metadata->name_, size);
2332 const char *latest(version_.VerStr());
2333 size_t length(strlen(latest));
2335 uint16_t vhash(hashlittle(latest, length));
2337 size_t capped(std::min<size_t>(8, length));
2338 latest = latest + length - capped;
2340 if (metadata->first_ == 0)
2341 metadata->first_ = now_;
2343 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2344 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2345 metadata->vhash_ = vhash;
2346 metadata->last_ = now_;
2347 } else if (metadata->last_ == 0)
2348 metadata->last_ = metadata->first_;
2351 _profile(Package$initWithVersion$Section)
2352 section_ = iterator.Section();
2355 _profile(Package$initWithVersion$Flags)
2356 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2357 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2362 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2363 pkgCache::VerIterator version;
2365 _profile(Package$packageWithIterator$GetCandidateVer)
2366 version = [database policy]->GetCandidateVer(iterator);
2374 _profile(Package$packageWithIterator$Allocate)
2375 package = [Package allocWithZone:zone];
2378 _profile(Package$packageWithIterator$Initialize)
2380 initWithVersion:version
2387 _profile(Package$packageWithIterator$Autorelease)
2388 package = [package autorelease];
2394 - (pkgCache::PkgIterator) iterator {
2398 - (NSString *) section {
2399 if (section$_ == nil) {
2400 if (section_ == NULL)
2403 _profile(Package$section$mappedSectionForPointer)
2404 section$_ = [database_ mappedSectionForPointer:section_];
2409 - (NSString *) simpleSection {
2410 if (NSString *section = [self section])
2411 return Simplify(section);
2416 - (NSString *) longSection {
2417 return LocalizeSection([self section]);
2420 - (NSString *) shortSection {
2421 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2424 - (NSString *) uri {
2427 pkgIndexFile *index;
2428 pkgCache::PkgFileIterator file(file_.File());
2429 if (![database_ list].FindIndex(file, index))
2431 return [NSString stringWithUTF8String:iterator_->Path];
2432 //return [NSString stringWithUTF8String:file.Site()];
2433 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2437 - (MIMEAddress *) maintainer {
2438 @synchronized (database_) {
2439 if ([database_ era] != era_ || file_.end())
2442 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2443 const std::string &maintainer(parser->Maintainer());
2444 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2447 - (NSString *) md5sum {
2448 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2452 @synchronized (database_) {
2453 if ([database_ era] != era_ || version_.end())
2456 return version_->InstalledSize;
2459 - (NSString *) longDescription {
2460 @synchronized (database_) {
2461 if ([database_ era] != era_ || file_.end())
2464 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2465 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2467 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2468 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2469 if ([lines count] < 2)
2472 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2473 for (size_t i(1), e([lines count]); i != e; ++i) {
2474 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2475 [trimmed addObject:trim];
2478 return [trimmed componentsJoinedByString:@"\n"];
2481 - (NSString *) shortDescription {
2482 if (parsed_ != NULL)
2483 return static_cast<NSString *>(parsed_->tagline_);
2485 @synchronized (database_) {
2486 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2488 const char *start, *end;
2489 if (!parser.ShortDesc(start, end))
2492 if (end - start > 200)
2496 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2499 while (end != start && end[-1] == '\r')
2503 return [(id) CYStringCreate(start, end - start) autorelease];
2507 _profile(Package$index)
2508 CFStringRef name((CFStringRef) [self name]);
2509 if (CFStringGetLength(name) == 0)
2511 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2512 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2514 return toupper(character);
2518 - (PackageValue *) metadata {
2523 PackageValue *metadata([self metadata]);
2524 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2527 - (bool) subscribed {
2528 return [self metadata]->subscribed_;
2531 - (bool) setSubscribed:(bool)subscribed {
2532 PackageValue *metadata([self metadata]);
2533 if (metadata->subscribed_ == subscribed)
2535 metadata->subscribed_ = subscribed;
2543 - (NSString *) latest {
2547 - (NSString *) installed {
2551 - (BOOL) uninstalled {
2552 return installed_.empty();
2556 return !version_.end();
2559 - (BOOL) upgradableAndEssential:(BOOL)essential {
2560 _profile(Package$upgradableAndEssential)
2561 pkgCache::VerIterator current(iterator_.CurrentVer());
2563 return essential && essential_;
2565 return !version_.end() && version_ != current;
2569 - (BOOL) essential {
2574 return [database_ cache][iterator_].InstBroken();
2577 - (BOOL) unfiltered {
2578 _profile(Package$unfiltered$obsolete)
2579 if (_unlikely(obsolete_))
2583 _profile(Package$unfiltered$hasSupportingRole)
2584 if (_unlikely(![self hasSupportingRole]))
2592 if (![self unfiltered])
2597 _profile(Package$visible$section)
2598 section = [self section];
2601 _profile(Package$visible$isSectionVisible)
2602 if (!isSectionVisible(section))
2610 unsigned char current(iterator_->CurrentState);
2611 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2614 - (BOOL) halfConfigured {
2615 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2618 - (BOOL) halfInstalled {
2619 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2623 @synchronized (database_) {
2624 if ([database_ era] != era_ || iterator_.end())
2627 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2628 return state.Mode != pkgDepCache::ModeKeep;
2631 - (NSString *) mode {
2632 @synchronized (database_) {
2633 if ([database_ era] != era_ || iterator_.end())
2636 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2638 switch (state.Mode) {
2639 case pkgDepCache::ModeDelete:
2640 if ((state.iFlags & pkgDepCache::Purge) != 0)
2644 case pkgDepCache::ModeKeep:
2645 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2646 return @"REINSTALL";
2647 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2651 case pkgDepCache::ModeInstall:
2652 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2653 return @"REINSTALL";
2654 else*/ switch (state.Status) {
2656 return @"DOWNGRADE";
2662 return @"NEW_INSTALL";
2673 - (NSString *) name {
2674 return name_.empty() ? id_ : name_;
2677 - (UIImage *) icon {
2678 NSString *section = [self simpleSection];
2681 if (parsed_ != NULL)
2682 if (NSString *href = parsed_->icon_)
2683 if ([href hasPrefix:@"file:///"])
2684 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2685 if (icon == nil) if (section != nil)
2686 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2687 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2688 if ([dicon hasPrefix:@"file:///"])
2689 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2691 icon = [UIImage applicationImageNamed:@"unknown.png"];
2695 - (NSString *) homepage {
2696 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2699 - (NSString *) depiction {
2700 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2703 - (MIMEAddress *) sponsor {
2704 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2707 - (MIMEAddress *) author {
2708 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2711 - (NSString *) support {
2712 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2715 - (NSArray *) files {
2716 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2717 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2720 fin.open([path UTF8String]);
2725 while (std::getline(fin, line))
2726 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2731 - (NSString *) state {
2732 @synchronized (database_) {
2733 if ([database_ era] != era_ || file_.end())
2736 switch (iterator_->CurrentState) {
2737 case pkgCache::State::NotInstalled:
2738 return @"NotInstalled";
2739 case pkgCache::State::UnPacked:
2741 case pkgCache::State::HalfConfigured:
2742 return @"HalfConfigured";
2743 case pkgCache::State::HalfInstalled:
2744 return @"HalfInstalled";
2745 case pkgCache::State::ConfigFiles:
2746 return @"ConfigFiles";
2747 case pkgCache::State::Installed:
2748 return @"Installed";
2749 case pkgCache::State::TriggersAwaited:
2750 return @"TriggersAwaited";
2751 case pkgCache::State::TriggersPending:
2752 return @"TriggersPending";
2755 return (NSString *) [NSNull null];
2758 - (NSString *) selection {
2759 @synchronized (database_) {
2760 if ([database_ era] != era_ || file_.end())
2763 switch (iterator_->SelectedState) {
2764 case pkgCache::State::Unknown:
2766 case pkgCache::State::Install:
2768 case pkgCache::State::Hold:
2770 case pkgCache::State::DeInstall:
2771 return @"DeInstall";
2772 case pkgCache::State::Purge:
2776 return (NSString *) [NSNull null];
2779 - (NSArray *) warnings {
2780 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2781 const char *name(iterator_.Name());
2783 size_t length(strlen(name));
2784 if (length < 2) invalid:
2785 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2786 else for (size_t i(0); i != length; ++i)
2788 /* XXX: technically this is not allowed */
2789 (name[i] < 'A' || name[i] > 'Z') &&
2790 (name[i] < 'a' || name[i] > 'z') &&
2791 (name[i] < '0' || name[i] > '9') &&
2792 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2795 if (strcmp(name, "cydia") != 0) {
2798 bool _private = false;
2801 bool repository = [[self section] isEqualToString:@"Repositories"];
2803 if (NSArray *files = [self files])
2804 for (NSString *file in files)
2805 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2807 else if (!user && [file isEqualToString:@"/User"])
2809 else if (!_private && [file isEqualToString:@"/private"])
2811 else if (!stash && [file isEqualToString:@"/var/stash"])
2814 /* XXX: this is not sensitive enough. only some folders are valid. */
2815 if (cydia && !repository)
2816 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2818 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2820 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2822 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2825 return [warnings count] == 0 ? nil : warnings;
2828 - (NSArray *) applications {
2829 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2831 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2833 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2834 if (NSArray *files = [self files])
2835 for (NSString *file in files)
2836 if (application_r(file)) {
2837 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2838 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2839 if ([id isEqualToString:me])
2842 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2844 display = application_r[1];
2846 NSString *bundle([file stringByDeletingLastPathComponent]);
2847 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2848 if (icon == nil || [icon length] == 0)
2850 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2852 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2853 [applications addObject:application];
2855 [application addObject:id];
2856 [application addObject:display];
2857 [application addObject:url];
2860 return [applications count] == 0 ? nil : applications;
2863 - (Source *) source {
2864 if (source_ == nil) {
2865 @synchronized (database_) {
2866 if ([database_ era] != era_ || file_.end())
2867 source_ = (Source *) [NSNull null];
2869 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2873 return source_ == (Source *) [NSNull null] ? nil : source_;
2880 - (BOOL) matches:(NSArray *)query {
2881 if (query == nil || [query count] == 0)
2890 string = [self name];
2891 length = [string length];
2893 for (NSString *term in query) {
2894 range = [string rangeOfString:term options:MatchCompareOptions_];
2895 if (range.location != NSNotFound)
2896 rank_ -= 6 * 1000000 / length;
2901 length = [string length];
2903 for (NSString *term in query) {
2904 range = [string rangeOfString:term options:MatchCompareOptions_];
2905 if (range.location != NSNotFound)
2906 rank_ -= 6 * 1000000 / length;
2910 string = [self shortDescription];
2911 length = [string length];
2912 NSUInteger stop(std::min<NSUInteger>(length, 200));
2914 for (NSString *term in query) {
2915 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2916 if (range.location != NSNotFound)
2917 rank_ -= 2 * 100000;
2923 - (bool) hasSupportingRole {
2928 if ([Role_ isEqualToString:@"User"])
2932 if ([Role_ isEqualToString:@"Hacker"])
2936 if ([Role_ isEqualToString:@"Developer"])
2941 - (NSArray *) tags {
2945 - (BOOL) hasTag:(NSString *)tag {
2946 return tags_ == nil ? NO : [tags_ containsObject:tag];
2949 - (NSString *) primaryPurpose {
2950 for (NSString *tag in (NSArray *) tags_)
2951 if ([tag hasPrefix:@"purpose::"])
2952 return [tag substringFromIndex:9];
2956 - (NSArray *) purposes {
2957 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2958 for (NSString *tag in (NSArray *) tags_)
2959 if ([tag hasPrefix:@"purpose::"])
2960 [purposes addObject:[tag substringFromIndex:9]];
2961 return [purposes count] == 0 ? nil : purposes;
2964 - (bool) isCommercial {
2965 return [self hasTag:@"cydia::commercial"];
2968 - (void) setIndex:(size_t)index {
2969 if (metadata_->index_ != index)
2970 metadata_->index_ = index;
2973 - (CYString &) cyname {
2974 return name_.empty() ? id_ : name_;
2977 - (uint32_t) compareBySection:(NSArray *)sections {
2978 NSString *section([self section]);
2979 for (size_t i(0), e([sections count]); i != e; ++i) {
2980 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2984 return _not(uint32_t);
2988 @synchronized (database_) {
2989 pkgProblemResolver *resolver = [database_ resolver];
2990 resolver->Clear(iterator_);
2992 pkgCacheFile &cache([database_ cache]);
2993 cache->SetReInstall(iterator_, false);
2994 cache->MarkKeep(iterator_, false);
2998 @synchronized (database_) {
2999 pkgProblemResolver *resolver = [database_ resolver];
3000 resolver->Clear(iterator_);
3001 resolver->Protect(iterator_);
3003 pkgCacheFile &cache([database_ cache]);
3004 cache->SetReInstall(iterator_, false);
3005 cache->MarkInstall(iterator_, false);
3007 pkgDepCache::StateCache &state((*cache)[iterator_]);
3008 if (!state.Install())
3009 cache->SetReInstall(iterator_, true);
3013 @synchronized (database_) {
3014 pkgProblemResolver *resolver = [database_ resolver];
3015 resolver->Clear(iterator_);
3016 resolver->Remove(iterator_);
3017 resolver->Protect(iterator_);
3019 pkgCacheFile &cache([database_ cache]);
3020 cache->SetReInstall(iterator_, false);
3021 cache->MarkDelete(iterator_, true);
3024 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3025 _profile(Package$isUnfilteredAndSearchedForBy)
3028 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3029 value &= [self unfiltered];
3032 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3033 value &= [self matches:query];
3040 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3041 if ([search length] == 0)
3044 _profile(Package$isUnfilteredAndSelectedForBy)
3047 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3048 value &= [self unfiltered];
3051 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3052 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3059 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3060 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3063 - (bool) isVisibleInSection:(NSString *)name {
3064 NSString *section([self section]);
3068 section == nil && [name length] == 0 ||
3069 [name isEqualToString:section]
3070 ) && [self visible];
3073 - (bool) isVisibleInSource:(Source *)source {
3074 return [self source] == source && [self visible];
3079 /* Section Class {{{ */
3080 @interface Section : NSObject {
3085 _H<NSString> localized_;
3088 - (NSComparisonResult) compareByLocalized:(Section *)section;
3089 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3090 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3091 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3092 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3093 - (NSString *) name;
3100 - (void) addToCount;
3102 - (void) setCount:(size_t)count;
3103 - (NSString *) localized;
3107 @implementation Section
3109 - (NSComparisonResult) compareByLocalized:(Section *)section {
3110 NSString *lhs(localized_);
3111 NSString *rhs([section localized]);
3113 /*if ([lhs length] != 0 && [rhs length] != 0) {
3114 unichar lhc = [lhs characterAtIndex:0];
3115 unichar rhc = [rhs characterAtIndex:0];
3117 if (isalpha(lhc) && !isalpha(rhc))
3118 return NSOrderedAscending;
3119 else if (!isalpha(lhc) && isalpha(rhc))
3120 return NSOrderedDescending;
3123 return [lhs compare:rhs options:LaxCompareOptions_];
3126 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3127 if ((self = [self initWithName:name localize:NO]) != nil) {
3128 if (localized != nil)
3129 localized_ = localized;
3133 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3134 return [self initWithName:name row:0 localize:localize];
3137 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3138 if ((self = [super init]) != nil) {
3143 localized_ = LocalizeSection(name_);
3147 /* XXX: localize the index thingees */
3148 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3149 if ((self = [super init]) != nil) {
3150 name_ = [NSString stringWithCharacters:&index length:1];
3156 - (NSString *) name {
3176 - (void) addToCount {
3180 - (void) setCount:(size_t)count {
3184 - (NSString *) localized {
3191 class CydiaLogCleaner :
3192 public pkgArchiveCleaner
3195 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3200 /* Database Implementation {{{ */
3201 @implementation Database
3203 + (Database *) sharedInstance {
3204 static _H<Database> instance;
3205 if (instance == nil)
3206 instance = [[[Database alloc] init] autorelease];
3214 - (void) releasePackages {
3215 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3216 CFArrayRemoveAllValues(packages_);
3220 // XXX: actually implement this thing
3222 [self releasePackages];
3223 apr_pool_destroy(pool_);
3224 NSRecycleZone(zone_);
3228 - (void) _readCydia:(NSNumber *)fd {
3229 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3230 std::istream is(&ib);
3233 static Pcre finish_r("^finish:([^:]*)$");
3235 while (std::getline(is, line)) {
3236 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3238 const char *data(line.c_str());
3239 size_t size = line.size();
3240 lprintf("C:%s\n", data);
3242 if (finish_r(data, size)) {
3243 NSString *finish = finish_r[1];
3244 int index = [Finishes_ indexOfObject:finish];
3245 if (index != INT_MAX && index > Finish_)
3255 - (void) _readStatus:(NSNumber *)fd {
3256 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3257 std::istream is(&ib);
3260 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3261 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3263 while (std::getline(is, line)) {
3264 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3266 const char *data(line.c_str());
3267 size_t size(line.size());
3268 lprintf("S:%s\n", data);
3270 if (conffile_r(data, size)) {
3271 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3272 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3273 } else if (strncmp(data, "status: ", 8) == 0) {
3274 // status: <package>: {unpacked,half-configured,installed}
3275 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3276 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3277 } else if (strncmp(data, "processing: ", 12) == 0) {
3278 // processing: configure: config-test
3279 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3280 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3281 } else if (pmstatus_r(data, size)) {
3282 std::string type([pmstatus_r[1] UTF8String]);
3284 NSString *package = pmstatus_r[2];
3285 if ([package isEqualToString:@"dpkg-exec"])
3288 float percent([pmstatus_r[3] floatValue]);
3289 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3291 NSString *string = pmstatus_r[4];
3293 if (type == "pmerror") {
3294 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3295 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3296 } else if (type == "pmstatus") {
3297 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3298 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3299 } else if (type == "pmconffile")
3300 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3302 lprintf("E:unknown pmstatus\n");
3304 lprintf("E:unknown status\n");
3312 - (void) _readOutput:(NSNumber *)fd {
3313 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3314 std::istream is(&ib);
3317 while (std::getline(is, line)) {
3318 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3320 lprintf("O:%s\n", line.c_str());
3322 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3323 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3335 - (Package *) packageWithName:(NSString *)name {
3338 @synchronized (self) {
3339 if (static_cast<pkgDepCache *>(cache_) == NULL)
3341 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3342 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3346 if ((self = [super init]) != nil) {
3353 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3354 apr_pool_create(&pool_, NULL);
3356 size_t capacity(MetaFile_->active_);
3362 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3363 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3367 _assert(pipe(fds) != -1);
3370 _config->Set("APT::Keep-Fds::", cydiafd_);
3371 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3374 detachNewThreadSelector:@selector(_readCydia:)
3376 withObject:[NSNumber numberWithInt:fds[0]]
3379 _assert(pipe(fds) != -1);
3383 detachNewThreadSelector:@selector(_readStatus:)
3385 withObject:[NSNumber numberWithInt:fds[0]]
3388 _assert(pipe(fds) != -1);
3389 _assert(dup2(fds[0], 0) != -1);
3390 _assert(close(fds[0]) != -1);
3392 input_ = fdopen(fds[1], "a");
3394 _assert(pipe(fds) != -1);
3395 _assert(dup2(fds[1], 1) != -1);
3396 _assert(close(fds[1]) != -1);
3399 detachNewThreadSelector:@selector(_readOutput:)
3401 withObject:[NSNumber numberWithInt:fds[0]]
3406 - (pkgCacheFile &) cache {
3410 - (pkgDepCache::Policy *) policy {
3414 - (pkgRecords *) records {
3418 - (pkgProblemResolver *) resolver {
3422 - (pkgAcquire &) fetcher {
3426 - (pkgSourceList &) list {
3430 - (NSArray *) packages {
3431 return (NSArray *) packages_;
3434 - (NSArray *) sources {
3438 - (Source *) sourceWithKey:(NSString *)key {
3439 for (Source *source in [self sources]) {
3440 if ([[source key] isEqualToString:key])
3445 - (bool) popErrorWithTitle:(NSString *)title {
3448 while (!_error->empty()) {
3450 bool warning(!_error->PopMessage(error));
3455 size_t size(error.size());
3456 if (size == 0 || error[size - 1] != '\n')
3458 error.resize(size - 1);
3461 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3463 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3464 if (warning && no_pubkey(error.c_str()))
3467 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3473 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3474 return [self popErrorWithTitle:title] || !success;
3477 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3478 @synchronized (self) {
3481 [self releasePackages];
3484 [sourceList_ removeAllObjects];
3504 apr_pool_clear(pool_);
3506 NSRecycleZone(zone_);
3507 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3509 int chk(creat("/tmp/cydia.chk", 0644));
3513 if (invocation != nil)
3514 [invocation invoke];
3516 NSString *title(UCLocalize("DATABASE"));
3519 OpProgress progress;
3520 while (!cache_.Open(progress, true)) { pop:
3522 bool warning(!_error->PopMessage(error));
3523 lprintf("cache_.Open():[%s]\n", error.c_str());
3525 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3526 [delegate_ repairWithSelector:@selector(configure)];
3527 else if (error == "The package lists or status file could not be parsed or opened.")
3528 [delegate_ repairWithSelector:@selector(update)];
3529 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3530 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3531 // else if (error == "Malformed Status line")
3532 // else if (error == "The list of sources could not be read.")
3534 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3544 unlink("/tmp/cydia.chk");
3546 now_ = [[NSDate date] timeIntervalSince1970];
3548 policy_ = new pkgDepCache::Policy();
3549 records_ = new pkgRecords(cache_);
3550 resolver_ = new pkgProblemResolver(cache_);
3551 fetcher_ = new pkgAcquire(&status_);
3554 list_ = new pkgSourceList();
3555 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3558 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3559 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3563 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3566 if (cache_->BrokenCount() != 0) {
3567 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3570 if (cache_->BrokenCount() != 0) {
3571 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3575 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3579 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3580 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3581 [sourceList_ addObject:object];
3583 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3584 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3585 // XXX: this could be more intelligent
3586 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3587 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3589 sourceMap_[cached->ID] = object;
3594 /*std::vector<Package *> packages;
3595 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3600 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3601 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3602 //packages.push_back(package);
3603 CFArrayAppendValue(packages_, CFRetain(package));
3607 /*if (packages.empty())
3608 packages_ = [[NSArray alloc] init];
3610 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3613 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3614 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3615 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3623 /*if (!packages.empty())
3624 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3625 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3627 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3629 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3631 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3635 size_t count(CFArrayGetCount(packages_));
3636 MetaFile_->active_ = count;
3638 for (size_t index(0); index != count; ++index)
3639 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3646 @synchronized (self) {
3648 resolver_ = new pkgProblemResolver(cache_);
3650 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3651 if (!cache_[iterator].Keep())
3652 cache_->MarkKeep(iterator, false);
3653 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3654 cache_->SetReInstall(iterator, false);
3657 - (void) configure {
3658 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3660 system([dpkg UTF8String]);
3665 // XXX: I don't remember this condition
3670 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3672 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3674 if ([self popErrorWithTitle:title])
3678 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3680 CydiaLogCleaner cleaner;
3681 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3688 fetcher_->Shutdown();
3690 pkgRecords records(cache_);
3692 lock_ = new FileFd();
3693 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3695 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3697 if ([self popErrorWithTitle:title])
3701 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3704 manager_ = (_system->CreatePM(cache_));
3705 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3712 bool substrate(RestartSubstrate_);
3713 RestartSubstrate_ = false;
3715 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3717 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3719 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3721 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3722 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3725 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3727 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3729 [self popErrorWithTitle:title];
3733 bool failed = false;
3734 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3735 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3737 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3743 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3751 RestartSubstrate_ = true;
3754 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3756 if (_error->PendingError()) {
3761 if (result == pkgPackageManager::Failed) {
3766 if (result != pkgPackageManager::Completed) {
3771 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3773 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3775 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3776 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3779 if (![before isEqualToArray:after])
3784 NSString *title(UCLocalize("UPGRADE"));
3785 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3791 [self updateWithStatus:status_];
3794 - (void) updateWithStatus:(Status &)status {
3795 NSString *title(UCLocalize("REFRESHING_DATA"));
3798 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3802 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3803 if ([self popErrorWithTitle:title])
3806 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3808 bool success(ListUpdate(status, list, PulseInterval_));
3809 if (status.WasCancelled())
3812 [self popErrorWithTitle:title forOperation:success];
3813 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3817 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3820 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3821 delegate_ = delegate;
3824 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3825 progress_ = delegate;
3826 status_.setDelegate(delegate);
3829 - (NSObject<ProgressDelegate> *) progressDelegate {
3833 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3834 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3835 return i == sourceMap_.end() ? nil : i->second;
3838 - (NSString *) mappedSectionForPointer:(const char *)section {
3839 _H<NSString> *mapped;
3841 _profile(Database$mappedSectionForPointer$Cache)
3842 mapped = §ions_[section];
3845 if (*mapped == NULL) {
3846 size_t length(strlen(section));
3847 char spaced[length + 1];
3849 _profile(Database$mappedSectionForPointer$Replace)
3850 for (size_t index(0); index != length; ++index)
3851 spaced[index] = section[index] == '_' ? ' ' : section[index];
3852 spaced[length] = '\0';
3857 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3858 string = [NSString stringWithUTF8String:spaced];
3861 _profile(Database$mappedSectionForPointer$Map)
3862 string = [SectionMap_ objectForKey:string] ?: string;
3872 static _H<NSMutableSet> Diversions_;
3874 @interface Diversion : NSObject {
3877 _H<NSString> format_;
3882 @implementation Diversion
3884 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3885 if ((self = [super init]) != nil) {
3886 pattern_ = [from UTF8String];
3892 - (NSString *) divert:(NSString *)url {
3893 return !pattern_(url) ? nil : pattern_->*format_;
3896 + (NSURL *) divertURL:(NSURL *)url {
3898 NSString *href([url absoluteString]);
3900 for (Diversion *diversion in (id) Diversions_)
3901 if (NSString *diverted = [diversion divert:href]) {
3903 NSLog(@"div: %@", diverted);
3905 url = [NSURL URLWithString:diverted];
3912 - (NSString *) key {
3916 - (NSUInteger) hash {
3920 - (BOOL) isEqual:(Diversion *)object {
3921 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3926 @interface CydiaObject : NSObject {
3927 _H<IndirectDelegate> indirect_;
3928 _transient id delegate_;
3931 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3937 @interface CydiaWebViewController : CyteWebViewController {
3938 _H<CydiaObject> cydia_;
3941 + (void) addDiversion:(Diversion *)diversion;
3942 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
3943 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
3944 - (void) setDelegate:(id)delegate;
3948 /* Web Scripting {{{ */
3949 @implementation CydiaObject
3951 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3952 if ((self = [super init]) != nil) {
3953 indirect_ = indirect;
3957 - (void) setDelegate:(id)delegate {
3958 delegate_ = delegate;
3961 + (NSArray *) _attributeKeys {
3962 return [NSArray arrayWithObjects:
3965 @"coreFoundationVersionNumber",
3982 - (NSArray *) attributeKeys {
3983 return [[self class] _attributeKeys];
3986 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3987 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3990 - (NSString *) version {
3994 - (NSString *) build {
3998 - (NSString *) coreFoundationVersionNumber {
3999 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4002 - (NSString *) device {
4003 return [[UIDevice currentDevice] uniqueIdentifier];
4006 - (NSString *) firmware {
4007 return [[UIDevice currentDevice] systemVersion];
4010 - (NSString *) hostname {
4011 return [[UIDevice currentDevice] name];
4014 - (NSString *) idiom {
4015 return (id) Idiom_ ?: [NSNull null];
4018 - (NSString *) mcc {
4019 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4020 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4024 - (NSString *) mnc {
4025 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4026 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4030 - (NSString *) operator {
4031 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4032 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4036 - (NSString *) bbsnum {
4037 return (id) BBSNum_ ?: [NSNull null];
4040 - (NSString *) ecid {
4041 return (id) ChipID_ ?: [NSNull null];
4044 - (NSString *) serial {
4045 return SerialNumber_;
4048 - (NSString *) role {
4049 return (id) Role_ ?: [NSNull null];
4052 - (NSString *) model {
4053 return [NSString stringWithUTF8String:Machine_];
4056 - (NSString *) token {
4057 return (id) Token_ ?: [NSNull null];
4060 + (NSString *) webScriptNameForSelector:(SEL)selector {
4062 else if (selector == @selector(addBridgedHost:))
4063 return @"addBridgedHost";
4064 else if (selector == @selector(addInsecureHost:))
4065 return @"addInsecureHost";
4066 else if (selector == @selector(addInternalRedirect::))
4067 return @"addInternalRedirect";
4068 else if (selector == @selector(addPipelinedHost:scheme:))
4069 return @"addPipelinedHost";
4070 else if (selector == @selector(addSource:::))
4071 return @"addSource";
4072 else if (selector == @selector(addTokenHost:))
4073 return @"addTokenHost";
4074 else if (selector == @selector(addTrivialSource:))
4075 return @"addTrivialSource";
4076 else if (selector == @selector(close))
4078 else if (selector == @selector(du:))
4080 else if (selector == @selector(stringWithFormat:arguments:))
4082 else if (selector == @selector(getAllSources))
4083 return @"getAllSourcs";
4084 else if (selector == @selector(getKernelNumber:))
4085 return @"getKernelNumber";
4086 else if (selector == @selector(getKernelString:))
4087 return @"getKernelString";
4088 else if (selector == @selector(getInstalledPackages))
4089 return @"getInstalledPackages";
4090 else if (selector == @selector(getIORegistryEntry::))
4091 return @"getIORegistryEntry";
4092 else if (selector == @selector(getLocaleIdentifier))
4093 return @"getLocaleIdentifier";
4094 else if (selector == @selector(getPreferredLanguages))
4095 return @"getPreferredLanguages";
4096 else if (selector == @selector(getPackageById:))
4097 return @"getPackageById";
4098 else if (selector == @selector(getMetadataKeys))
4099 return @"getMetadataKeys";
4100 else if (selector == @selector(getMetadataValue:))
4101 return @"getMetadataValue";
4102 else if (selector == @selector(getSessionValue:))
4103 return @"getSessionValue";
4104 else if (selector == @selector(installPackages:))
4105 return @"installPackages";
4106 else if (selector == @selector(localizedStringForKey:value:table:))
4108 else if (selector == @selector(popViewController:))
4109 return @"popViewController";
4110 else if (selector == @selector(refreshSources))
4111 return @"refreshSources";
4112 else if (selector == @selector(removeButton))
4113 return @"removeButton";
4114 else if (selector == @selector(saveConfig))
4115 return @"saveConfig";
4116 else if (selector == @selector(setMetadataValue::))
4117 return @"setMetadataValue";
4118 else if (selector == @selector(setSessionValue::))
4119 return @"setSessionValue";
4120 else if (selector == @selector(substitutePackageNames:))
4121 return @"substitutePackageNames";
4122 else if (selector == @selector(scrollToBottom:))
4123 return @"scrollToBottom";
4124 else if (selector == @selector(setAllowsNavigationAction:))
4125 return @"setAllowsNavigationAction";
4126 else if (selector == @selector(setBadgeValue:))
4127 return @"setBadgeValue";
4128 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4129 return @"setButtonImage";
4130 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4131 return @"setButtonTitle";
4132 else if (selector == @selector(setHidesBackButton:))
4133 return @"setHidesBackButton";
4134 else if (selector == @selector(setHidesNavigationBar:))
4135 return @"setHidesNavigationBar";
4136 else if (selector == @selector(setNavigationBarStyle:))
4137 return @"setNavigationBarStyle";
4138 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4139 return @"setNavigationBarTintColor";
4140 else if (selector == @selector(setPasteboardString:))
4141 return @"setPasteboardString";
4142 else if (selector == @selector(setPasteboardURL:))
4143 return @"setPasteboardURL";
4144 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4145 return @"setScrollAlwaysBounceVertical";
4146 else if (selector == @selector(setScrollIndicatorStyle:))
4147 return @"setScrollIndicatorStyle";
4148 else if (selector == @selector(setToken:))
4150 else if (selector == @selector(setViewportWidth:))
4151 return @"setViewportWidth";
4152 else if (selector == @selector(statfs:))
4154 else if (selector == @selector(supports:))
4156 else if (selector == @selector(unload))
4162 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4163 return [self webScriptNameForSelector:selector] == nil;
4166 - (BOOL) supports:(NSString *)feature {
4167 return [feature isEqualToString:@"window.open"];
4171 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4174 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4175 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4178 - (void) setScrollIndicatorStyle:(NSString *)style {
4179 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4182 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4183 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4186 - (NSNumber *) getKernelNumber:(NSString *)name {
4187 const char *string([name UTF8String]);
4190 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4191 return (id) [NSNull null];
4193 if (size != sizeof(int))
4194 return (id) [NSNull null];
4197 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4198 return (id) [NSNull null];
4200 return [NSNumber numberWithInt:value];
4203 - (NSString *) getKernelString:(NSString *)name {
4204 const char *string([name UTF8String]);
4207 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4208 return (id) [NSNull null];
4210 char value[size + 1];
4211 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4212 return (id) [NSNull null];
4214 // XXX: just in case you request something ludicrous
4217 return [NSString stringWithCString:value];
4220 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4221 NSObject *value(CYIOGetValue([path UTF8String], entry));
4224 if ([value isKindOfClass:[NSData class]])
4225 value = CYHex((NSData *) value);
4230 - (NSArray *) getMetadataKeys {
4231 @synchronized (Values_) {
4232 return [Values_ allKeys];
4235 - (id) getMetadataValue:(NSString *)key {
4236 @synchronized (Values_) {
4237 return [Values_ objectForKey:key];
4240 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4241 @synchronized (Values_) {
4242 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4243 [Values_ removeObjectForKey:key];
4245 [Values_ setObject:value forKey:key];
4247 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4250 - (id) getSessionValue:(NSString *)key {
4251 @synchronized (SessionData_) {
4252 return [SessionData_ objectForKey:key];
4255 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4256 @synchronized (SessionData_) {
4257 if (value == (id) [WebUndefined undefined])
4258 [SessionData_ removeObjectForKey:key];
4260 [SessionData_ setObject:value forKey:key];
4263 - (void) addBridgedHost:(NSString *)host {
4264 @synchronized (HostConfig_) {
4265 [BridgedHosts_ addObject:host];
4268 - (void) addInsecureHost:(NSString *)host {
4269 @synchronized (HostConfig_) {
4270 [InsecureHosts_ addObject:host];
4273 - (void) addTokenHost:(NSString *)host {
4274 @synchronized (HostConfig_) {
4275 [TokenHosts_ addObject:host];
4278 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4279 @synchronized (HostConfig_) {
4280 if (scheme != (id) [WebUndefined undefined])
4281 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4283 [PipelinedHosts_ addObject:host];
4286 - (void) popViewController:(NSNumber *)value {
4287 if (value == (id) [WebUndefined undefined])
4288 value = [NSNumber numberWithBool:YES];
4289 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4292 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4293 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4295 for (NSString *section in sections)
4296 [array addObject:section];
4298 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4301 distribution, @"Distribution",
4303 nil] waitUntilDone:NO];
4306 - (void) addTrivialSource:(NSString *)href {
4307 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4310 - (void) refreshSources {
4311 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4314 - (void) saveConfig {
4315 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4318 - (NSArray *) getAllSources {
4319 return [[Database sharedInstance] sources];
4322 - (NSArray *) getInstalledPackages {
4323 Database *database([Database sharedInstance]);
4324 @synchronized (database) {
4325 NSArray *packages([database packages]);
4326 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4327 for (Package *package in packages)
4328 if (![package uninstalled])
4329 [installed addObject:package];
4333 - (Package *) getPackageById:(NSString *)id {
4334 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4338 return (Package *) [NSNull null];
4341 - (NSString *) getLocaleIdentifier {
4342 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4345 - (NSArray *) getPreferredLanguages {
4349 - (NSArray *) statfs:(NSString *)path {
4352 if (path == nil || statfs([path UTF8String], &stat) == -1)
4355 return [NSArray arrayWithObjects:
4356 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4357 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4358 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4362 - (NSNumber *) du:(NSString *)path {
4363 NSNumber *value(nil);
4366 _assert(pipe(fds) != -1);
4368 pid_t pid(ExecFork());
4370 _assert(dup2(fds[1], 1) != -1);
4371 _assert(close(fds[0]) != -1);
4372 _assert(close(fds[1]) != -1);
4373 /* XXX: this should probably not use du */
4374 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4379 _assert(close(fds[1]) != -1);
4381 if (FILE *du = fdopen(fds[0], "r")) {
4383 while (fgets(line, sizeof(line), du) != NULL) {
4384 size_t length(strlen(line));
4385 while (length != 0 && line[length - 1] == '\n')
4386 line[--length] = '\0';
4387 if (char *tab = strchr(line, '\t')) {
4389 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4394 } else _assert(close(fds[0]));
4402 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4405 - (void) installPackages:(NSArray *)packages {
4406 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4409 - (NSString *) substitutePackageNames:(NSString *)message {
4410 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4411 for (size_t i(0), e([words count]); i != e; ++i) {
4412 NSString *word([words objectAtIndex:i]);
4413 if (Package *package = [[Database sharedInstance] packageWithName:word])
4414 [words replaceObjectAtIndex:i withObject:[package name]];
4417 return [words componentsJoinedByString:@" "];
4420 - (void) removeButton {
4421 [indirect_ removeButton];
4424 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4425 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4428 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4429 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4432 - (void) setBadgeValue:(id)value {
4433 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4436 - (void) setAllowsNavigationAction:(NSString *)value {
4437 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4440 - (void) setHidesBackButton:(NSString *)value {
4441 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4444 - (void) setHidesNavigationBar:(NSString *)value {
4445 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4448 - (void) setNavigationBarStyle:(NSString *)value {
4449 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4452 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4453 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4454 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4455 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4458 - (void) setPasteboardString:(NSString *)value {
4459 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4462 - (void) setPasteboardURL:(NSString *)value {
4463 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4466 - (void) _setToken:(NSString *)token {
4470 [Metadata_ removeObjectForKey:@"Token"];
4472 [Metadata_ setObject:Token_ forKey:@"Token"];
4477 - (void) setToken:(NSString *)token {
4478 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4481 - (void) scrollToBottom:(NSNumber *)animated {
4482 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4485 - (void) setViewportWidth:(float)width {
4486 [indirect_ setViewportWidthOnMainThread:width];
4489 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4490 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4491 unsigned count([arguments count]);
4493 for (unsigned i(0); i != count; ++i)
4494 values[i] = [arguments objectAtIndex:i];
4495 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4498 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4499 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4501 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4503 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4509 @interface NSURL (CydiaSecure)
4512 @implementation NSURL (CydiaSecure)
4514 - (bool) isCydiaSecure {
4515 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4518 @synchronized (HostConfig_) {
4519 if ([InsecureHosts_ containsObject:[self host]])
4528 /* Cydia Browser Controller {{{ */
4529 @implementation CydiaWebViewController
4531 - (NSURL *) navigationURL {
4532 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4535 + (void) _initialize {
4536 [super _initialize];
4538 Diversions_ = [NSMutableSet setWithCapacity:0];
4541 + (void) addDiversion:(Diversion *)diversion {
4542 [Diversions_ addObject:diversion];
4545 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4546 [super webView:view didClearWindowObject:window forFrame:frame];
4547 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4550 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4551 WebDataSource *source([frame dataSource]);
4552 NSURLResponse *response([source response]);
4553 NSURL *url([response URL]);
4554 NSString *scheme([[url scheme] lowercaseString]);
4556 bool bridged(false);
4558 @synchronized (HostConfig_) {
4559 if ([scheme isEqualToString:@"file"])
4561 else if ([scheme isEqualToString:@"https"])
4562 if ([BridgedHosts_ containsObject:[url host]])
4567 [window setValue:cydia forKey:@"cydia"];
4570 - (void) _setupMail:(MFMailComposeViewController *)controller {
4571 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4573 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4574 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4577 - (NSURL *) URLWithURL:(NSURL *)url {
4578 return [Diversion divertURL:url];
4581 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4582 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4585 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4586 NSMutableURLRequest *copy([request mutableCopy]);
4588 NSURL *url([copy URL]);
4589 NSString *host([url host]);
4591 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf-Version"] == nil)
4592 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf-Version"];
4593 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4594 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4599 @synchronized (HostConfig_) {
4600 bridged = [BridgedHosts_ containsObject:host];
4601 token = [TokenHosts_ containsObject:host];
4604 if ([url isCydiaSecure]) {
4606 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4607 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4609 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4610 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4617 - (void) setDelegate:(id)delegate {
4618 [super setDelegate:delegate];
4619 [cydia_ setDelegate:delegate];
4622 - (NSString *) applicationNameForUserAgent {
4627 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4628 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4634 @interface AppCacheController : CydiaWebViewController {
4639 @implementation AppCacheController
4641 - (void) didReceiveMemoryWarning {
4642 // XXX: this doesn't work
4645 - (bool) retainsNetworkActivityIndicator {
4653 @interface NSObject (CydiaScript)
4654 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4657 @implementation NSObject (CydiaScript)
4659 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4665 @implementation NSArray (CydiaScript)
4667 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4668 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4669 for (size_t i(0), e([self count]); i != e; ++i)
4670 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4676 @implementation NSDictionary (CydiaScript)
4678 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4679 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4681 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4688 /* Confirmation Controller {{{ */
4689 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4690 if (!iterator.end())
4691 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4692 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4694 pkgCache::PkgIterator package(dep.TargetPkg());
4697 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4704 @protocol ConfirmationControllerDelegate
4705 - (void) cancelAndClear:(bool)clear;
4706 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4710 @interface ConfirmationController : CydiaWebViewController {
4711 _transient Database *database_;
4713 _H<UIAlertView> essential_;
4715 _H<NSDictionary> changes_;
4716 _H<NSMutableArray> issues_;
4717 _H<NSDictionary> sizes_;
4722 - (id) initWithDatabase:(Database *)database;
4726 @implementation ConfirmationController
4730 RestartSubstrate_ = true;
4731 [delegate_ confirmWithNavigationController:[self navigationController]];
4734 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4735 NSString *context([alert context]);
4737 if ([context isEqualToString:@"remove"]) {
4738 if (button == [alert cancelButtonIndex])
4739 [self dismissModalViewControllerAnimated:YES];
4740 else if (button == [alert firstOtherButtonIndex]) {
4744 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4745 } else if ([context isEqualToString:@"unable"]) {
4746 [self dismissModalViewControllerAnimated:YES];
4747 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4749 [super alertView:alert clickedButtonAtIndex:button];
4753 - (void) _doContinue {
4754 [delegate_ cancelAndClear:NO];
4755 [self dismissModalViewControllerAnimated:YES];
4758 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4759 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4763 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4764 [super webView:view didClearWindowObject:window forFrame:frame];
4766 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4767 (id) changes_, @"changes",
4768 (id) issues_, @"issues",
4769 (id) sizes_, @"sizes",
4771 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4774 - (id) initWithDatabase:(Database *)database {
4775 if ((self = [super init]) != nil) {
4776 database_ = database;
4778 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4779 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4780 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4781 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4782 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4786 pkgCacheFile &cache([database_ cache]);
4787 NSArray *packages([database_ packages]);
4788 pkgDepCache::Policy *policy([database_ policy]);
4790 issues_ = [NSMutableArray arrayWithCapacity:4];
4792 for (Package *package in packages) {
4793 pkgCache::PkgIterator iterator([package iterator]);
4794 NSString *name([package id]);
4796 if ([package broken]) {
4797 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4799 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4801 reasons, @"reasons",
4804 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4808 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4809 pkgCache::DepIterator start;
4810 pkgCache::DepIterator end;
4811 dep.GlobOr(start, end); // ++dep
4813 if (!cache->IsImportantDep(end))
4815 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4818 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4820 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4821 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4822 clauses, @"clauses",
4826 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4828 pkgCache::PkgIterator target(start.TargetPkg());
4829 if (target->ProvidesList != 0)
4830 reason = @"missing";
4832 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4834 reason = @"installed";
4835 installed = [NSString stringWithUTF8String:ver.VerStr()];
4836 } else if (!cache[target].CandidateVerIter(cache).end())
4837 reason = @"uninstalled";
4838 else if (target->ProvidesList == 0)
4839 reason = @"uninstallable";
4841 reason = @"virtual";
4844 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4845 [NSString stringWithUTF8String:start.CompType()], @"operator",
4846 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4849 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4850 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4851 version, @"version",
4853 installed, @"installed",
4856 // yes, seriously. (wtf?)
4864 pkgDepCache::StateCache &state(cache[iterator]);
4866 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4868 if (state.NewInstall())
4869 [installs addObject:name];
4870 // XXX: else if (state.Install())
4871 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4872 [reinstalls addObject:name];
4873 // XXX: move before previous if
4874 else if (state.Upgrade())
4875 [upgrades addObject:name];
4876 else if (state.Downgrade())
4877 [downgrades addObject:name];
4878 else if (!state.Delete())
4879 // XXX: _assert(state.Keep());
4881 else if (special_r(name))
4882 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4883 [NSNull null], @"package",
4884 [NSArray arrayWithObjects:
4885 [NSDictionary dictionaryWithObjectsAndKeys:
4886 @"Conflicts", @"relationship",
4887 [NSArray arrayWithObjects:
4888 [NSDictionary dictionaryWithObjectsAndKeys:
4890 [NSNull null], @"version",
4891 @"installed", @"reason",
4898 if ([package essential])
4900 [removes addObject:name];
4903 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4904 substrate_ |= DepSubstrate(iterator.CurrentVer());
4909 else if (Advanced_) {
4910 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4912 essential_ = [[[UIAlertView alloc]
4913 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4914 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4916 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4918 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4922 [essential_ setContext:@"remove"];
4924 essential_ = [[[UIAlertView alloc]
4925 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4926 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4928 cancelButtonTitle:UCLocalize("OKAY")
4929 otherButtonTitles:nil
4932 [essential_ setContext:@"unable"];
4935 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4936 installs, @"installs",
4937 reinstalls, @"reinstalls",
4938 upgrades, @"upgrades",
4939 downgrades, @"downgrades",
4940 removes, @"removes",
4943 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4944 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4945 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4948 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4952 - (UIBarButtonItem *) leftButton {
4953 return [[[UIBarButtonItem alloc]
4954 initWithTitle:UCLocalize("CANCEL")
4955 style:UIBarButtonItemStylePlain
4957 action:@selector(cancelButtonClicked)
4962 - (void) applyRightButton {
4963 if ([issues_ count] == 0 && ![self isLoading])
4964 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4965 initWithTitle:UCLocalize("CONFIRM")
4966 style:UIBarButtonItemStyleDone
4968 action:@selector(confirmButtonClicked)
4971 [[self navigationItem] setRightBarButtonItem:nil];
4975 - (void) cancelButtonClicked {
4976 [self dismissModalViewControllerAnimated:YES];
4977 [delegate_ cancelAndClear:YES];
4981 - (void) confirmButtonClicked {
4982 if (essential_ != nil)
4992 /* Progress Data {{{ */
4993 @interface CydiaProgressData : NSObject {
4994 _transient id delegate_;
5003 _H<NSMutableArray> events_;
5004 _H<NSString> title_;
5006 _H<NSString> status_;
5007 _H<NSString> finish_;
5012 @implementation CydiaProgressData
5014 + (NSArray *) _attributeKeys {
5015 return [NSArray arrayWithObjects:
5027 - (NSArray *) attributeKeys {
5028 return [[self class] _attributeKeys];
5031 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5032 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5036 if ((self = [super init]) != nil) {
5037 events_ = [NSMutableArray arrayWithCapacity:32];
5041 - (void) setDelegate:(id)delegate {
5042 delegate_ = delegate;
5045 - (void) setPercent:(float)value {
5049 - (NSNumber *) percent {
5050 return [NSNumber numberWithFloat:percent_];
5053 - (void) setCurrent:(float)value {
5057 - (NSNumber *) current {
5058 return [NSNumber numberWithFloat:current_];
5061 - (void) setTotal:(float)value {
5065 - (NSNumber *) total {
5066 return [NSNumber numberWithFloat:total_];
5069 - (void) setSpeed:(float)value {
5073 - (NSNumber *) speed {
5074 return [NSNumber numberWithFloat:speed_];
5077 - (NSArray *) events {
5081 - (void) removeAllEvents {
5082 [events_ removeAllObjects];
5085 - (void) addEvent:(CydiaProgressEvent *)event {
5086 [events_ addObject:event];
5089 - (void) setTitle:(NSString *)text {
5093 - (NSString *) title {
5097 - (void) setFinish:(NSString *)text {
5101 - (NSString *) finish {
5102 return (id) finish_ ?: [NSNull null];
5105 - (void) setRunning:(bool)running {
5109 - (NSNumber *) running {
5110 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5115 /* Progress Controller {{{ */
5116 @interface ProgressController : CydiaWebViewController <
5119 _transient Database *database_;
5120 _H<CydiaProgressData, 1> progress_;
5124 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5126 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5128 - (void) setTitle:(NSString *)title;
5129 - (void) setCancellable:(bool)cancellable;
5133 @implementation ProgressController
5136 [database_ setProgressDelegate:nil];
5140 - (UIBarButtonItem *) leftButton {
5141 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5142 initWithTitle:UCLocalize("CANCEL")
5143 style:UIBarButtonItemStylePlain
5145 action:@selector(cancel)
5146 ] autorelease] : nil;
5149 - (void) updateCancel {
5150 [super applyLeftButton];
5153 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5154 if ((self = [super init]) != nil) {
5155 database_ = database;
5156 delegate_ = delegate;
5158 [database_ setProgressDelegate:self];
5160 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5161 [progress_ setDelegate:self];
5163 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5165 [scroller_ setBackgroundColor:[UIColor blackColor]];
5167 [[self navigationItem] setHidesBackButton:YES];
5169 [self updateCancel];
5173 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5174 [super webView:view didClearWindowObject:window forFrame:frame];
5175 [window setValue:progress_ forKey:@"cydiaProgress"];
5178 - (void) updateProgress {
5179 [self dispatchEvent:@"CydiaProgressUpdate"];
5182 - (void) viewWillAppear:(BOOL)animated {
5183 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5184 [super viewWillAppear:animated];
5188 UpdateExternalStatus(0);
5191 [delegate_ saveState];
5195 [delegate_ returnToCydia];
5199 [delegate_ terminateWithSuccess];
5200 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5201 [delegate_ suspendWithAnimation:YES];
5203 [delegate_ suspend];*/
5215 system("/usr/bin/sbreload");
5221 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5222 SBReboot(SBSSpringBoardServerPort());
5224 reboot2(RB_AUTOBOOT);
5231 - (void) setTitle:(NSString *)title {
5232 [progress_ setTitle:title];
5233 [self updateProgress];
5236 - (UIBarButtonItem *) rightButton {
5237 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5238 initWithTitle:UCLocalize("CLOSE")
5239 style:UIBarButtonItemStylePlain
5241 action:@selector(close)
5247 system("su -c /usr/bin/uicache mobile");
5251 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5252 UpdateExternalStatus(1);
5254 [progress_ setRunning:true];
5255 [self setTitle:title];
5256 // implicit updateProgress
5258 SHA1SumValue notifyconf; {
5260 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5263 MMap mmap(file, MMap::ReadOnly);
5265 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5266 notifyconf = sha1.Result();
5270 SHA1SumValue springlist; {
5272 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5275 MMap mmap(file, MMap::ReadOnly);
5277 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5278 springlist = sha1.Result();
5282 if (invocation != nil) {
5283 [invocation yieldToSelector:@selector(invoke)];
5284 [self setTitle:@"COMPLETE"];
5289 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5292 MMap mmap(file, MMap::ReadOnly);
5294 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5295 if (!(notifyconf == sha1.Result()))
5302 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5305 MMap mmap(file, MMap::ReadOnly);
5307 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5308 if (!(springlist == sha1.Result()))
5314 if (RestartSubstrate_)
5318 RestartSubstrate_ = false;
5321 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5322 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5323 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5324 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5325 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5328 UIProgressHUD *hud([delegate_ addProgressHUD]);
5329 [hud setText:UCLocalize("LOADING")];
5330 [self yieldToSelector:@selector(uicache)];
5331 [delegate_ removeProgressHUD:hud];
5333 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5335 [progress_ setRunning:false];
5336 [self updateProgress];
5338 [self applyRightButton];
5341 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5342 [progress_ addEvent:event];
5343 [self updateProgress];
5346 - (bool) isProgressCancelled {
5347 return cancel_ == 2;
5352 [self updateCancel];
5355 - (void) setCancellable:(bool)cancellable {
5356 unsigned cancel(cancel_);
5360 else if (cancel_ == 0)
5363 if (cancel != cancel_)
5364 [self updateCancel];
5367 - (void) setProgressCancellable:(NSNumber *)cancellable {
5368 [self setCancellable:[cancellable boolValue]];
5371 - (void) setProgressPercent:(NSNumber *)percent {
5372 [progress_ setPercent:[percent floatValue]];
5373 [self updateProgress];
5376 - (void) setProgressStatus:(NSDictionary *)status {
5377 if (status == nil) {
5378 [progress_ setCurrent:0];
5379 [progress_ setTotal:0];
5380 [progress_ setSpeed:0];
5382 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5384 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5385 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5386 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5389 [self updateProgress];
5395 /* Package Cell {{{ */
5396 @interface PackageCell : CyteTableViewCell <
5397 CyteTableViewCellDelegate
5401 _H<NSString> description_;
5403 _H<NSString> source_;
5405 _H<UIImage> placard_;
5409 - (PackageCell *) init;
5410 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5412 - (void) drawContentRect:(CGRect)rect;
5416 @implementation PackageCell
5418 - (PackageCell *) init {
5419 CGRect frame(CGRectMake(0, 0, 320, 74));
5420 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5421 UIView *content([self contentView]);
5422 CGRect bounds([content bounds]);
5424 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5425 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5426 [content addSubview:content_];
5428 [content_ setDelegate:self];
5429 [content_ setOpaque:YES];
5433 - (NSString *) accessibilityLabel {
5434 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5437 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5438 summarized_ = summary;
5448 [content_ setBackgroundColor:[UIColor whiteColor]];
5452 Source *source = [package source];
5454 icon_ = [package icon];
5456 if (NSString *name = [package name])
5457 name_ = [NSString stringWithString:name];
5459 NSString *description(nil);
5461 if (description == nil && IsWildcat_)
5462 description = [package longDescription];
5463 if (description == nil)
5464 description = [package shortDescription];
5466 if (description != nil)
5467 description_ = [NSString stringWithString:description];
5469 commercial_ = [package isCommercial];
5471 NSString *label = nil;
5472 bool trusted = false;
5474 if (source != nil) {
5475 label = [source label];
5476 trusted = [source trusted];
5477 } else if ([[package id] isEqualToString:@"firmware"])
5478 label = UCLocalize("APPLE");
5480 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5482 NSString *from(label);
5484 NSString *section = [package simpleSection];
5485 if (section != nil && ![section isEqualToString:label]) {
5486 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5487 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5490 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5492 if (NSString *purpose = [package primaryPurpose])
5493 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5498 if (NSString *mode = [package mode]) {
5499 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5500 color = RemovingColor_;
5501 //placard = @"removing";
5503 color = InstallingColor_;
5504 //placard = @"installing";
5507 // XXX: the removing/installing placards are not @2x
5510 color = [UIColor whiteColor];
5512 if ([package installed] != nil)
5513 placard = @"installed";
5518 [content_ setBackgroundColor:color];
5521 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5524 [self setNeedsDisplay];
5525 [content_ setNeedsDisplay];
5528 - (void) drawSummaryContentRect:(CGRect)rect {
5529 bool highlighted(highlighted_);
5530 float width([self bounds].size.width);
5534 rect.size = [(UIImage *) icon_ size];
5536 while (rect.size.width > 16 || rect.size.height > 16) {
5537 rect.size.width /= 2;
5538 rect.size.height /= 2;
5541 rect.origin.x = 18 - rect.size.width / 2;
5542 rect.origin.y = 18 - rect.size.height / 2;
5544 [icon_ drawInRect:rect];
5547 if (badge_ != nil) {
5549 rect.size = [(UIImage *) badge_ size];
5551 rect.size.width /= 4;
5552 rect.size.height /= 4;
5554 rect.origin.x = 23 - rect.size.width / 2;
5555 rect.origin.y = 23 - rect.size.height / 2;
5557 [badge_ drawInRect:rect];
5564 UISetColor(commercial_ ? Purple_ : Black_);
5565 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5567 if (placard_ != nil)
5568 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5571 - (void) drawNormalContentRect:(CGRect)rect {
5572 bool highlighted(highlighted_);
5573 float width([self bounds].size.width);
5577 rect.size = [(UIImage *) icon_ size];
5579 while (rect.size.width > 32 || rect.size.height > 32) {
5580 rect.size.width /= 2;
5581 rect.size.height /= 2;
5584 rect.origin.x = 25 - rect.size.width / 2;
5585 rect.origin.y = 25 - rect.size.height / 2;
5587 [icon_ drawInRect:rect];
5590 if (badge_ != nil) {
5592 rect.size = [(UIImage *) badge_ size];
5594 rect.size.width /= 2;
5595 rect.size.height /= 2;
5597 rect.origin.x = 36 - rect.size.width / 2;
5598 rect.origin.y = 36 - rect.size.height / 2;
5600 [badge_ drawInRect:rect];
5607 UISetColor(commercial_ ? Purple_ : Black_);
5608 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5609 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5612 UISetColor(commercial_ ? Purplish_ : Gray_);
5613 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5615 if (placard_ != nil)
5616 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5619 - (void) drawContentRect:(CGRect)rect {
5621 [self drawSummaryContentRect:rect];
5623 [self drawNormalContentRect:rect];
5628 /* Section Cell {{{ */
5629 @interface SectionCell : CyteTableViewCell <
5630 CyteTableViewCellDelegate
5632 _H<NSString> basic_;
5633 _H<NSString> section_;
5635 _H<NSString> count_;
5637 _H<UISwitch> switch_;
5641 - (void) setSection:(Section *)section editing:(BOOL)editing;
5645 @implementation SectionCell
5647 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5648 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5649 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5650 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5651 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5653 UIView *content([self contentView]);
5654 CGRect bounds([content bounds]);
5656 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5657 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5658 [content addSubview:content_];
5659 [content_ setBackgroundColor:[UIColor whiteColor]];
5661 [content_ setDelegate:self];
5665 - (void) onSwitch:(id)sender {
5666 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5667 if (metadata == nil) {
5668 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5669 [Sections_ setObject:metadata forKey:basic_];
5672 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5676 - (void) setSection:(Section *)section editing:(BOOL)editing {
5677 if (editing != editing_) {
5679 [switch_ removeFromSuperview];
5681 [self addSubview:switch_];
5690 if (section == nil) {
5691 name_ = UCLocalize("ALL_PACKAGES");
5694 basic_ = [section name];
5695 section_ = [section localized];
5697 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5698 count_ = [NSString stringWithFormat:@"%d", [section count]];
5701 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5704 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5705 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5707 [content_ setNeedsDisplay];
5710 - (void) setFrame:(CGRect)frame {
5711 [super setFrame:frame];
5713 CGRect rect([switch_ frame]);
5714 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5717 - (NSString *) accessibilityLabel {
5721 - (void) drawContentRect:(CGRect)rect {
5722 bool highlighted(highlighted_ && !editing_);
5724 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5729 float width(rect.size.width);
5735 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5737 CGSize size = [count_ sizeWithFont:Font14_];
5741 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5747 /* File Table {{{ */
5748 @interface FileTable : CyteViewController <
5749 UITableViewDataSource,
5752 _transient Database *database_;
5753 _H<Package> package_;
5755 _H<NSMutableArray> files_;
5756 _H<UITableView, 2> list_;
5759 - (id) initWithDatabase:(Database *)database;
5760 - (void) setPackage:(Package *)package;
5764 @implementation FileTable
5766 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5767 return files_ == nil ? 0 : [files_ count];
5770 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5774 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5775 static NSString *reuseIdentifier = @"Cell";
5777 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5779 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5780 [cell setFont:[UIFont systemFontOfSize:16]];
5782 [cell setText:[files_ objectAtIndex:indexPath.row]];
5783 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5788 - (NSURL *) navigationURL {
5789 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5793 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5794 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5795 [list_ setRowHeight:24.0f];
5796 [(UITableView *) list_ setDataSource:self];
5797 [list_ setDelegate:self];
5798 [self setView:list_];
5801 - (void) viewDidLoad {
5802 [super viewDidLoad];
5804 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5807 - (void) releaseSubviews {
5813 [super releaseSubviews];
5816 - (id) initWithDatabase:(Database *)database {
5817 if ((self = [super init]) != nil) {
5818 database_ = database;
5822 - (void) setPackage:(Package *)package {
5826 files_ = [NSMutableArray arrayWithCapacity:32];
5828 if (package != nil) {
5830 name_ = [package id];
5832 if (NSArray *files = [package files])
5833 [files_ addObjectsFromArray:files];
5835 if ([files_ count] != 0) {
5836 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5837 [files_ removeObjectAtIndex:0];
5838 [files_ sortUsingSelector:@selector(compareByPath:)];
5840 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5841 [stack addObject:@"/"];
5843 for (int i(0), e([files_ count]); i != e; ++i) {
5844 NSString *file = [files_ objectAtIndex:i];
5845 while (![file hasPrefix:[stack lastObject]])
5846 [stack removeLastObject];
5847 NSString *directory = [stack lastObject];
5848 [stack addObject:[file stringByAppendingString:@"/"]];
5849 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5850 ([stack count] - 2) * 3, "",
5851 [file substringFromIndex:[directory length]]
5860 - (void) reloadData {
5863 [self setPackage:[database_ packageWithName:name_]];
5868 /* Package Controller {{{ */
5869 @interface CYPackageController : CydiaWebViewController <
5870 UIActionSheetDelegate
5872 _transient Database *database_;
5873 _H<Package> package_;
5876 _H<NSMutableArray> buttons_;
5877 _H<UIBarButtonItem> button_;
5880 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5884 @implementation CYPackageController
5886 - (NSURL *) navigationURL {
5887 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5890 /* XXX: this is not safe at all... localization of /fail/ */
5891 - (void) _clickButtonWithName:(NSString *)name {
5892 if ([name isEqualToString:UCLocalize("CLEAR")])
5893 [delegate_ clearPackage:package_];
5894 else if ([name isEqualToString:UCLocalize("INSTALL")])
5895 [delegate_ installPackage:package_];
5896 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5897 [delegate_ installPackage:package_];
5898 else if ([name isEqualToString:UCLocalize("REMOVE")])
5899 [delegate_ removePackage:package_];
5900 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5901 [delegate_ installPackage:package_];
5902 else _assert(false);
5905 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5906 NSString *context([sheet context]);
5908 if ([context isEqualToString:@"modify"]) {
5909 if (button != [sheet cancelButtonIndex]) {
5910 NSString *buttonName = [buttons_ objectAtIndex:button];
5911 [self _clickButtonWithName:buttonName];
5914 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5918 - (bool) _allowJavaScriptPanel {
5923 - (void) _customButtonClicked {
5924 int count([buttons_ count]);
5929 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5931 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5932 [buttons addObjectsFromArray:buttons_];
5934 UIActionSheet *sheet = [[[UIActionSheet alloc]
5937 cancelButtonTitle:nil
5938 destructiveButtonTitle:nil
5939 otherButtonTitles:nil
5942 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5944 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5945 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5947 [sheet setContext:@"modify"];
5949 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5953 // We don't want to allow non-commercial packages to do custom things to the install button,
5954 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5955 - (void) customButtonClicked {
5957 [super customButtonClicked];
5959 [self _customButtonClicked];
5962 - (void) reloadButtonClicked {
5963 // Don't reload a commerical package by tapping the loading button,
5964 // but if it's not an Install button, we should forward it on.
5965 if (![package_ uninstalled])
5966 [self _customButtonClicked];
5969 - (void) applyLoadingTitle {
5970 // Don't show "Loading" as the title. Ever.
5973 - (UIBarButtonItem *) rightButton {
5978 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5979 if ((self = [super init]) != nil) {
5980 database_ = database;
5981 buttons_ = [NSMutableArray arrayWithCapacity:4];
5982 name_ = name == nil ? @"" : [NSString stringWithString:name];
5983 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5987 - (void) reloadData {
5990 package_ = [database_ packageWithName:name_];
5992 [buttons_ removeAllObjects];
5994 if (package_ != nil) {
5995 [(Package *) package_ parse];
5997 commercial_ = [package_ isCommercial];
5999 if ([package_ mode] != nil)
6000 [buttons_ addObject:UCLocalize("CLEAR")];
6001 if ([package_ source] == nil);
6002 else if ([package_ upgradableAndEssential:NO])
6003 [buttons_ addObject:UCLocalize("UPGRADE")];
6004 else if ([package_ uninstalled])
6005 [buttons_ addObject:UCLocalize("INSTALL")];
6007 [buttons_ addObject:UCLocalize("REINSTALL")];
6008 if (![package_ uninstalled])
6009 [buttons_ addObject:UCLocalize("REMOVE")];
6013 switch ([buttons_ count]) {
6014 case 0: title = nil; break;
6015 case 1: title = [buttons_ objectAtIndex:0]; break;
6016 default: title = UCLocalize("MODIFY"); break;
6019 button_ = [[[UIBarButtonItem alloc]
6021 style:UIBarButtonItemStylePlain
6023 action:@selector(customButtonClicked)
6027 - (bool) isLoading {
6028 return commercial_ ? [super isLoading] : false;
6034 /* Package List Controller {{{ */
6035 @interface PackageListController : CyteViewController <
6036 UITableViewDataSource,
6039 _transient Database *database_;
6041 _H<NSArray> packages_;
6042 _H<NSMutableArray> sections_;
6043 _H<UITableView, 2> list_;
6044 _H<NSMutableArray> index_;
6045 _H<NSMutableDictionary> indices_;
6046 _H<NSString> title_;
6047 unsigned reloading_;
6050 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6051 - (void) setDelegate:(id)delegate;
6052 - (void) resetCursor;
6057 @implementation PackageListController
6059 - (bool) isSummarized {
6063 - (bool) showsSections {
6067 - (void) deselectWithAnimation:(BOOL)animated {
6068 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6071 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6072 CGRect base = [[self view] bounds];
6073 base.size.height -= bounds.size.height;
6074 base.origin = [list_ frame].origin;
6076 [UIView beginAnimations:nil context:NULL];
6077 [UIView setAnimationBeginsFromCurrentState:YES];
6078 [UIView setAnimationCurve:curve];
6079 [UIView setAnimationDuration:duration];
6080 [list_ setFrame:base];
6081 [UIView commitAnimations];
6084 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6085 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6088 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6089 [self resizeForKeyboardBounds:bounds duration:0];
6092 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6093 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6094 *curve = UIViewAnimationCurveEaseInOut;
6096 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6098 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6101 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6104 - (void) keyboardWillShow:(NSNotification *)notification {
6107 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6108 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6110 NSTimeInterval duration;
6111 UIViewAnimationCurve curve;
6112 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6114 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);
6115 UIViewController *base = self;
6116 while ([base parentViewController] != nil)
6117 base = [base parentViewController];
6118 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6119 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6121 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6122 intersection.size.height += CYStatusBarHeight();
6124 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6127 - (void) keyboardWillHide:(NSNotification *)notification {
6128 NSTimeInterval duration;
6129 UIViewAnimationCurve curve;
6130 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6132 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6135 - (void) viewWillAppear:(BOOL)animated {
6136 [super viewWillAppear:animated];
6138 [self resizeForKeyboardBounds:CGRectZero];
6139 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6140 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6143 - (void) viewWillDisappear:(BOOL)animated {
6144 [super viewWillDisappear:animated];
6146 [self resizeForKeyboardBounds:CGRectZero];
6147 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6148 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6151 - (void) viewDidAppear:(BOOL)animated {
6152 [super viewDidAppear:animated];
6153 [self deselectWithAnimation:animated];
6156 - (void) didSelectPackage:(Package *)package {
6157 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6158 [view setDelegate:delegate_];
6159 [[self navigationController] pushViewController:view animated:YES];
6162 #if TryIndexedCollation
6163 + (BOOL) hasIndexedCollation {
6164 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6168 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6169 NSInteger count([sections_ count]);
6170 return count == 0 ? 1 : count;
6173 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6174 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6176 return [[sections_ objectAtIndex:section] name];
6179 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6180 if ([sections_ count] == 0)
6182 return [[sections_ objectAtIndex:section] count];
6185 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6186 @synchronized (database_) {
6187 if ([database_ era] != era_)
6190 Section *section([sections_ objectAtIndex:[path section]]);
6191 NSInteger row([path row]);
6192 Package *package([packages_ objectAtIndex:([section row] + row)]);
6193 return [[package retain] autorelease];
6196 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6197 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6199 cell = [[[PackageCell alloc] init] autorelease];
6201 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6202 [cell setPackage:package asSummary:[self isSummarized]];
6206 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6207 Package *package([self packageAtIndexPath:path]);
6208 package = [database_ packageWithName:[package id]];
6209 [self didSelectPackage:package];
6212 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6213 if (![self showsSections])
6219 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6220 #if TryIndexedCollation
6221 if ([[self class] hasIndexedCollation]) {
6222 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6229 - (void) updateHeight {
6230 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6233 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6234 if ((self = [super init]) != nil) {
6235 database_ = database;
6236 title_ = [title copy];
6237 [[self navigationItem] setTitle:title_];
6242 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6243 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6244 [self setView:view];
6246 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6247 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6248 [view addSubview:list_];
6250 // XXX: is 20 the most optimal number here?
6251 [list_ setSectionIndexMinimumDisplayRowCount:20];
6253 [(UITableView *) list_ setDataSource:self];
6254 [list_ setDelegate:self];
6256 [self updateHeight];
6259 - (void) releaseSubviews {
6267 [super releaseSubviews];
6270 - (void) setDelegate:(id)delegate {
6271 delegate_ = delegate;
6274 - (bool) shouldYield {
6278 - (bool) shouldBlock {
6282 - (NSMutableArray *) _reloadPackages {
6283 @synchronized (database_) {
6284 era_ = [database_ era];
6285 NSArray *packages([database_ packages]);
6287 return [NSMutableArray arrayWithArray:packages];
6290 - (void) _reloadData {
6291 if (reloading_ != 0) {
6299 if ([self shouldYield]) {
6303 if (![self shouldBlock])
6306 hud = [delegate_ addProgressHUD];
6307 [hud setText:UCLocalize("LOADING")];
6311 packages = [self yieldToSelector:@selector(_reloadPackages)];
6314 [delegate_ removeProgressHUD:hud];
6315 } while (reloading_ == 2);
6317 packages = [self _reloadPackages];
6320 @synchronized (database_) {
6321 if (era_ != [database_ era])
6325 packages_ = packages;
6327 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6328 sections_ = [NSMutableArray arrayWithCapacity:16];
6330 Section *section = nil;
6332 #if TryIndexedCollation
6333 if ([[self class] hasIndexedCollation]) {
6334 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6336 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6337 NSArray *titles = [collation sectionIndexTitles];
6340 _profile(PackageTable$reloadData$Section)
6341 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6345 _profile(PackageTable$reloadData$Section$Package)
6346 package = [packages_ objectAtIndex:offset];
6347 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6350 while (secidx < index) {
6353 _profile(PackageTable$reloadData$Section$Allocate)
6354 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6357 _profile(PackageTable$reloadData$Section$Add)
6358 [sections_ addObject:section];
6362 [section addToCount];
6368 index_ = [NSMutableArray arrayWithCapacity:32];
6370 bool sectioned([self showsSections]);
6372 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6373 [sections_ addObject:section];
6376 _profile(PackageTable$reloadData$Section)
6377 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6381 _profile(PackageTable$reloadData$Section$Package)
6382 package = [packages_ objectAtIndex:offset];
6383 index = [package index];
6386 if (sectioned && (section == nil || [section index] != index)) {
6387 _profile(PackageTable$reloadData$Section$Allocate)
6388 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6391 [index_ addObject:[section name]];
6392 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6394 _profile(PackageTable$reloadData$Section$Add)
6395 [sections_ addObject:section];
6399 [section addToCount];
6404 [self updateHeight];
6406 _profile(PackageTable$reloadData$List)
6407 [(UITableView *) list_ setDataSource:self];
6412 - (void) reloadData {
6415 if ([self shouldYield])
6416 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6421 - (void) resetCursor {
6422 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6425 - (void) clearData {
6426 [self updateHeight];
6428 [list_ setDataSource:nil];
6436 /* Filtered Package List Controller {{{ */
6437 @interface FilteredPackageListController : PackageListController {
6440 _H<NSObject> object_;
6443 - (void) setObject:(id)object;
6444 - (void) setObject:(id)object forFilter:(SEL)filter;
6447 - (void) setFilter:(SEL)filter;
6449 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6453 @implementation FilteredPackageListController
6459 - (void) setFilter:(SEL)filter {
6460 @synchronized (self) {
6463 /* XXX: this is an unsafe optimization of doomy hell */
6464 Method method(class_getInstanceMethod([Package class], filter));
6465 _assert(method != NULL);
6466 imp_ = method_getImplementation(method);
6467 _assert(imp_ != NULL);
6470 - (void) setObject:(id)object {
6471 @synchronized (self) {
6475 - (void) setObject:(id)object forFilter:(SEL)filter {
6476 @synchronized (self) {
6477 [self setFilter:filter];
6478 [self setObject:object];
6481 - (NSMutableArray *) _reloadPackages {
6482 @synchronized (database_) {
6483 era_ = [database_ era];
6484 NSArray *packages([database_ packages]);
6486 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6490 _H<NSObject> object;
6492 @synchronized (self) {
6498 _profile(PackageTable$reloadData$Filter)
6499 for (Package *package in packages)
6500 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6501 [filtered addObject:package];
6507 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6508 if ((self = [super initWithDatabase:database title:title]) != nil) {
6509 [self setFilter:filter];
6510 [self setObject:object];
6517 /* Home Controller {{{ */
6518 @interface HomeController : CydiaWebViewController {
6523 @implementation HomeController
6526 if ((self = [super init]) != nil) {
6527 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6532 - (NSURL *) navigationURL {
6533 return [NSURL URLWithString:@"cydia://home"];
6536 - (void) aboutButtonClicked {
6537 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6539 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6540 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6541 [alert setCancelButtonIndex:0];
6544 @"Copyright \u00a9 2008-2011\n"
6547 "Jay Freeman (saurik)\n"
6548 "saurik@saurik.com\n"
6549 "http://www.saurik.com/"
6555 - (UIBarButtonItem *) leftButton {
6556 return [[[UIBarButtonItem alloc]
6557 initWithTitle:UCLocalize("ABOUT")
6558 style:UIBarButtonItemStylePlain
6560 action:@selector(aboutButtonClicked)
6566 /* Manage Controller {{{ */
6567 @interface ManageController : CydiaWebViewController {
6570 - (void) queueStatusDidChange;
6574 @implementation ManageController
6577 if ((self = [super init]) != nil) {
6578 [self setURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6582 - (NSURL *) navigationURL {
6583 return [NSURL URLWithString:@"cydia://manage"];
6586 - (UIBarButtonItem *) leftButton {
6587 return [[[UIBarButtonItem alloc]
6588 initWithTitle:UCLocalize("SETTINGS")
6589 style:UIBarButtonItemStylePlain
6591 action:@selector(settingsButtonClicked)
6595 - (void) settingsButtonClicked {
6596 [delegate_ showSettings];
6599 - (void) queueButtonClicked {
6603 - (UIBarButtonItem *) rightButton {
6604 return Queuing_ ? [[[UIBarButtonItem alloc]
6605 initWithTitle:UCLocalize("QUEUE")
6606 style:UIBarButtonItemStyleDone
6608 action:@selector(queueButtonClicked)
6609 ] autorelease] : nil;
6612 - (void) queueStatusDidChange {
6613 [self applyRightButton];
6616 - (bool) isLoading {
6617 return !Queuing_ && [super isLoading];
6623 /* Refresh Bar {{{ */
6624 @interface RefreshBar : UINavigationBar {
6625 _H<UIProgressIndicator> indicator_;
6626 _H<UITextLabel> prompt_;
6627 _H<UIProgressBar> progress_;
6628 _H<UINavigationButton> cancel_;
6633 @implementation RefreshBar
6635 - (void) positionViews {
6636 CGRect frame = [cancel_ frame];
6637 frame.size = [cancel_ sizeThatFits:frame.size];
6638 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6639 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6640 [cancel_ setFrame:frame];
6642 CGSize prgsize = {75, 100};
6644 [self frame].size.width - prgsize.width - 10,
6645 ([self frame].size.height - prgsize.height) / 2
6647 [progress_ setFrame:prgrect];
6649 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6650 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6651 CGRect indrect = {{indoffset, indoffset}, indsize};
6652 [indicator_ setFrame:indrect];
6654 CGSize prmsize = {215, indsize.height + 4};
6656 indoffset * 2 + indsize.width,
6657 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6659 [prompt_ setFrame:prmrect];
6662 - (void) setFrame:(CGRect)frame {
6663 [super setFrame:frame];
6664 [self positionViews];
6667 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6668 if ((self = [super initWithFrame:frame]) != nil) {
6669 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6671 [self setBarStyle:UIBarStyleBlack];
6673 UIBarStyle barstyle([self _barStyle:NO]);
6674 bool ugly(barstyle == UIBarStyleDefault);
6676 UIProgressIndicatorStyle style = ugly ?
6677 UIProgressIndicatorStyleMediumBrown :
6678 UIProgressIndicatorStyleMediumWhite;
6680 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6681 [(UIProgressIndicator *) indicator_ setStyle:style];
6682 [indicator_ startAnimation];
6683 [self addSubview:indicator_];
6685 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6686 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6687 [prompt_ setBackgroundColor:[UIColor clearColor]];
6688 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6689 [self addSubview:prompt_];
6691 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6692 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6693 [(UIProgressBar *) progress_ setStyle:0];
6694 [self addSubview:progress_];
6696 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6697 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6698 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6699 [cancel_ setBarStyle:barstyle];
6701 [self positionViews];
6705 - (void) setCancellable:(bool)cancellable {
6707 [self addSubview:cancel_];
6709 [cancel_ removeFromSuperview];
6713 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6714 [progress_ setProgress:0];
6718 [self setCancellable:NO];
6721 - (void) setPrompt:(NSString *)prompt {
6722 [prompt_ setText:prompt];
6725 - (void) setProgress:(float)progress {
6726 [progress_ setProgress:progress];
6732 /* Cydia Navigation Controller Interface {{{ */
6733 @interface UINavigationController (Cydia)
6735 - (NSArray *) navigationURLCollection;
6736 - (void) unloadData;
6741 /* Cydia Tab Bar Controller {{{ */
6742 @interface CYTabBarController : UITabBarController <
6743 UITabBarControllerDelegate,
6746 _transient Database *database_;
6747 _H<RefreshBar, 1> refreshbar_;
6751 // XXX: ok, "updatedelegate_"?...
6752 _transient NSObject<CydiaDelegate> *updatedelegate_;
6754 _H<UIViewController> remembered_;
6755 _transient UIViewController *transient_;
6758 - (NSArray *) navigationURLCollection;
6759 - (void) dropBar:(BOOL)animated;
6760 - (void) beginUpdate;
6761 - (void) raiseBar:(BOOL)animated;
6763 - (void) unloadData;
6767 @implementation CYTabBarController
6769 - (void) didReceiveMemoryWarning {
6770 [super didReceiveMemoryWarning];
6772 // presenting a UINavigationController on 2.x does not update its transitionView
6773 // it thereby will not allow its topViewController to be unloaded by memory pressure
6774 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6775 UIViewController *selected([self selectedViewController]);
6776 for (UINavigationController *controller in [self viewControllers])
6777 if (controller != selected)
6778 if (UIViewController *top = [controller topViewController])
6783 - (void) setUnselectedViewController:(UIViewController *)transient {
6784 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6785 if (transient != nil) {
6786 [[[self viewControllers] objectAtIndex:0] pushViewController:transient animated:YES];
6787 [self setSelectedIndex:0];
6791 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
6792 [navigation setViewControllers:[NSArray arrayWithObject:transient]];
6793 transient = navigation;
6795 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6796 if (transient != nil) {
6797 if (transient_ == nil)
6798 remembered_ = [controllers objectAtIndex:0];
6799 transient_ = transient;
6800 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6801 [controllers replaceObjectAtIndex:0 withObject:transient_];
6802 [self setSelectedIndex:0];
6803 [self setViewControllers:controllers];
6804 [self concealTabBarSelection];
6805 } else if (remembered_ != nil) {
6806 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6807 transient_ = transient;
6808 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6810 [self setViewControllers:controllers];
6811 [self revealTabBarSelection];
6815 - (UIViewController *) unselectedViewController {
6819 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6820 if ([self unselectedViewController])
6821 [self setUnselectedViewController:nil];
6823 // presenting a UINavigationController on 2.x does not update its transitionView
6824 // if this view was unloaded, the tranitionView may currently be presenting nothing
6825 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
6826 UINavigationController *navigation((UINavigationController *) viewController);
6827 [navigation pushViewController:[[[UIViewController alloc] init] autorelease] animated:NO];
6828 [navigation popViewControllerAnimated:NO];
6832 - (NSArray *) navigationURLCollection {
6833 NSMutableArray *items([NSMutableArray array]);
6835 // XXX: Should this deal with transient view controllers?
6836 for (id navigation in [self viewControllers]) {
6837 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6839 [items addObject:stack];
6845 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6846 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6847 [self setUnselectedViewController:nil];
6849 [super dismissModalViewControllerAnimated:YES];
6852 - (void) unloadData {
6855 for (UINavigationController *controller in [self viewControllers])
6856 [controller unloadData];
6858 if (UIViewController *selected = [self selectedViewController])
6859 [selected reloadData];
6861 if (UIViewController *unselected = [self unselectedViewController]) {
6862 [unselected unloadData];
6863 [unselected reloadData];
6868 [[NSNotificationCenter defaultCenter] removeObserver:self];
6873 - (id) initWithDatabase:(Database *)database {
6874 if ((self = [super init]) != nil) {
6875 database_ = database;
6876 [self setDelegate:self];
6878 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6879 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6881 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6885 - (void) setUpdate:(NSDate *)date {
6889 - (void) beginUpdate {
6890 [(RefreshBar *) refreshbar_ start];
6893 [updatedelegate_ retainNetworkActivityIndicator];
6897 detachNewThreadSelector:@selector(performUpdate)
6903 - (void) performUpdate {
6904 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6907 status.setDelegate(self);
6908 [database_ updateWithStatus:status];
6911 performSelectorOnMainThread:@selector(completeUpdate)
6919 - (void) stopUpdateWithSelector:(SEL)selector {
6921 [updatedelegate_ releaseNetworkActivityIndicator];
6923 [self raiseBar:YES];
6926 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6929 - (void) completeUpdate {
6932 [self stopUpdateWithSelector:@selector(reloadData)];
6935 - (void) cancelUpdate {
6936 [self stopUpdateWithSelector:@selector(updateData)];
6939 - (void) cancelPressed {
6940 [self cancelUpdate];
6947 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6948 [refreshbar_ setPrompt:[event compoundMessage]];
6951 - (bool) isProgressCancelled {
6955 - (void) setProgressCancellable:(NSNumber *)cancellable {
6956 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6959 - (void) setProgressPercent:(NSNumber *)percent {
6960 [refreshbar_ setProgress:[percent floatValue]];
6963 - (void) setProgressStatus:(NSDictionary *)status {
6965 [self setProgressPercent:[status objectForKey:@"Percent"]];
6968 - (void) setUpdateDelegate:(id)delegate {
6969 updatedelegate_ = delegate;
6972 - (UIView *) transitionView {
6973 if ([self respondsToSelector:@selector(_transitionView)])
6974 return [self _transitionView];
6976 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6979 - (void) dropBar:(BOOL)animated {
6984 UIView *transition([self transitionView]);
6985 [[self view] addSubview:refreshbar_];
6987 CGRect barframe([refreshbar_ frame]);
6989 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6990 barframe.origin.y = CYStatusBarHeight();
6992 barframe.origin.y = 0;
6994 [refreshbar_ setFrame:barframe];
6997 [UIView beginAnimations:nil context:NULL];
6999 CGRect viewframe = [transition frame];
7000 viewframe.origin.y += barframe.size.height;
7001 viewframe.size.height -= barframe.size.height;
7002 [transition setFrame:viewframe];
7005 [UIView commitAnimations];
7007 // Ensure bar has the proper width for our view, it might have changed
7008 barframe.size.width = viewframe.size.width;
7009 [refreshbar_ setFrame:barframe];
7012 - (void) raiseBar:(BOOL)animated {
7017 UIView *transition([self transitionView]);
7018 [refreshbar_ removeFromSuperview];
7020 CGRect barframe([refreshbar_ frame]);
7023 [UIView beginAnimations:nil context:NULL];
7025 CGRect viewframe = [transition frame];
7026 viewframe.origin.y -= barframe.size.height;
7027 viewframe.size.height += barframe.size.height;
7028 [transition setFrame:viewframe];
7031 [UIView commitAnimations];
7034 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7035 bool dropped(dropped_);
7040 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7046 - (void) statusBarFrameChanged:(NSNotification *)notification {
7056 /* Cydia Navigation Controller Implementation {{{ */
7057 @implementation UINavigationController (Cydia)
7059 - (NSArray *) navigationURLCollection {
7060 NSMutableArray *stack([NSMutableArray array]);
7062 for (CyteViewController *controller in [self viewControllers]) {
7063 NSString *url = [[controller navigationURL] absoluteString];
7065 [stack addObject:url];
7071 - (void) reloadData {
7074 UIViewController *visible([self visibleViewController]);
7076 [visible reloadData];
7078 // on the iPad, this view controller is ALSO visible. :(
7080 if (UIViewController *top = [self topViewController])
7085 - (void) unloadData {
7086 for (CyteViewController *page in [self viewControllers])
7095 /* Cydia:// Protocol {{{ */
7096 @interface CydiaURLProtocol : NSURLProtocol {
7101 @implementation CydiaURLProtocol
7103 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7104 NSURL *url([request URL]);
7108 NSString *scheme([[url scheme] lowercaseString]);
7109 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7111 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7117 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7121 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7122 id<NSURLProtocolClient> client([self client]);
7124 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7126 NSData *data(UIImagePNGRepresentation(icon));
7128 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7129 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7130 [client URLProtocol:self didLoadData:data];
7131 [client URLProtocolDidFinishLoading:self];
7135 - (void) startLoading {
7136 id<NSURLProtocolClient> client([self client]);
7137 NSURLRequest *request([self request]);
7139 NSURL *url([request URL]);
7140 NSString *href([url absoluteString]);
7141 NSString *scheme([[url scheme] lowercaseString]);
7145 if ([scheme isEqualToString:@"cydia"])
7146 path = [href substringFromIndex:8];
7147 else if ([scheme isEqualToString:@"about"])
7148 path = [href substringFromIndex:12];
7149 else _assert(false);
7151 NSRange slash([path rangeOfString:@"/"]);
7154 if (slash.location == NSNotFound) {
7158 command = [path substringToIndex:slash.location];
7159 path = [path substringFromIndex:(slash.location + 1)];
7162 Database *database([Database sharedInstance]);
7164 if ([command isEqualToString:@"package-icon"]) {
7167 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7168 Package *package([database packageWithName:path]);
7172 UIImage *icon([package icon]);
7173 [self _returnPNGWithImage:icon forRequest:request];
7174 } else if ([command isEqualToString:@"uikit-image"]) {
7177 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7178 UIImage *icon(_UIImageWithName(path));
7179 [self _returnPNGWithImage:icon forRequest:request];
7180 } else if ([command isEqualToString:@"section-icon"]) {
7183 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7184 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7186 icon = [UIImage applicationImageNamed:@"unknown.png"];
7187 [self _returnPNGWithImage:icon forRequest:request];
7189 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7193 - (void) stopLoading {
7199 /* Section Controller {{{ */
7200 @interface SectionController : FilteredPackageListController {
7201 _H<NSString> section_;
7204 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7208 @implementation SectionController
7210 - (NSURL *) navigationURL {
7211 NSString *name = section_;
7215 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", [name stringByAddingPercentEscapesIncludingReserved]]];
7218 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7221 title = UCLocalize("ALL_PACKAGES");
7222 else if (![name isEqual:@""])
7223 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7225 title = UCLocalize("NO_SECTION");
7227 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7234 /* Sections Controller {{{ */
7235 @interface SectionsController : CyteViewController <
7236 UITableViewDataSource,
7239 _transient Database *database_;
7240 _H<NSMutableArray> sections_;
7241 _H<NSMutableArray> filtered_;
7242 _H<UITableView, 2> list_;
7245 - (id) initWithDatabase:(Database *)database;
7246 - (void) editButtonClicked;
7250 @implementation SectionsController
7252 - (NSURL *) navigationURL {
7253 return [NSURL URLWithString:@"cydia://sections"];
7256 - (void) updateNavigationItem {
7257 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7258 if ([sections_ count] == 0) {
7259 [[self navigationItem] setRightBarButtonItem:nil];
7261 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7262 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7264 action:@selector(editButtonClicked)
7265 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7269 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7270 [super setEditing:editing animated:animated];
7275 [delegate_ updateData];
7277 [self updateNavigationItem];
7280 - (void) viewDidAppear:(BOOL)animated {
7281 [super viewDidAppear:animated];
7282 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7285 - (void) viewWillDisappear:(BOOL)animated {
7286 [super viewWillDisappear:animated];
7287 if ([self isEditing]) [self setEditing:NO];
7290 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7291 Section *section = nil;
7292 int index = [indexPath row];
7293 if (![self isEditing]) {
7296 section = [filtered_ objectAtIndex:index];
7298 section = [sections_ objectAtIndex:index];
7303 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7304 if ([self isEditing])
7305 return [sections_ count];
7307 return [filtered_ count] + 1;
7310 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7314 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7315 static NSString *reuseIdentifier = @"SectionCell";
7317 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7319 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7321 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7326 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7327 if ([self isEditing])
7330 Section *section = [self sectionAtIndexPath:indexPath];
7332 SectionController *controller = [[[SectionController alloc]
7333 initWithDatabase:database_
7334 section:[section name]
7336 [controller setDelegate:delegate_];
7338 [[self navigationController] pushViewController:controller animated:YES];
7342 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7343 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7344 [list_ setRowHeight:45.0f];
7345 [(UITableView *) list_ setDataSource:self];
7346 [list_ setDelegate:self];
7347 [self setView:list_];
7350 - (void) viewDidLoad {
7351 [super viewDidLoad];
7353 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7356 - (void) releaseSubviews {
7362 [super releaseSubviews];
7365 - (id) initWithDatabase:(Database *)database {
7366 if ((self = [super init]) != nil) {
7367 database_ = database;
7371 - (void) reloadData {
7374 NSArray *packages = [database_ packages];
7376 sections_ = [NSMutableArray arrayWithCapacity:16];
7377 filtered_ = [NSMutableArray arrayWithCapacity:16];
7379 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7382 for (Package *package in packages) {
7383 NSString *name([package section]);
7384 NSString *key(name == nil ? @"" : name);
7388 _profile(SectionsView$reloadData$Section)
7389 section = [sections objectForKey:key];
7390 if (section == nil) {
7391 _profile(SectionsView$reloadData$Section$Allocate)
7392 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7393 [sections setObject:section forKey:key];
7398 [section addToCount];
7400 _profile(SectionsView$reloadData$Filter)
7401 if (![package valid] || ![package visible])
7409 [sections_ addObjectsFromArray:[sections allValues]];
7411 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7413 for (Section *section in (id) sections_) {
7414 size_t count([section row]);
7418 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7419 [section setCount:count];
7420 [filtered_ addObject:section];
7423 [self updateNavigationItem];
7428 - (void) editButtonClicked {
7429 [self setEditing:![self isEditing] animated:YES];
7435 /* Changes Controller {{{ */
7436 @interface ChangesController : CyteViewController <
7437 UITableViewDataSource,
7440 _transient Database *database_;
7442 _H<NSArray> packages_;
7443 _H<NSMutableArray> sections_;
7444 _H<UITableView, 2> list_;
7445 _H<CyteWebView, 1> dickbar_;
7447 _H<IndirectDelegate, 1> indirect_;
7448 _H<CydiaObject> cydia_;
7451 - (id) initWithDatabase:(Database *)database;
7455 @implementation ChangesController
7457 - (NSURL *) navigationURL {
7458 return [NSURL URLWithString:@"cydia://changes"];
7461 - (void) viewDidAppear:(BOOL)animated {
7462 [super viewDidAppear:animated];
7463 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7466 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7467 NSInteger count([sections_ count]);
7468 return count == 0 ? 1 : count;
7471 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7472 if ([sections_ count] == 0)
7474 return [[sections_ objectAtIndex:section] name];
7477 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7478 if ([sections_ count] == 0)
7480 return [[sections_ objectAtIndex:section] count];
7483 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7484 @synchronized (database_) {
7485 if ([database_ era] != era_)
7488 NSUInteger sectionIndex([path section]);
7489 if (sectionIndex >= [sections_ count])
7491 Section *section([sections_ objectAtIndex:sectionIndex]);
7492 NSInteger row([path row]);
7493 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7496 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7497 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7499 cell = [[[PackageCell alloc] init] autorelease];
7501 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7502 [cell setPackage:package asSummary:false];
7506 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7507 Package *package([self packageAtIndexPath:path]);
7508 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7509 [view setDelegate:delegate_];
7510 [[self navigationController] pushViewController:view animated:YES];
7514 - (void) refreshButtonClicked {
7515 [delegate_ beginUpdate];
7516 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7519 - (void) upgradeButtonClicked {
7520 [delegate_ distUpgrade];
7521 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7525 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7526 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7527 [self setView:view];
7529 list_ = [[[UITableView alloc] initWithFrame:[view bounds] style:UITableViewStylePlain] autorelease];
7530 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7531 [list_ setRowHeight:73];
7532 [(UITableView *) list_ setDataSource:self];
7533 [list_ setDelegate:self];
7534 [view addSubview:list_];
7536 if (AprilFools_ && kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) {
7537 CGRect dickframe([view bounds]);
7538 dickframe.size.height = 44;
7540 dickbar_ = [[[CyteWebView alloc] initWithFrame:dickframe] autorelease];
7541 [dickbar_ setDelegate:self];
7542 [view addSubview:dickbar_];
7544 [dickbar_ setBackgroundColor:[UIColor clearColor]];
7545 [dickbar_ setScalesPageToFit:YES];
7547 UIWebDocumentView *document([dickbar_ _documentView]);
7548 [document setBackgroundColor:[UIColor clearColor]];
7549 [document setDrawsBackground:NO];
7551 WebView *webview([document webView]);
7552 [webview setShouldUpdateWhileOffscreen:NO];
7554 UIScrollView *scroller([dickbar_ scrollView]);
7555 [scroller setScrollingEnabled:NO];
7556 [scroller setFixedBackgroundPattern:YES];
7557 [scroller setBackgroundColor:[UIColor clearColor]];
7559 WebPreferences *preferences([webview preferences]);
7560 [preferences setCacheModel:WebCacheModelDocumentBrowser];
7561 [preferences setJavaScriptCanOpenWindowsAutomatically:YES];
7562 [preferences setOfflineWebApplicationCacheEnabled:YES];
7564 [dickbar_ loadRequest:[NSURLRequest
7565 requestWithURL:[Diversion divertURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/dickbar/", UI_]]]
7566 cachePolicy:NSURLRequestUseProtocolCachePolicy
7570 UIEdgeInsets inset = {44, 0, 0, 0};
7571 [list_ setContentInset:inset];
7573 [dickbar_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
7577 - (void) webView:(WebView *)view decidePolicyForNewWindowAction:(NSDictionary *)action request:(NSURLRequest *)request newFrameName:(NSString *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {
7578 NSURL *url([request URL]);
7582 if ([frame isEqualToString:@"_open"])
7583 [delegate_ openURL:url];
7585 CyteViewController *controller([delegate_ pageForURL:url forExternal:NO] ?: [[[CydiaWebViewController alloc] initWithRequest:request] autorelease]);
7586 [controller setDelegate:delegate_];
7587 [[self navigationController] pushViewController:controller animated:YES];
7593 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
7594 return [CydiaWebViewController requestWithHeaders:request];
7597 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7598 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
7601 - (void) setDelegate:(id)delegate {
7602 [super setDelegate:delegate];
7603 [cydia_ setDelegate:delegate];
7606 - (void) viewDidLoad {
7607 [super viewDidLoad];
7609 [[self navigationItem] setTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES"))];
7612 - (void) releaseSubviews {
7619 [super releaseSubviews];
7622 - (id) initWithDatabase:(Database *)database {
7623 if ((self = [super init]) != nil) {
7624 indirect_ = [[[IndirectDelegate alloc] initWithDelegate:self] autorelease];
7625 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
7626 database_ = database;
7630 - (NSMutableArray *) _reloadPackages {
7631 @synchronized (database_) {
7632 era_ = [database_ era];
7633 NSArray *packages([database_ packages]);
7635 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7638 _profile(ChangesController$_reloadPackages$Filter)
7639 for (Package *package in packages)
7640 if ([package upgradableAndEssential:YES] || [package visible])
7641 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7644 _profile(ChangesController$_reloadPackages$radixSort)
7645 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7652 - (void) _reloadData {
7657 UIProgressHUD *hud([delegate_ addProgressHUD]);
7658 [hud setText:UCLocalize("LOADING")];
7659 //NSLog(@"HUD:%@::%@", delegate_, hud);
7660 packages = [self yieldToSelector:@selector(_reloadPackages)];
7661 [delegate_ removeProgressHUD:hud];
7663 packages = [self _reloadPackages];
7666 @synchronized (database_) {
7667 if (era_ != [database_ era])
7670 packages_ = packages;
7671 sections_ = [NSMutableArray arrayWithCapacity:16];
7673 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7674 Section *ignored = nil;
7675 Section *section = nil;
7679 bool unseens = false;
7681 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7683 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7684 Package *package = [packages_ objectAtIndex:offset];
7686 BOOL uae = [package upgradableAndEssential:YES];
7690 time_t seen([package seen]);
7692 if (section == nil || last != seen) {
7696 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7699 _profile(ChangesController$reloadData$Allocate)
7700 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7701 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7702 [sections_ addObject:section];
7706 [section addToCount];
7707 } else if ([package ignored]) {
7708 if (ignored == nil) {
7709 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7711 [ignored addToCount];
7714 [upgradable addToCount];
7719 CFRelease(formatter);
7722 Section *last = [sections_ lastObject];
7723 size_t count = [last count];
7724 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7725 [sections_ removeLastObject];
7728 if ([ignored count] != 0)
7729 [sections_ insertObject:ignored atIndex:0];
7731 [sections_ insertObject:upgradable atIndex:0];
7735 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7736 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7737 style:UIBarButtonItemStylePlain
7739 action:@selector(upgradeButtonClicked)
7740 ] autorelease]) animated:YES];
7742 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7743 initWithTitle:UCLocalize("REFRESH")
7744 style:UIBarButtonItemStylePlain
7746 action:@selector(refreshButtonClicked)
7747 ] autorelease]) animated:YES];
7752 - (void) reloadData {
7754 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7759 /* Search Controller {{{ */
7760 @interface SearchController : FilteredPackageListController <
7763 _H<UISearchBar, 1> search_;
7767 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7768 - (void) reloadData;
7772 @implementation SearchController
7774 - (NSURL *) navigationURL {
7775 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7776 return [NSURL URLWithString:@"cydia://search"];
7778 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7781 - (void) useSearch {
7782 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7787 - (void) viewWillAppear:(BOOL)animated {
7788 [super viewWillAppear:animated];
7790 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7794 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7795 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7800 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7801 [search_ resignFirstResponder];
7805 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7806 [search_ setText:@""];
7807 [self searchBarButtonClicked:searchBar];
7810 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7811 [self searchBarButtonClicked:searchBar];
7814 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7815 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7819 - (bool) shouldYield {
7823 - (bool) shouldBlock {
7824 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7827 - (bool) isSummarized {
7828 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7831 - (bool) showsSections {
7835 - (NSMutableArray *) _reloadPackages {
7836 NSMutableArray *packages([super _reloadPackages]);
7837 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7838 [packages radixSortUsingSelector:@selector(rank)];
7842 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7843 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7844 search_ = [[[UISearchBar alloc] init] autorelease];
7845 [search_ setDelegate:self];
7848 [search_ setText:query];
7852 - (void) viewDidAppear:(BOOL)animated {
7853 [super viewDidAppear:animated];
7855 if (!searchloaded_) {
7856 searchloaded_ = YES;
7857 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7858 [search_ layoutSubviews];
7859 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7861 UITextField *textField;
7862 if ([search_ respondsToSelector:@selector(searchField)])
7863 textField = [search_ searchField];
7865 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7867 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7868 [textField setEnablesReturnKeyAutomatically:NO];
7869 [[self navigationItem] setTitleView:textField];
7873 - (void) reloadData {
7874 id object([search_ text]);
7875 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7876 object = [object componentsSeparatedByString:@" "];
7878 [self setObject:object];
7884 - (void) didSelectPackage:(Package *)package {
7885 [search_ resignFirstResponder];
7886 [super didSelectPackage:package];
7891 /* Package Settings Controller {{{ */
7892 @interface PackageSettingsController : CyteViewController <
7893 UITableViewDataSource,
7896 _transient Database *database_;
7898 _H<Package> package_;
7899 _H<UITableView, 2> table_;
7900 _H<UISwitch> subscribedSwitch_;
7901 _H<UISwitch> ignoredSwitch_;
7902 _H<UITableViewCell> subscribedCell_;
7903 _H<UITableViewCell> ignoredCell_;
7906 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7910 @implementation PackageSettingsController
7912 - (NSURL *) navigationURL {
7913 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7916 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7917 if (package_ == nil)
7920 if ([package_ installed] == nil)
7926 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7927 if (package_ == nil)
7930 // both sections contain just one item right now.
7934 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7938 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7940 return UCLocalize("SHOW_ALL_CHANGES_EX");
7942 return UCLocalize("IGNORE_UPGRADES_EX");
7945 - (void) onSubscribed:(id)control {
7946 bool value([control isOn]);
7947 if (package_ == nil)
7949 if ([package_ setSubscribed:value])
7950 [delegate_ updateData];
7953 - (void) _updateIgnored {
7954 const char *package([name_ UTF8String]);
7955 bool on([ignoredSwitch_ isOn]);
7957 pid_t pid(ExecFork());
7959 FILE *dpkg(popen("dpkg --set-selections", "w"));
7960 fwrite(package, strlen(package), 1, dpkg);
7963 fwrite(" hold\n", 6, 1, dpkg);
7965 fwrite(" install\n", 9, 1, dpkg);
7976 - (void) onIgnored:(id)control {
7977 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7978 [invocation setTarget:self];
7979 [invocation setSelector:@selector(_updateIgnored)];
7981 [delegate_ reloadDataWithInvocation:invocation];
7984 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7985 if (package_ == nil)
7988 switch ([indexPath section]) {
7989 case 0: return subscribedCell_;
7990 case 1: return ignoredCell_;
7999 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8000 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8001 [self setView:view];
8003 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8004 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8005 [(UITableView *) table_ setDataSource:self];
8006 [table_ setDelegate:self];
8007 [view addSubview:table_];
8009 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8010 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8011 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8013 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8014 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8015 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8017 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8018 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8019 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8020 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8022 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8023 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8024 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8025 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8028 - (void) viewDidLoad {
8029 [super viewDidLoad];
8031 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8034 - (void) releaseSubviews {
8036 subscribedCell_ = nil;
8038 ignoredSwitch_ = nil;
8039 subscribedSwitch_ = nil;
8041 [super releaseSubviews];
8044 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8045 if ((self = [super init]) != nil) {
8046 database_ = database;
8051 - (void) reloadData {
8054 package_ = [database_ packageWithName:name_];
8056 if (package_ != nil) {
8057 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8058 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8059 } // XXX: what now, G?
8061 [table_ reloadData];
8067 /* Installed Controller {{{ */
8068 @interface InstalledController : FilteredPackageListController {
8072 - (id) initWithDatabase:(Database *)database;
8074 - (void) updateRoleButton;
8075 - (void) queueStatusDidChange;
8079 @implementation InstalledController
8081 - (NSURL *) navigationURL {
8082 return [NSURL URLWithString:@"cydia://installed"];
8085 - (id) initWithDatabase:(Database *)database {
8086 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
8087 [self updateRoleButton];
8088 [self queueStatusDidChange];
8093 - (void) queueButtonClicked {
8098 - (void) queueStatusDidChange {
8102 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8103 initWithTitle:UCLocalize("QUEUE")
8104 style:UIBarButtonItemStyleDone
8106 action:@selector(queueButtonClicked)
8109 [[self navigationItem] setLeftBarButtonItem:nil];
8115 - (void) updateRoleButton {
8116 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
8117 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8118 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8119 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8121 action:@selector(roleButtonClicked)
8125 - (void) roleButtonClicked {
8126 [self setObject:[NSNumber numberWithBool:expert_]];
8130 [self updateRoleButton];
8136 /* Source Cell {{{ */
8137 @interface SourceCell : CyteTableViewCell <
8138 CyteTableViewCellDelegate
8142 _H<NSString> origin_;
8143 _H<NSString> label_;
8146 - (void) setSource:(Source *)source;
8150 @implementation SourceCell
8152 - (void) _setImage:(NSArray *)data {
8153 if ([url_ isEqual:[data objectAtIndex:0]]) {
8154 icon_ = [data objectAtIndex:1];
8155 [content_ setNeedsDisplay];
8159 - (void) _setSource:(NSURL *) url {
8160 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8162 if (NSData *data = [NSURLConnection
8163 sendSynchronousRequest:[NSURLRequest
8165 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8169 returningResponse:NULL
8172 if (UIImage *image = [UIImage imageWithData:data])
8173 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8178 - (void) setSource:(Source *)source {
8179 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8181 origin_ = [source name];
8182 label_ = [source rooturi];
8184 [content_ setNeedsDisplay];
8186 url_ = [source iconURL];
8187 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8190 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8191 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8192 UIView *content([self contentView]);
8193 CGRect bounds([content bounds]);
8195 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8196 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8197 [content_ setBackgroundColor:[UIColor whiteColor]];
8198 [content addSubview:content_];
8200 [content_ setDelegate:self];
8201 [content_ setOpaque:YES];
8203 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8207 - (NSString *) accessibilityLabel {
8211 - (void) drawContentRect:(CGRect)rect {
8212 bool highlighted(highlighted_);
8213 float width(rect.size.width);
8217 rect.size = [(UIImage *) icon_ size];
8219 while (rect.size.width > 32 || rect.size.height > 32) {
8220 rect.size.width /= 2;
8221 rect.size.height /= 2;
8224 rect.origin.x = 25 - rect.size.width / 2;
8225 rect.origin.y = 25 - rect.size.height / 2;
8227 [icon_ drawInRect:rect];
8235 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 65) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8239 [label_ drawAtPoint:CGPointMake(48, 29) forWidth:(width - 65) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8244 /* Source Controller {{{ */
8245 @interface SourceController : FilteredPackageListController {
8246 _transient Source *source_;
8250 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8254 @implementation SourceController
8256 - (NSURL *) navigationURL {
8257 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8260 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8261 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8263 key_ = [source key];
8267 - (void) reloadData {
8268 source_ = [database_ sourceWithKey:key_];
8269 key_ = [source_ key];
8270 [self setObject:source_];
8272 [[self navigationItem] setTitle:[source_ label]];
8279 /* Sources Controller {{{ */
8280 @interface SourcesController : CyteViewController <
8281 UITableViewDataSource,
8284 _transient Database *database_;
8287 _H<UITableView, 2> list_;
8288 _H<NSMutableArray> sources_;
8292 _H<UIProgressHUD> hud_;
8295 //NSURLConnection *installer_;
8296 NSURLConnection *trivial_;
8297 NSURLConnection *trivial_bz2_;
8298 NSURLConnection *trivial_gz_;
8299 //NSURLConnection *automatic_;
8304 - (id) initWithDatabase:(Database *)database;
8305 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8309 @implementation SourcesController
8311 - (void) _releaseConnection:(NSURLConnection *)connection {
8312 if (connection != nil) {
8313 [connection cancel];
8314 //[connection setDelegate:nil];
8315 [connection release];
8320 //[self _releaseConnection:installer_];
8321 [self _releaseConnection:trivial_];
8322 [self _releaseConnection:trivial_gz_];
8323 [self _releaseConnection:trivial_bz2_];
8324 //[self _releaseConnection:automatic_];
8329 - (NSURL *) navigationURL {
8330 return [NSURL URLWithString:@"cydia://sources"];
8333 - (void) viewDidAppear:(BOOL)animated {
8334 [super viewDidAppear:animated];
8335 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8338 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8342 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8346 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8347 return [sources_ count];
8350 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8351 @synchronized (database_) {
8352 if ([database_ era] != era_)
8355 return [sources_ objectAtIndex:[indexPath row]];
8358 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8359 static NSString *cellIdentifier = @"SourceCell";
8361 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8362 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8363 [cell setSource:[self sourceAtIndexPath:indexPath]];
8364 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8369 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8370 Source *source = [self sourceAtIndexPath:indexPath];
8372 SourceController *controller = [[[SourceController alloc]
8373 initWithDatabase:database_
8377 [controller setDelegate:delegate_];
8379 [[self navigationController] pushViewController:controller animated:YES];
8382 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8383 Source *source = [self sourceAtIndexPath:indexPath];
8384 return [source record] != nil;
8387 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8388 if (editingStyle == UITableViewCellEditingStyleDelete) {
8389 Source *source = [self sourceAtIndexPath:indexPath];
8390 [Sources_ removeObjectForKey:[source key]];
8391 [delegate_ syncData];
8396 [delegate_ addTrivialSource:href_];
8399 [delegate_ syncData];
8402 - (NSString *) getWarning {
8403 NSString *href(href_);
8404 NSRange colon([href rangeOfString:@"://"]);
8405 if (colon.location != NSNotFound)
8406 href = [href substringFromIndex:(colon.location + 3)];
8407 href = [href stringByAddingPercentEscapes];
8408 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8410 NSURL *url([NSURL URLWithString:href]);
8412 NSStringEncoding encoding;
8413 NSError *error(nil);
8415 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8416 return [warning length] == 0 ? nil : warning;
8420 - (void) _endConnection:(NSURLConnection *)connection {
8421 // XXX: the memory management in this method is horribly awkward
8423 NSURLConnection **field = NULL;
8424 if (connection == trivial_)
8426 else if (connection == trivial_bz2_)
8427 field = &trivial_bz2_;
8428 else if (connection == trivial_gz_)
8429 field = &trivial_gz_;
8430 _assert(field != NULL);
8431 [connection release];
8436 trivial_bz2_ == nil &&
8439 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8441 [delegate_ releaseNetworkActivityIndicator];
8443 [delegate_ removeProgressHUD:hud_];
8447 if (warning != nil) {
8448 UIAlertView *alert = [[[UIAlertView alloc]
8449 initWithTitle:UCLocalize("SOURCE_WARNING")
8452 cancelButtonTitle:UCLocalize("CANCEL")
8454 UCLocalize("ADD_ANYWAY"),
8458 [alert setContext:@"warning"];
8459 [alert setNumberOfRows:1];
8462 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8468 } else if (error_ != nil) {
8469 UIAlertView *alert = [[[UIAlertView alloc]
8470 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8471 message:[error_ localizedDescription]
8473 cancelButtonTitle:UCLocalize("OK")
8474 otherButtonTitles:nil
8477 [alert setContext:@"urlerror"];
8482 UIAlertView *alert = [[[UIAlertView alloc]
8483 initWithTitle:UCLocalize("NOT_REPOSITORY")
8484 message:UCLocalize("NOT_REPOSITORY_EX")
8486 cancelButtonTitle:UCLocalize("OK")
8487 otherButtonTitles:nil
8490 [alert setContext:@"trivial"];
8500 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8501 switch ([response statusCode]) {
8507 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8508 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8510 [self _endConnection:connection];
8513 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8514 [self _endConnection:connection];
8517 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8518 NSURL *url([NSURL URLWithString:href]);
8520 NSMutableURLRequest *request = [NSMutableURLRequest
8522 cachePolicy:NSURLRequestUseProtocolCachePolicy
8523 timeoutInterval:120.0
8526 [request setHTTPMethod:method];
8528 if (Machine_ != NULL)
8529 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8531 if ([url isCydiaSecure]) {
8532 if (UniqueID_ != nil) {
8533 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8534 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8538 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8541 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8542 NSString *context([alert context]);
8544 if ([context isEqualToString:@"source"]) {
8547 NSString *href = [[alert textField] text];
8549 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8551 if (![href hasSuffix:@"/"])
8552 href_ = [href stringByAppendingString:@"/"];
8556 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8557 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8558 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8559 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8563 // XXX: this is stupid
8564 hud_ = [delegate_ addProgressHUD];
8565 [hud_ setText:UCLocalize("VERIFYING_URL")];
8566 [delegate_ retainNetworkActivityIndicator];
8575 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8576 } else if ([context isEqualToString:@"trivial"])
8577 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8578 else if ([context isEqualToString:@"urlerror"])
8579 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8580 else if ([context isEqualToString:@"warning"]) {
8583 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8592 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8597 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8598 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8599 [list_ setRowHeight:53];
8600 [(UITableView *) list_ setDataSource:self];
8601 [list_ setDelegate:self];
8602 [self setView:list_];
8605 - (void) viewDidLoad {
8606 [super viewDidLoad];
8608 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8609 [self updateButtonsForEditingStatus:NO animated:NO];
8612 - (void) releaseSubviews {
8617 [super releaseSubviews];
8620 - (id) initWithDatabase:(Database *)database {
8621 if ((self = [super init]) != nil) {
8622 database_ = database;
8626 - (void) reloadData {
8629 @synchronized (database_) {
8630 era_ = [database_ era];
8633 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8636 sources_ = [NSMutableArray arrayWithCapacity:16];
8637 [sources_ addObjectsFromArray:[database_ sources]];
8639 [sources_ sortUsingSelector:@selector(compareByName:)];
8642 int count([sources_ count]);
8644 for (int i = 0; i != count; i++) {
8645 if ([[sources_ objectAtIndex:i] record] == nil)
8650 [list_ setEditing:NO];
8651 [self updateButtonsForEditingStatus:NO animated:NO];
8655 - (void) showAddSourcePrompt {
8656 UIAlertView *alert = [[[UIAlertView alloc]
8657 initWithTitle:UCLocalize("ENTER_APT_URL")
8660 cancelButtonTitle:UCLocalize("CANCEL")
8662 UCLocalize("ADD_SOURCE"),
8666 [alert setContext:@"source"];
8668 [alert setNumberOfRows:1];
8669 [alert addTextFieldWithValue:@"http://" label:@""];
8671 UITextInputTraits *traits = [[alert textField] textInputTraits];
8672 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8673 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8674 [traits setKeyboardType:UIKeyboardTypeURL];
8675 // XXX: UIReturnKeyDone
8676 [traits setReturnKeyType:UIReturnKeyNext];
8681 - (void) addButtonClicked {
8682 [self showAddSourcePrompt];
8685 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8686 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8687 initWithTitle:UCLocalize("ADD")
8688 style:UIBarButtonItemStylePlain
8690 action:@selector(addButtonClicked)
8691 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8693 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8694 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8695 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8697 action:@selector(editButtonClicked)
8698 ] autorelease] animated:animated];
8700 if (IsWildcat_ && !editing)
8701 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8702 initWithTitle:UCLocalize("SETTINGS")
8703 style:UIBarButtonItemStylePlain
8705 action:@selector(settingsButtonClicked)
8709 - (void) settingsButtonClicked {
8710 [delegate_ showSettings];
8713 - (void) editButtonClicked {
8714 [list_ setEditing:![list_ isEditing] animated:YES];
8716 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8722 /* Settings Controller {{{ */
8723 @interface SettingsController : CyteViewController <
8724 UITableViewDataSource,
8727 _transient Database *database_;
8728 // XXX: ok, "roledelegate_"?...
8729 _transient id roledelegate_;
8730 _H<UITableView, 2> table_;
8731 _H<UISegmentedControl> segment_;
8732 _H<UIView> container_;
8735 - (void) showDoneButton;
8736 - (void) resizeSegmentedControl;
8740 @implementation SettingsController
8743 table_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStyleGrouped] autorelease];
8744 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8745 [table_ setDelegate:self];
8746 [(UITableView *) table_ setDataSource:self];
8747 [self setView:table_];
8749 NSArray *items = [NSArray arrayWithObjects:
8751 UCLocalize("HACKER"),
8752 UCLocalize("DEVELOPER"),
8754 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8755 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8756 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8757 [container_ addSubview:segment_];
8760 - (void) viewDidLoad {
8761 [super viewDidLoad];
8763 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8766 if ([Role_ isEqualToString:@"User"]) index = 0;
8767 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8768 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8770 [segment_ setSelectedSegmentIndex:index];
8771 [self showDoneButton];
8774 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8775 [self resizeSegmentedControl];
8778 - (void) releaseSubviews {
8783 [super releaseSubviews];
8786 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8787 if ((self = [super init]) != nil) {
8788 database_ = database;
8789 roledelegate_ = delegate;
8793 - (void) resizeSegmentedControl {
8794 CGFloat width = [[self view] frame].size.width;
8795 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8798 - (void) viewWillAppear:(BOOL)animated {
8799 [super viewWillAppear:animated];
8801 [self resizeSegmentedControl];
8804 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8805 [self resizeSegmentedControl];
8808 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8809 [self resizeSegmentedControl];
8813 NSString *role(nil);
8815 switch ([segment_ selectedSegmentIndex]) {
8816 case 0: role = @"User"; break;
8817 case 1: role = @"Hacker"; break;
8818 case 2: role = @"Developer"; break;
8823 if (![role isEqualToString:Role_]) {
8824 bool rolling(Role_ == nil);
8827 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8831 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8835 [roledelegate_ loadData];
8837 [roledelegate_ updateData];
8841 - (void) segmentChanged:(UISegmentedControl *)control {
8842 [self showDoneButton];
8845 - (void) saveAndClose {
8848 [[self navigationItem] setRightBarButtonItem:nil];
8849 [[self navigationController] dismissModalViewControllerAnimated:YES];
8852 - (void) doneButtonClicked {
8853 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8854 [spinner startAnimating];
8855 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8856 [[self navigationItem] setRightBarButtonItem:spinItem];
8858 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8861 - (void) showDoneButton {
8862 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8863 initWithTitle:UCLocalize("DONE")
8864 style:UIBarButtonItemStyleDone
8866 action:@selector(doneButtonClicked)
8867 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8870 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8871 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8875 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8879 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8880 return nil; // This method is required by the protocol.
8883 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8885 return UCLocalize("ROLE_EX");
8887 return [NSString stringWithFormat:
8888 @"%@: %@\n%@: %@\n%@: %@",
8889 UCLocalize("USER"), UCLocalize("USER_EX"),
8890 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8891 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8896 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8897 return section == 3 ? 44.0f : 0;
8900 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8901 return section == 3 ? container_ : nil;
8904 - (void) reloadData {
8907 [table_ reloadData];
8912 /* Stash Controller {{{ */
8913 @interface StashController : CyteViewController {
8914 _H<UIActivityIndicatorView> spinner_;
8915 _H<UILabel> status_;
8916 _H<UILabel> caption_;
8921 @implementation StashController
8924 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8925 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8926 [self setView:view];
8928 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8930 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8931 CGRect spinrect = [spinner_ frame];
8932 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8933 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8934 [spinner_ setFrame:spinrect];
8935 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8936 [view addSubview:spinner_];
8937 [spinner_ startAnimating];
8940 captrect.size.width = [[self view] frame].size.width;
8941 captrect.size.height = 40.0f;
8942 captrect.origin.x = 0;
8943 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8944 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8945 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8946 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8947 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8948 [caption_ setTextColor:[UIColor whiteColor]];
8949 [caption_ setBackgroundColor:[UIColor clearColor]];
8950 [caption_ setShadowColor:[UIColor blackColor]];
8951 [caption_ setTextAlignment:UITextAlignmentCenter];
8952 [view addSubview:caption_];
8955 statusrect.size.width = [[self view] frame].size.width;
8956 statusrect.size.height = 30.0f;
8957 statusrect.origin.x = 0;
8958 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8959 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8960 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8961 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8962 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8963 [status_ setTextColor:[UIColor whiteColor]];
8964 [status_ setBackgroundColor:[UIColor clearColor]];
8965 [status_ setShadowColor:[UIColor blackColor]];
8966 [status_ setTextAlignment:UITextAlignmentCenter];
8967 [view addSubview:status_];
8970 - (void) releaseSubviews {
8975 [super releaseSubviews];
8981 @interface CYURLCache : SDURLCache {
8986 @implementation CYURLCache
8988 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8991 else if ([event isEqualToString:@"no-cache"])
8993 else if ([event isEqualToString:@"store"])
8995 else if ([event isEqualToString:@"invalid"])
8997 else if ([event isEqualToString:@"memory"])
8999 else if ([event isEqualToString:@"disk"])
9001 else if ([event isEqualToString:@"miss"])
9004 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
9008 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
9009 if (NSURLResponse *response = [cached response])
9010 if (NSString *mime = [response MIMEType])
9011 if ([mime isEqualToString:@"text/cache-manifest"]) {
9012 NSURL *url([response URL]);
9015 NSLog(@"###: %@", [url absoluteString]);
9018 @synchronized (HostConfig_) {
9019 [CachedURLs_ addObject:url];
9023 [super storeCachedResponse:cached forRequest:request];
9028 @interface Cydia : UIApplication <
9029 ConfirmationControllerDelegate,
9032 UINavigationControllerDelegate,
9033 UITabBarControllerDelegate
9035 _H<UIWindow> window_;
9036 _H<CYTabBarController> tabbar_;
9037 _H<CydiaLoadingViewController> emulated_;
9039 _H<NSMutableArray> essential_;
9040 _H<NSMutableArray> broken_;
9042 Database *database_;
9044 _H<NSURL> starturl_;
9049 _H<StashController> stash_;
9058 @implementation Cydia
9060 - (void) beginUpdate {
9061 [tabbar_ beginUpdate];
9065 return [tabbar_ updating];
9069 if ([broken_ count] != 0) {
9070 int count = [broken_ count];
9072 UIAlertView *alert = [[[UIAlertView alloc]
9073 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9074 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9076 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
9078 UCLocalize("TEMPORARY_IGNORE"),
9082 [alert setContext:@"fixhalf"];
9083 [alert setNumberOfRows:2];
9085 } else if (!Ignored_ && [essential_ count] != 0) {
9086 int count = [essential_ count];
9088 UIAlertView *alert = [[[UIAlertView alloc]
9089 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9090 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9092 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9094 UCLocalize("UPGRADE_ESSENTIAL"),
9095 UCLocalize("COMPLETE_UPGRADE"),
9099 [alert setContext:@"upgrade"];
9104 - (void) returnToCydia {
9108 - (void) _saveConfig {
9109 @synchronized (database_) {
9116 NSString *error(nil);
9118 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9120 NSError *error(nil);
9121 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9122 NSLog(@"failure to save metadata data: %@", error);
9127 NSLog(@"failure to serialize metadata: %@", error);
9131 CydiaWriteSources();
9134 // Navigation controller for the queuing badge.
9135 - (UINavigationController *) queueNavigationController {
9136 NSArray *controllers = [tabbar_ viewControllers];
9137 return [controllers objectAtIndex:3];
9140 - (void) unloadData {
9141 [tabbar_ unloadData];
9144 - (void) _updateData {
9148 UINavigationController *navigation = [self queueNavigationController];
9150 id queuedelegate = nil;
9151 if ([[navigation viewControllers] count] > 0)
9152 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9154 [queuedelegate queueStatusDidChange];
9155 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9158 - (void) _refreshIfPossible:(NSDate *)update {
9159 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9161 bool recently = false;
9162 if (update != nil) {
9163 NSTimeInterval interval([update timeIntervalSinceNow]);
9164 if (interval <= 0 && interval > -(15*60))
9168 // Don't automatic refresh if:
9169 // - We already refreshed recently.
9170 // - We already auto-refreshed this launch.
9171 // - Auto-refresh is disabled.
9172 if (recently || loaded_ || ManualRefresh) {
9173 // If we are cancelling, we need to make sure it knows it's already loaded.
9176 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9178 // We are going to load, so remember that.
9181 SCNetworkReachabilityFlags flags; {
9182 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9183 SCNetworkReachabilityGetFlags(reachability, &flags);
9184 CFRelease(reachability);
9187 // XXX: this elaborate mess is what Apple is using to determine this? :(
9188 // XXX: do we care if the user has to intervene? maybe that's ok?
9190 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9191 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9192 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9193 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9194 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9195 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9199 // If we can reach the server, auto-refresh!
9201 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9207 - (void) refreshIfPossible {
9208 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9211 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9212 @synchronized (self) {
9213 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9214 [hud setText:UCLocalize("RELOADING_DATA")];
9216 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9220 [essential_ removeAllObjects];
9221 [broken_ removeAllObjects];
9223 NSArray *packages([database_ packages]);
9224 for (Package *package in packages) {
9226 [broken_ addObject:package];
9227 if ([package upgradableAndEssential:NO]) {
9228 if ([package essential])
9229 [essential_ addObject:package];
9234 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9237 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9238 [changesItem setBadgeValue:badge];
9239 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9240 [self setApplicationIconBadgeNumber:changes];
9243 [changesItem setBadgeValue:nil];
9244 [changesItem setAnimatedBadge:NO];
9245 [self setApplicationIconBadgeNumber:0];
9251 [self removeProgressHUD:hud];
9254 - (void) updateData {
9260 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9263 - (void) disemulate {
9264 if (emulated_ == nil)
9267 [window_ addSubview:[tabbar_ view]];
9268 [[emulated_ view] removeFromSuperview];
9270 [window_ setUserInteractionEnabled:YES];
9273 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9274 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9276 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9278 UIViewController *parent;
9279 if (emulated_ == nil)
9288 [parent presentModalViewController:navigation animated:YES];
9291 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9292 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9294 if (navigation != nil)
9295 [navigation pushViewController:progress animated:YES];
9297 [self presentModalViewController:progress force:YES];
9299 [progress invoke:invocation withTitle:title];
9303 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9304 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9307 - (void) repairWithInvocation:(NSInvocation *)invocation {
9309 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9313 - (void) repairWithSelector:(SEL)selector {
9314 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9317 - (void) reloadData {
9318 [self reloadDataWithInvocation:nil];
9319 if ([database_ progressDelegate] == nil)
9325 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9328 - (void) addSource:(NSDictionary *) source {
9329 CydiaAddSource(source);
9332 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9333 CydiaAddSource(href, distribution, sections);
9336 - (void) addTrivialSource:(NSString *)href {
9337 CydiaAddSource(href, @"./");
9340 - (void) updateValues {
9345 pkgProblemResolver *resolver = [database_ resolver];
9347 resolver->InstallProtect();
9348 if (!resolver->Resolve(true))
9353 // XXX: this is a really crappy way of doing this.
9354 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9355 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9356 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9357 if ([tabbar_ updating])
9358 [tabbar_ cancelUpdate];
9360 if (![database_ prepare])
9363 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9364 [page setDelegate:self];
9365 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9368 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9369 [tabbar_ presentModalViewController:confirm_ animated:YES];
9375 @synchronized (self) {
9380 - (void) clearPackage:(Package *)package {
9381 @synchronized (self) {
9388 - (void) installPackages:(NSArray *)packages {
9389 @synchronized (self) {
9390 for (Package *package in packages)
9397 - (void) installPackage:(Package *)package {
9398 @synchronized (self) {
9405 - (void) removePackage:(Package *)package {
9406 @synchronized (self) {
9413 - (void) distUpgrade {
9414 @synchronized (self) {
9415 if (![database_ upgrade])
9422 [database_ perform];
9423 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9426 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9429 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9431 [self refreshIfPossible];
9434 - (void) showSettings {
9435 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9438 - (void) retainNetworkActivityIndicator {
9439 if (activity_++ == 0)
9440 [self setNetworkActivityIndicatorVisible:YES];
9443 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9447 - (void) releaseNetworkActivityIndicator {
9448 if (--activity_ == 0)
9449 [self setNetworkActivityIndicatorVisible:NO];
9452 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9457 - (void) cancelAndClear:(bool)clear {
9458 @synchronized (self) {
9470 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9471 NSString *context([alert context]);
9473 if ([context isEqualToString:@"conffile"]) {
9474 FILE *input = [database_ input];
9475 if (button == [alert cancelButtonIndex])
9476 fprintf(input, "N\n");
9477 else if (button == [alert firstOtherButtonIndex])
9478 fprintf(input, "Y\n");
9481 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9482 } else if ([context isEqualToString:@"fixhalf"]) {
9483 if (button == [alert cancelButtonIndex]) {
9484 @synchronized (self) {
9485 for (Package *broken in (id) broken_) {
9488 NSString *id = [broken id];
9489 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9490 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9491 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9492 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9498 } else if (button == [alert firstOtherButtonIndex]) {
9499 [broken_ removeAllObjects];
9503 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9504 } else if ([context isEqualToString:@"upgrade"]) {
9505 if (button == [alert firstOtherButtonIndex]) {
9506 @synchronized (self) {
9507 for (Package *essential in (id) essential_)
9508 [essential install];
9513 } else if (button == [alert firstOtherButtonIndex] + 1) {
9515 } else if (button == [alert cancelButtonIndex]) {
9519 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9523 - (void) system:(NSString *)command {
9524 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9527 system([command UTF8String]);
9533 - (void) applicationWillSuspend {
9535 [super applicationWillSuspend];
9538 - (BOOL) isSafeToSuspend {
9541 NSLog(@"isSafeToSuspend: locked_ != 0");
9546 // Use external process status API internally.
9547 // This is probably a really bad idea.
9548 // XXX: what is the point of this? does this solve anything at all?
9549 uint64_t status = 0;
9551 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9552 notify_get_state(notify_token, &status);
9553 notify_cancel(notify_token);
9558 NSLog(@"isSafeToSuspend: status != 0");
9564 NSLog(@"isSafeToSuspend: -> true");
9569 - (void) applicationSuspend:(__GSEvent *)event {
9570 if ([self isSafeToSuspend])
9571 [super applicationSuspend:event];
9574 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9575 if ([self isSafeToSuspend])
9576 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9579 - (void) _setSuspended:(BOOL)value {
9580 if ([self isSafeToSuspend])
9581 [super _setSuspended:value];
9584 - (UIProgressHUD *) addProgressHUD {
9585 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9586 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9588 [window_ setUserInteractionEnabled:NO];
9590 UIViewController *target(tabbar_);
9591 if (UIViewController *modal = [target modalViewController])
9594 [hud showInView:[target view]];
9600 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9603 [hud removeFromSuperview];
9604 [window_ setUserInteractionEnabled:YES];
9607 - (CyteViewController *) pageForPackage:(NSString *)name {
9608 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9611 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9612 NSString *scheme([[url scheme] lowercaseString]);
9613 if ([[url absoluteString] length] <= [scheme length] + 3)
9615 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9616 NSArray *components([path componentsSeparatedByString:@"/"]);
9618 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9619 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1]]);
9620 if (controller != nil)
9621 [controller setDelegate:self];
9625 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9628 NSString *base([components objectAtIndex:0]);
9630 CyteViewController *controller = nil;
9632 if ([base isEqualToString:@"url"]) {
9633 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9634 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9635 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9636 } else if (!external && [components count] == 1) {
9637 if ([base isEqualToString:@"manage"]) {
9638 controller = [[[ManageController alloc] init] autorelease];
9641 if ([base isEqualToString:@"storage"]) {
9642 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/storage/", UI_]]] autorelease];
9645 if ([base isEqualToString:@"sources"]) {
9646 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9649 if ([base isEqualToString:@"home"]) {
9650 controller = [[[HomeController alloc] init] autorelease];
9653 if ([base isEqualToString:@"sections"]) {
9654 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9657 if ([base isEqualToString:@"search"]) {
9658 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9661 if ([base isEqualToString:@"changes"]) {
9662 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9665 if ([base isEqualToString:@"installed"]) {
9666 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9668 } else if ([components count] == 2) {
9669 NSString *argument = [components objectAtIndex:1];
9671 if ([base isEqualToString:@"package"]) {
9672 controller = [self pageForPackage:argument];
9675 if (!external && [base isEqualToString:@"search"]) {
9676 controller = [[[SearchController alloc] initWithDatabase:database_ query:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9679 if (!external && [base isEqualToString:@"sections"]) {
9680 if ([argument isEqualToString:@"all"])
9682 controller = [[[SectionController alloc] initWithDatabase:database_ section:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] autorelease];
9685 if (!external && [base isEqualToString:@"sources"]) {
9686 if ([argument isEqualToString:@"add"]) {
9687 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9688 [(SourcesController *)controller showAddSourcePrompt];
9690 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9691 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9695 if (!external && [base isEqualToString:@"launch"]) {
9696 [self launchApplicationWithIdentifier:argument suspended:NO];
9699 } else if (!external && [components count] == 3) {
9700 NSString *arg1 = [components objectAtIndex:1];
9701 NSString *arg2 = [components objectAtIndex:2];
9703 if ([base isEqualToString:@"package"]) {
9704 if ([arg2 isEqualToString:@"settings"]) {
9705 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9706 } else if ([arg2 isEqualToString:@"files"]) {
9707 if (Package *package = [database_ packageWithName:arg1]) {
9708 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9709 [(FileTable *)controller setPackage:package];
9715 [controller setDelegate:self];
9719 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9720 CyteViewController *page([self pageForURL:url forExternal:external]);
9723 [tabbar_ setUnselectedViewController:page];
9728 - (void) applicationOpenURL:(NSURL *)url {
9729 [super applicationOpenURL:url];
9734 [self openCydiaURL:url forExternal:YES];
9737 - (void) applicationWillResignActive:(UIApplication *)application {
9738 // Stop refreshing if you get a phone call or lock the device.
9739 if ([tabbar_ updating])
9740 [tabbar_ cancelUpdate];
9742 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9743 [super applicationWillResignActive:application];
9746 - (void) saveState {
9747 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9748 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9749 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9755 - (void) applicationWillTerminate:(UIApplication *)application {
9759 - (void) setConfigurationData:(NSString *)data {
9760 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9762 if (!conffile_r(data)) {
9763 lprintf("E:invalid conffile\n");
9767 NSString *ofile = conffile_r[1];
9768 //NSString *nfile = conffile_r[2];
9770 UIAlertView *alert = [[[UIAlertView alloc]
9771 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9772 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9774 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9776 UCLocalize("ACCEPT_NEW_COPY"),
9777 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9781 [alert setContext:@"conffile"];
9782 [alert setNumberOfRows:2];
9786 - (void) addStashController {
9788 stash_ = [[[StashController alloc] init] autorelease];
9789 [window_ addSubview:[stash_ view]];
9792 - (void) removeStashController {
9793 [[stash_ view] removeFromSuperview];
9799 [self setIdleTimerDisabled:YES];
9801 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9802 UpdateExternalStatus(1);
9803 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9804 UpdateExternalStatus(0);
9806 [self removeStashController];
9808 pid_t pid(ExecFork());
9810 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9811 perror("launchctl stop");
9818 - (void) setupViewControllers {
9819 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9821 NSMutableArray *items([NSMutableArray arrayWithObjects:
9822 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9823 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9824 [[[UITabBarItem alloc] initWithTitle:(AprilFools_ ? @"Timeline" : UCLocalize("CHANGES")) image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9825 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9829 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9830 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9832 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9835 NSMutableArray *controllers([NSMutableArray array]);
9836 for (UITabBarItem *item in items) {
9837 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9838 [controller setTabBarItem:item];
9839 [controllers addObject:controller];
9841 [tabbar_ setViewControllers:controllers];
9843 [tabbar_ setUpdateDelegate:self];
9846 - (void) _sendMemoryWarningNotification {
9847 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9848 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9850 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9853 - (void) _sendMemoryWarningNotifications {
9855 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9861 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9863 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9866 - (void) applicationDidFinishLaunching:(id)unused {
9867 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9870 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9871 [self setApplicationSupportsShakeToEdit:NO];
9873 @synchronized (HostConfig_) {
9874 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9877 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9878 initWithMemoryCapacity:524288
9879 diskCapacity:10485760
9880 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9883 [CydiaWebViewController _initialize];
9885 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9887 // this would disallow http{,s} URLs from accessing this data
9888 //[WebView registerURLSchemeAsLocal:@"cydia"];
9890 Font12_ = [UIFont systemFontOfSize:12];
9891 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9892 Font14_ = [UIFont systemFontOfSize:14];
9893 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9894 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9896 essential_ = [NSMutableArray arrayWithCapacity:4];
9897 broken_ = [NSMutableArray arrayWithCapacity:4];
9899 // XXX: I really need this thing... like, seriously... I'm sorry
9900 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9902 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9903 [window_ orderFront:self];
9904 [window_ makeKey:self];
9905 [window_ setHidden:NO];
9908 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9909 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9910 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9911 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9912 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9913 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9914 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9915 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9916 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9919 [self addStashController];
9920 // XXX: this would be much cleaner as a yieldToSelector:
9921 // that way the removeStashController could happen right here inline
9922 // we also could no longer require the useless stash_ field anymore
9923 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9927 database_ = [Database sharedInstance];
9928 [database_ setDelegate:self];
9930 [window_ setUserInteractionEnabled:NO];
9931 [self setupViewControllers];
9933 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9934 [window_ addSubview:[emulated_ view]];
9936 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9940 - (NSArray *) defaultStartPages {
9941 NSMutableArray *standard = [NSMutableArray array];
9942 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9943 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9944 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9946 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9948 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9949 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9951 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9958 [window_ setUserInteractionEnabled:YES];
9959 [self showSettings];
9962 if ([emulated_ modalViewController] != nil)
9963 [emulated_ dismissModalViewControllerAnimated:YES];
9964 [window_ setUserInteractionEnabled:NO];
9967 [self reloadDataWithInvocation:nil];
9968 [self refreshIfPossible];
9973 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9974 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9975 int standardIndex = 0;
9976 NSArray *standard = [self defaultStartPages];
9983 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9984 if (valid && closed != nil) {
9985 NSTimeInterval interval([closed timeIntervalSinceNow]);
9986 // XXX: Is 30 minutes the optimal time here?
9987 if (interval <= -(30*60))
9991 if (valid && [saved count] != [standard count])
9995 for (unsigned int i = 0; i < [standard count]; i++) {
9996 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9997 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9998 // but it's good enough for now.
9999 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10006 NSArray *items = nil;
10008 [tabbar_ setSelectedIndex:savedIndex];
10011 [tabbar_ setSelectedIndex:standardIndex];
10015 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10016 NSArray *stack = [items objectAtIndex:tab];
10017 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10018 NSMutableArray *current = [NSMutableArray array];
10020 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10021 NSString *addr = [stack objectAtIndex:nav];
10022 NSURL *url = [NSURL URLWithString:addr];
10023 CyteViewController *page = [self pageForURL:url forExternal:NO];
10025 [current addObject:page];
10028 [navigation setViewControllers:current];
10031 // (Try to) show the startup URL.
10032 if (starturl_ != nil) {
10033 [self openCydiaURL:starturl_ forExternal:NO];
10038 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10039 if (item != nil && IsWildcat_) {
10040 [sheet showFromBarButtonItem:item animated:YES];
10042 [sheet showInView:window_];
10046 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10047 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10048 [progress setTitle:task];
10049 [progress addProgressEvent:event];
10052 - (void) addProgressEventForTask:(NSArray *)data {
10053 CydiaProgressEvent *event([data objectAtIndex:0]);
10054 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10055 [self addProgressEvent:event forTask:task];
10058 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10059 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10065 id Alloc_(id self, SEL selector) {
10066 id object = alloc_(self, selector);
10067 lprintf("[%s]A-%p\n", self->isa->name, object);
10072 id Dealloc_(id self, SEL selector) {
10073 id object = dealloc_(self, selector);
10074 lprintf("[%s]D-%p\n", self->isa->name, object);
10078 Class $WebDefaultUIKitDelegate;
10080 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
10081 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
10082 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
10083 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
10086 static NSSet *MobilizedFiles_;
10088 static NSURL *MobilizeURL(NSURL *url) {
10089 NSString *path([url path]);
10090 if ([path hasPrefix:@"/var/root/"]) {
10091 NSString *file([path substringFromIndex:10]);
10092 if ([MobilizedFiles_ containsObject:file])
10093 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10099 Class $CFXPreferencesPropertyListSource;
10100 @class CFXPreferencesPropertyListSource;
10102 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10103 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10104 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10105 url = MobilizeURL(url);
10106 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
10107 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
10113 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10114 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10115 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10116 url = MobilizeURL(url);
10117 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
10118 //NSLog(@"%@ %@", [url absoluteString], value);
10124 Class $NSURLConnection;
10126 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10127 NSMutableURLRequest *copy([request mutableCopy]);
10129 NSURL *url([copy URL]);
10131 NSString *host([url host]);
10132 NSString *scheme([[url scheme] lowercaseString]);
10134 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10136 @synchronized (HostConfig_) {
10137 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10138 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10139 [copy setHTTPShouldUsePipelining:YES];
10141 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10142 if ([control isEqualToString:@"max-age=0"])
10143 if ([CachedURLs_ containsObject:url]) {
10145 NSLog(@"~~~: %@", url);
10148 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10150 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10151 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10152 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10156 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10160 int main(int argc, char *argv[]) {
10161 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10165 UpdateExternalStatus(0);
10167 if (Class $UIDevice = objc_getClass("UIDevice")) {
10168 UIDevice *device([$UIDevice currentDevice]);
10169 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10171 IsWildcat_ = false;
10173 UIScreen *screen([UIScreen mainScreen]);
10174 if ([screen respondsToSelector:@selector(scale)])
10175 ScreenScale_ = [screen scale];
10179 UIDevice *device([UIDevice currentDevice]);
10180 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10181 Idiom_ = @"iphone";
10183 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10184 if (idiom == UIUserInterfaceIdiomPhone)
10185 Idiom_ = @"iphone";
10186 else if (idiom == UIUserInterfaceIdiomPad)
10189 NSLog(@"unknown UIUserInterfaceIdiom!");
10192 Pcre pattern("^([0-9]+\\.[0-9]+)");
10194 if (pattern([device systemVersion]))
10195 Firmware_ = pattern[1];
10196 if (pattern(Cydia_))
10197 Major_ = pattern[1];
10199 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10201 HostConfig_ = [[[NSObject alloc] init] autorelease];
10202 @synchronized (HostConfig_) {
10203 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10204 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10205 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10206 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10207 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10210 NSString *ui(@"ui/ios");
10212 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10213 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10214 UI_ = CydiaURL(ui);
10216 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10218 MobilizedFiles_ = [NSMutableSet setWithObjects:
10219 @"Library/Preferences/com.apple.Accessibility.plist",
10220 @"Library/Preferences/com.apple.preferences.sounds.plist",
10223 /* Library Hacks {{{ */
10224 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10226 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10228 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10229 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10230 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10231 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10234 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10235 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10236 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10237 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10240 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10241 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10242 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10243 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10244 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10247 $NSURLConnection = objc_getClass("NSURLConnection");
10248 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10249 if (NSURLConnection$init$ != NULL) {
10250 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10251 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10254 /* Set Locale {{{ */
10255 Locale_ = CFLocaleCopyCurrent();
10256 Languages_ = [NSLocale preferredLanguages];
10258 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10259 //NSLog(@"%@", [Languages_ description]);
10262 if (Locale_ != NULL)
10263 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10264 else if (Languages_ != nil && [Languages_ count] != 0)
10265 lang = [[Languages_ objectAtIndex:0] UTF8String];
10267 // XXX: consider just setting to C and then falling through?
10270 if (lang != NULL) {
10271 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10272 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10275 NSLog(@"Setting Language: %s", lang);
10277 if (lang != NULL) {
10278 setenv("LANG", lang, true);
10279 std::setlocale(LC_ALL, lang);
10283 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10285 /* Parse Arguments {{{ */
10286 bool substrate(false);
10292 for (int argi(1); argi != argc; ++argi)
10293 if (strcmp(argv[argi], "--") == 0) {
10295 argv[argi] = argv[0];
10301 for (int argi(1); argi != arge; ++argi)
10302 if (strcmp(args[argi], "--substrate") == 0)
10305 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10309 App_ = [[NSBundle mainBundle] bundlePath];
10315 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10316 alloc_ = alloc->method_imp;
10317 alloc->method_imp = (IMP) &Alloc_;*/
10319 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10320 dealloc_ = dealloc->method_imp;
10321 dealloc->method_imp = (IMP) &Dealloc_;*/
10323 /* System Information {{{ */
10327 size = sizeof(maxproc);
10328 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10329 perror("sysctlbyname(\"kern.maxproc\", ?)");
10330 else if (maxproc < 64) {
10332 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10333 perror("sysctlbyname(\"kern.maxproc\", #)");
10336 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10337 char *osversion = new char[size];
10338 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10339 perror("sysctlbyname(\"kern.osversion\", ?)");
10341 System_ = [NSString stringWithUTF8String:osversion];
10343 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10344 char *machine = new char[size];
10345 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10346 perror("sysctlbyname(\"hw.machine\", ?)");
10348 Machine_ = machine;
10350 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10351 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10352 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10354 UniqueID_ = [device uniqueIdentifier];
10356 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10357 Product_ = [info objectForKey:@"SafariProductVersion"];
10358 Safari_ = [info objectForKey:@"CFBundleVersion"];
10361 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10363 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10364 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10365 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10366 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10367 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10368 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10370 UserAgent_ = agent;
10372 /* Load Database {{{ */
10374 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10376 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10378 if (Metadata_ == NULL)
10379 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10381 Settings_ = [Metadata_ objectForKey:@"Settings"];
10383 Packages_ = [Metadata_ objectForKey:@"Packages"];
10385 Values_ = [Metadata_ objectForKey:@"Values"];
10386 Sections_ = [Metadata_ objectForKey:@"Sections"];
10387 Sources_ = [Metadata_ objectForKey:@"Sources"];
10389 Token_ = [Metadata_ objectForKey:@"Token"];
10391 Version_ = [Metadata_ objectForKey:@"Version"];
10394 if (Settings_ != nil)
10395 Role_ = [Settings_ objectForKey:@"Role"];
10397 if (Values_ == nil) {
10398 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10399 [Metadata_ setObject:Values_ forKey:@"Values"];
10402 if (Sections_ == nil) {
10403 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10404 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10407 if (Sources_ == nil) {
10408 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10409 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10412 if (Version_ == nil) {
10413 Version_ = [NSNumber numberWithUnsignedInt:0];
10414 [Metadata_ setObject:Version_ forKey:@"Version"];
10417 if ([Version_ unsignedIntValue] == 0) {
10418 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10419 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10420 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10421 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10423 Version_ = [NSNumber numberWithUnsignedInt:1];
10424 [Metadata_ setObject:Version_ forKey:@"Version"];
10426 [Metadata_ removeObjectForKey:@"LastUpdate"];
10432 CydiaWriteSources();
10435 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10438 if (Packages_ != nil) {
10440 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10444 [Metadata_ removeObjectForKey:@"Packages"];
10450 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10452 #define MobileSubstrate_(name) \
10453 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10454 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10455 if (handle == NULL) \
10456 NSLog(@"%s", dlerror()); \
10459 MobileSubstrate_(Activator)
10460 MobileSubstrate_(libstatusbar)
10461 MobileSubstrate_(SimulatedKeyEvents)
10462 MobileSubstrate_(WinterBoard)
10464 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10465 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10467 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10469 if (access("/User", F_OK) != 0 || version != 5) {
10471 system("/usr/libexec/cydia/firmware.sh");
10475 _assert([[NSFileManager defaultManager]
10476 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10477 withIntermediateDirectories:YES
10482 if (access("/tmp/cydia.chk", F_OK) == 0) {
10483 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10484 _assert(errno == ENOENT);
10485 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10486 _assert(errno == ENOENT);
10489 /* APT Initialization {{{ */
10490 _assert(pkgInitConfig(*_config));
10491 _assert(pkgInitSystem(*_config, _system));
10494 _config->Set("APT::Acquire::Translation", lang);
10496 // XXX: this timeout might be important :(
10497 //_config->Set("Acquire::http::Timeout", 15);
10499 _config->Set("Acquire::http::MaxParallel", 3);
10501 /* Color Choices {{{ */
10502 space_ = CGColorSpaceCreateDeviceRGB();
10504 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10505 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10506 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10507 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10508 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10509 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10510 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10511 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10512 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10514 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10515 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10517 /* UIKit Configuration {{{ */
10518 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10519 if ($GSFontSetUseLegacyFontMetrics != NULL)
10520 $GSFontSetUseLegacyFontMetrics(YES);
10522 // XXX: I have a feeling this was important
10523 //UIKeyboardDisableAutomaticAppearance();
10526 Colon_ = UCLocalize("COLON_DELIMITED");
10527 Elision_ = UCLocalize("ELISION");
10528 Error_ = UCLocalize("ERROR");
10529 Warning_ = UCLocalize("WARNING");
10532 AprilFools_ = true;
10534 CFGregorianDate date(CFAbsoluteTimeGetGregorianDate(CFAbsoluteTimeGetCurrent(), CFTimeZoneCopySystem()));
10535 AprilFools_ = date.month == 4 && date.day == 1;
10539 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10541 CGColorSpaceRelease(space_);
10542 CFRelease(Locale_);