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 const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
257 static _finline NSString *CydiaURL(NSString *path) {
259 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
260 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
261 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
262 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
263 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
265 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
268 static _finline void UpdateExternalStatus(uint64_t newStatus) {
270 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
271 notify_set_state(notify_token, newStatus);
272 notify_cancel(notify_token);
274 notify_post("com.saurik.Cydia.status");
277 static CGFloat CYStatusBarHeight() {
278 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
279 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
282 /* NSForcedOrderingSearch doesn't work on the iPhone */
283 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
284 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
285 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
287 /* Insertion Sort {{{ */
289 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
290 const char *ptr = (const char *)list;
292 CFIndex half = count / 2;
293 const char *probe = ptr + elementSize * half;
294 CFComparisonResult cr = comparator(element, probe, context);
295 if (0 == cr) return (probe - (const char *)list) / elementSize;
296 ptr = (cr < 0) ? ptr : probe + elementSize;
297 count = (cr < 0) ? half : (half + (count & 1) - 1);
299 return (ptr - (const char *)list) / elementSize;
302 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
303 const char *ptr = (const char *)list;
305 CFIndex half = count / 2;
306 const char *probe = ptr + elementSize * half;
307 CFComparisonResult cr = comparator(element, probe, context);
308 if (0 == cr) return (probe - (const char *)list) / elementSize;
309 ptr = (cr < 0) ? ptr : probe + elementSize;
310 count = (cr < 0) ? half : (half + (count & 1) - 1);
312 return (ptr - (const char *)list) / elementSize;
315 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
316 if (range.length == 0)
318 const void **values(new const void *[range.length]);
319 CFArrayGetValues(array, range, values);
321 #if HistogramInsertionSort > 0
322 uint32_t total(0), *offsets(new uint32_t[range.length]);
325 for (CFIndex index(1); index != range.length; ++index) {
326 const void *value(values[index]);
327 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
328 CFIndex correct(index);
329 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
330 #if HistogramInsertionSort > 1
331 NSLog(@"%@ < %@", value, values[correct - 1]);
336 if (correct != index) {
337 size_t offset(index - correct);
338 #if HistogramInsertionSort
342 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
344 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
345 values[correct] = value;
349 CFArrayReplaceValues(array, range, values, range.length);
352 #if HistogramInsertionSort > 0
353 for (CFIndex index(0); index != range.length; ++index)
354 if (offsets[index] != 0)
355 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
356 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
363 /* Apple Bug Fixes {{{ */
364 @implementation UIWebDocumentView (Cydia)
366 - (void) _setScrollerOffset:(CGPoint)offset {
367 UIScroller *scroller([self _scroller]);
369 CGSize size([scroller contentSize]);
370 CGSize bounds([scroller bounds].size);
373 max.x = size.width - bounds.width;
374 max.y = size.height - bounds.height;
382 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
383 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
385 [scroller setOffset:offset];
391 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
392 size_t length([self length] - state->state);
395 else if (length > count)
397 for (size_t i(0); i != length; ++i)
398 objects[i] = [self item:state->state++];
399 state->itemsPtr = objects;
400 state->mutationsPtr = (unsigned long *) self;
404 /* Cydia NSString Additions {{{ */
405 @interface NSString (Cydia)
406 - (NSComparisonResult) compareByPath:(NSString *)other;
407 - (NSString *) stringByCachingURLWithCurrentCDN;
408 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
411 @implementation NSString (Cydia)
413 - (NSComparisonResult) compareByPath:(NSString *)other {
414 NSString *prefix = [self commonPrefixWithString:other options:0];
415 size_t length = [prefix length];
417 NSRange lrange = NSMakeRange(length, [self length] - length);
418 NSRange rrange = NSMakeRange(length, [other length] - length);
420 lrange = [self rangeOfString:@"/" options:0 range:lrange];
421 rrange = [other rangeOfString:@"/" options:0 range:rrange];
423 NSComparisonResult value;
425 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
426 value = NSOrderedSame;
427 else if (lrange.location == NSNotFound)
428 value = NSOrderedAscending;
429 else if (rrange.location == NSNotFound)
430 value = NSOrderedDescending;
432 value = NSOrderedSame;
434 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
435 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
436 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
437 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
439 NSComparisonResult result = [lpath compare:rpath];
440 return result == NSOrderedSame ? value : result;
443 - (NSString *) stringByCachingURLWithCurrentCDN {
445 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
446 withString:@"://cache.cydia.saurik.com/"
450 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
451 return [(id)CFURLCreateStringByAddingPercentEscapes(
456 kCFStringEncodingUTF8
463 /* C++ NSString Wrapper Cache {{{ */
464 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
465 return size == 0 ? NULL :
466 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
467 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
470 static _finline CFStringRef CYStringCreate(const char *data) {
471 return CYStringCreate(data, strlen(data));
480 _finline void clear_() {
481 if (cache_ != NULL) {
488 _finline bool empty() const {
492 _finline size_t size() const {
496 _finline char *data() const {
500 _finline void clear() {
505 _finline CYString() :
512 _finline ~CYString() {
516 void operator =(const CYString &rhs) {
520 if (rhs.cache_ == nil)
523 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
526 void copy(apr_pool_t *pool) {
527 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
528 memcpy(temp, data_, size_);
533 void set(apr_pool_t *pool, const char *data, size_t size) {
539 data_ = const_cast<char *>(data);
547 _finline void set(apr_pool_t *pool, const char *data) {
548 set(pool, data, data == NULL ? 0 : strlen(data));
551 _finline void set(apr_pool_t *pool, const std::string &rhs) {
552 set(pool, rhs.data(), rhs.size());
555 bool operator ==(const CYString &rhs) const {
556 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
559 _finline operator CFStringRef() {
561 cache_ = CYStringCreate(data_, size_);
565 _finline operator id() {
566 return (NSString *) static_cast<CFStringRef>(*this);
569 _finline operator const char *() {
570 return reinterpret_cast<const char *>(data_);
574 /* C++ NSString Algorithm Adapters {{{ */
576 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
579 struct NSStringMapHash :
580 std::unary_function<NSString *, size_t>
582 _finline size_t operator ()(NSString *value) const {
583 return CFStringHashNSString((CFStringRef) value);
587 struct NSStringMapLess :
588 std::binary_function<NSString *, NSString *, bool>
590 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
591 return [lhs compare:rhs] == NSOrderedAscending;
595 struct NSStringMapEqual :
596 std::binary_function<NSString *, NSString *, bool>
598 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
599 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
600 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
601 //[lhs isEqualToString:rhs];
606 /* CoreGraphics Primitives {{{ */
611 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
612 CGFloat color[] = {red, green, blue, alpha};
613 return CGColorCreate(space, color);
622 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
623 color_(Create_(space, red, green, blue, alpha))
625 Set(space, red, green, blue, alpha);
630 CGColorRelease(color_);
637 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
639 color_ = Create_(space, red, green, blue, alpha);
642 operator CGColorRef() {
648 /* Random Global Variables {{{ */
649 static const int PulseInterval_ = 50000;
651 static const NSString *UI_;
654 static bool RestartSubstrate_;
655 static NSArray *Finishes_;
657 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
658 #define NotifyConfig_ "/etc/notify.conf"
660 static bool Queuing_;
662 static CYColor Blue_;
663 static CYColor Blueish_;
664 static CYColor Black_;
666 static CYColor White_;
667 static CYColor Gray_;
668 static CYColor Green_;
669 static CYColor Purple_;
670 static CYColor Purplish_;
672 static UIColor *InstallingColor_;
673 static UIColor *RemovingColor_;
675 static NSString *App_;
677 static BOOL Advanced_;
678 static BOOL Ignored_;
680 static _H<UIFont> Font12_;
681 static _H<UIFont> Font12Bold_;
682 static _H<UIFont> Font14_;
683 static _H<UIFont> Font18Bold_;
684 static _H<UIFont> Font22Bold_;
686 static const char *Machine_ = NULL;
687 static NSString *System_ = nil;
688 static NSString *SerialNumber_ = nil;
689 static NSString *ChipID_ = nil;
690 static NSString *BBSNum_ = nil;
691 static _H<NSString> Token_;
692 static NSString *UniqueID_ = nil;
693 static NSString *PLMN_ = nil;
694 static NSString *Build_ = nil;
695 static NSString *Product_ = nil;
696 static NSString *Safari_ = nil;
698 static CFLocaleRef Locale_;
699 static NSArray *Languages_;
700 static CGColorSpaceRef space_;
702 static NSDictionary *SectionMap_;
703 static NSMutableDictionary *Metadata_;
704 static _transient NSMutableDictionary *Settings_;
705 static _transient NSString *Role_;
706 static _transient NSMutableDictionary *Packages_;
707 static _transient NSMutableDictionary *Values_;
708 static _transient NSMutableDictionary *Sections_;
709 _H<NSMutableDictionary> Sources_;
710 static _transient NSNumber *Version_;
711 _H<NSString> CydiaSource_;
716 static CGFloat ScreenScale_;
717 static NSString *Idiom_;
718 _H<NSString> Firmware_;
719 static NSString *Major_;
721 static _H<NSMutableDictionary> SessionData_;
722 static _H<NSObject> HostConfig_;
723 static _H<NSMutableSet> BridgedHosts_;
724 static _H<NSMutableSet> TokenHosts_;
725 static _H<NSMutableSet> InsecureHosts_;
726 static _H<NSMutableSet> PipelinedHosts_;
727 static _H<NSMutableSet> CachedURLs_;
729 static NSString *kCydiaProgressEventTypeError = @"Error";
730 static NSString *kCydiaProgressEventTypeInformation = @"Information";
731 static NSString *kCydiaProgressEventTypeStatus = @"Status";
732 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
735 /* Display Helpers {{{ */
736 inline float Interpolate(float begin, float end, float fraction) {
737 return (end - begin) * fraction + begin;
740 static _finline const char *StripVersion_(const char *version) {
741 const char *colon(strchr(version, ':'));
742 return colon == NULL ? version : colon + 1;
745 NSString *LocalizeSection(NSString *section) {
746 static Pcre title_r("^(.*?) \\((.*)\\)$");
747 if (title_r(section)) {
748 NSString *parent(title_r[1]);
749 NSString *child(title_r[2]);
751 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
752 LocalizeSection(parent),
753 LocalizeSection(child)
757 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
760 NSString *Simplify(NSString *title) {
761 const char *data = [title UTF8String];
762 size_t size = [title length];
764 static Pcre square_r("^\\[(.*)\\]$");
765 if (square_r(data, size))
766 return Simplify(square_r[1]);
768 static Pcre paren_r("^\\((.*)\\)$");
769 if (paren_r(data, size))
770 return Simplify(paren_r[1]);
772 static Pcre title_r("^(.*?) \\((.*)\\)$");
773 if (title_r(data, size))
774 return Simplify(title_r[1]);
780 NSString *GetLastUpdate() {
781 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
784 return UCLocalize("NEVER_OR_UNKNOWN");
786 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
787 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
789 CFRelease(formatter);
791 return [(NSString *) formatted autorelease];
794 bool isSectionVisible(NSString *section) {
795 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
796 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
797 return hidden == nil || ![hidden boolValue];
800 static NSObject *CYIOGetValue(const char *path, NSString *property) {
801 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
802 if (entry == MACH_PORT_NULL)
805 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
806 IOObjectRelease(entry);
810 return [(id) value autorelease];
813 static NSString *CYHex(NSData *data, bool reverse = false) {
817 size_t length([data length]);
818 uint8_t bytes[length];
819 [data getBytes:bytes];
821 char string[length * 2 + 1];
822 for (size_t i(0); i != length; ++i)
823 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
825 return [NSString stringWithUTF8String:string];
830 /* Delegate Prototypes {{{ */
833 @class CydiaProgressEvent;
835 @protocol DatabaseDelegate
836 - (void) repairWithSelector:(SEL)selector;
837 - (void) setConfigurationData:(NSString *)data;
838 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
841 @class CYPackageController;
843 @protocol CydiaDelegate
844 - (void) returnToCydia;
846 - (void) retainNetworkActivityIndicator;
847 - (void) releaseNetworkActivityIndicator;
848 - (void) clearPackage:(Package *)package;
849 - (void) installPackage:(Package *)package;
850 - (void) installPackages:(NSArray *)packages;
851 - (void) removePackage:(Package *)package;
852 - (void) beginUpdate;
854 - (void) distUpgrade;
858 - (void) addSource:(NSDictionary *)source;
859 - (void) addTrivialSource:(NSString *)href;
860 - (void) showSettings;
861 - (UIProgressHUD *) addProgressHUD;
862 - (void) removeProgressHUD:(UIProgressHUD *)hud;
863 - (CyteViewController *) pageForPackage:(NSString *)name;
864 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
865 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
869 /* Status Delegation {{{ */
871 public pkgAcquireStatus
874 _transient NSObject<ProgressDelegate> *delegate_;
884 void setDelegate(NSObject<ProgressDelegate> *delegate) {
885 delegate_ = delegate;
888 NSObject<ProgressDelegate> *getDelegate() const {
892 virtual bool MediaChange(std::string media, std::string drive) {
896 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
900 virtual void Fetch(pkgAcquire::ItemDesc &item) {
901 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
902 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
903 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
906 virtual void Done(pkgAcquire::ItemDesc &item) {
907 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
908 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
909 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
912 virtual void Fail(pkgAcquire::ItemDesc &item) {
914 item.Owner->Status == pkgAcquire::Item::StatIdle ||
915 item.Owner->Status == pkgAcquire::Item::StatDone
919 std::string &error(item.Owner->ErrorText);
923 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
924 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
927 virtual bool Pulse(pkgAcquire *Owner) {
928 bool value = pkgAcquireStatus::Pulse(Owner);
931 double(CurrentBytes + CurrentItems) /
932 double(TotalBytes + TotalItems)
935 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
936 [NSNumber numberWithDouble:percent], @"Percent",
938 [NSNumber numberWithDouble:CurrentBytes], @"Current",
939 [NSNumber numberWithDouble:TotalBytes], @"Total",
940 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
941 nil] waitUntilDone:YES];
943 if (value && ![delegate_ isProgressCancelled])
951 _finline bool WasCancelled() const {
955 virtual void Start() {
956 pkgAcquireStatus::Start();
957 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
960 virtual void Stop() {
961 pkgAcquireStatus::Stop();
962 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
963 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
967 /* Database Interface {{{ */
968 typedef std::map< unsigned long, _H<Source> > SourceMap;
970 @interface Database : NSObject {
977 pkgDepCache::Policy *policy_;
978 pkgRecords *records_;
979 pkgProblemResolver *resolver_;
980 pkgAcquire *fetcher_;
982 SPtr<pkgPackageManager> manager_;
983 pkgSourceList *list_;
985 SourceMap sourceMap_;
986 _H<NSMutableArray> sourceList_;
988 CFMutableArrayRef packages_;
990 _transient NSObject<DatabaseDelegate> *delegate_;
991 _transient NSObject<ProgressDelegate> *progress_;
999 std::map<const char *, _H<NSString> > sections_;
1002 + (Database *) sharedInstance;
1005 - (void) _readCydia:(NSNumber *)fd;
1006 - (void) _readStatus:(NSNumber *)fd;
1007 - (void) _readOutput:(NSNumber *)fd;
1011 - (Package *) packageWithName:(NSString *)name;
1013 - (pkgCacheFile &) cache;
1014 - (pkgDepCache::Policy *) policy;
1015 - (pkgRecords *) records;
1016 - (pkgProblemResolver *) resolver;
1017 - (pkgAcquire &) fetcher;
1018 - (pkgSourceList &) list;
1019 - (NSArray *) packages;
1020 - (NSArray *) sources;
1021 - (Source *) sourceWithKey:(NSString *)key;
1022 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1030 - (void) updateWithStatus:(Status &)status;
1032 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1034 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1035 - (NSObject<ProgressDelegate> *) progressDelegate;
1037 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1039 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1043 /* ProgressEvent Implementation {{{ */
1044 @implementation CydiaProgressEvent
1046 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1047 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1050 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1051 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1052 [event setPackage:package];
1056 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1057 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1059 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1060 NSArray *fields([description componentsSeparatedByString:@" "]);
1061 [event setItem:fields];
1063 if ([fields count] > 3) {
1064 [event setPackage:[fields objectAtIndex:2]];
1065 [event setVersion:[fields objectAtIndex:3]];
1068 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1073 + (NSArray *) _attributeKeys {
1074 return [NSArray arrayWithObjects:
1084 - (NSArray *) attributeKeys {
1085 return [[self class] _attributeKeys];
1088 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1089 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1092 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1093 if ((self = [super init]) != nil) {
1099 - (NSString *) message {
1103 - (NSString *) type {
1107 - (NSArray *) item {
1108 return (id) item_ ?: [NSNull null];
1111 - (void) setItem:(NSArray *)item {
1115 - (NSString *) package {
1116 return (id) package_ ?: [NSNull null];
1119 - (void) setPackage:(NSString *)package {
1123 - (NSString *) url {
1124 return (id) url_ ?: [NSNull null];
1127 - (void) setURL:(NSString *)url {
1131 - (void) setVersion:(NSString *)version {
1135 - (NSString *) version {
1136 return (id) version_ ?: [NSNull null];
1139 - (NSString *) compound:(NSString *)value {
1141 NSString *mode(nil); {
1142 NSString *type([self type]);
1143 if ([type isEqualToString:kCydiaProgressEventTypeError])
1144 mode = UCLocalize("ERROR");
1145 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1146 mode = UCLocalize("WARNING");
1150 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1156 - (NSString *) compoundMessage {
1157 return [self compound:[self message]];
1160 - (NSString *) compoundTitle {
1163 if (package_ == nil)
1165 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1166 title = [package name];
1170 return [self compound:title];
1176 // Cytore Definitions {{{
1177 struct PackageValue :
1180 Cytore::Offset<PackageValue> next_;
1182 uint32_t index_ : 23;
1183 uint32_t subscribed_ : 1;
1200 Cytore::Offset<PackageValue> packages_[1 << 16];
1203 static Cytore::File<MetaValue> MetaFile_;
1205 // Cytore Helper Functions {{{
1206 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1207 SplitHash nhash = { hashlittle(name, length) };
1209 PackageValue *metadata;
1211 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1212 offset: if (offset->IsNull()) {
1213 *offset = MetaFile_.New<PackageValue>(length + 1);
1214 metadata = &MetaFile_.Get(*offset);
1216 if (metadata == NULL) {
1220 metadata = new PackageValue();
1221 memset(metadata, 0, sizeof(*metadata));
1224 memcpy(metadata->name_, name, length + 1);
1225 metadata->nhash_ = nhash.u16[1];
1227 metadata = &MetaFile_.Get(*offset);
1229 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1230 offset = &metadata->next_;
1238 static void PackageImport(const void *key, const void *value, void *context) {
1239 bool &fail(*reinterpret_cast<bool *>(context));
1242 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1243 NSLog(@"failed to import package %@", key);
1247 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1248 NSDictionary *package((NSDictionary *) value);
1250 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1251 if ([subscribed boolValue] && !metadata->subscribed_)
1252 metadata->subscribed_ = true;
1254 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1255 time_t time([date timeIntervalSince1970]);
1256 if (metadata->first_ > time || metadata->first_ == 0)
1257 metadata->first_ = time;
1260 NSDate *date([package objectForKey:@"LastSeen"]);
1261 NSString *version([package objectForKey:@"LastVersion"]);
1263 if (date != nil && version != nil) {
1264 time_t time([date timeIntervalSince1970]);
1265 if (metadata->last_ < time || metadata->last_ == 0)
1266 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1267 size_t length(strlen(buffer));
1268 uint16_t vhash(hashlittle(buffer, length));
1270 size_t capped(std::min<size_t>(8, length));
1271 char *latest(buffer + length - capped);
1273 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1274 metadata->vhash_ = vhash;
1276 metadata->last_ = time;
1282 /* Source Class {{{ */
1283 @interface Source : NSObject {
1285 Database *database_;
1288 CYString depiction_;
1289 CYString description_;
1295 CYString distribution_;
1301 _H<NSString> authority_;
1303 CYString defaultIcon_;
1305 _H<NSDictionary> record_;
1309 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1311 - (NSComparisonResult) compareByName:(Source *)source;
1313 - (NSString *) depictionForPackage:(NSString *)package;
1314 - (NSString *) supportForPackage:(NSString *)package;
1316 - (NSDictionary *) record;
1319 - (NSString *) rooturi;
1320 - (NSString *) distribution;
1321 - (NSString *) type;
1324 - (NSString *) host;
1326 - (NSString *) name;
1327 - (NSString *) shortDescription;
1328 - (NSString *) label;
1329 - (NSString *) origin;
1330 - (NSString *) version;
1332 - (NSString *) defaultIcon;
1333 - (NSURL *) iconURL;
1337 @implementation Source
1341 distribution_.clear();
1346 description_.clear();
1352 defaultIcon_.clear();
1359 + (NSString *) webScriptNameForSelector:(SEL)selector {
1361 else if (selector == @selector(addSection:))
1362 return @"addSection";
1363 else if (selector == @selector(getField:))
1365 else if (selector == @selector(removeSection:))
1366 return @"removeSection";
1367 else if (selector == @selector(remove))
1373 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1374 return [self webScriptNameForSelector:selector] == nil;
1377 + (NSArray *) _attributeKeys {
1378 return [NSArray arrayWithObjects:
1389 @"shortDescription",
1396 - (NSArray *) attributeKeys {
1397 return [[self class] _attributeKeys];
1400 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1401 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1404 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1407 trusted_ = index->IsTrusted();
1409 uri_.set(pool, index->GetURI());
1410 distribution_.set(pool, index->GetDist());
1411 type_.set(pool, index->GetType());
1413 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1414 if (dindex != NULL) {
1415 base_.set(pool, dindex->MetaIndexURI(""));
1418 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1421 pkgTagFile tags(&fd);
1423 pkgTagSection section;
1430 {"default-icon", &defaultIcon_},
1431 {"depiction", &depiction_},
1432 {"description", &description_},
1434 {"origin", &origin_},
1435 {"support", &support_},
1436 {"version", &version_},
1439 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1440 const char *start, *end;
1442 if (section.Find(names[i].name_, start, end)) {
1443 CYString &value(*names[i].value_);
1444 value.set(pool, start, end - start);
1450 record_ = [Sources_ objectForKey:[self key]];
1452 NSURL *url([NSURL URLWithString:uri_]);
1456 host_ = [host_ lowercaseString];
1461 authority_ = [url path];
1464 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1465 if ((self = [super init]) != nil) {
1466 era_ = [database era];
1467 database_ = database;
1470 [self setMetaIndex:index inPool:pool];
1474 - (NSString *) getField:(NSString *)name {
1475 @synchronized (database_) {
1476 if ([database_ era] != era_ || index_ == NULL)
1479 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1484 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1489 pkgTagFile tags(&fd);
1491 pkgTagSection section;
1494 const char *start, *end;
1495 if (!section.Find([name UTF8String], start, end))
1496 return (NSString *) [NSNull null];
1498 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1501 - (NSComparisonResult) compareByName:(Source *)source {
1502 NSString *lhs = [self name];
1503 NSString *rhs = [source name];
1505 if ([lhs length] != 0 && [rhs length] != 0) {
1506 unichar lhc = [lhs characterAtIndex:0];
1507 unichar rhc = [rhs characterAtIndex:0];
1509 if (isalpha(lhc) && !isalpha(rhc))
1510 return NSOrderedAscending;
1511 else if (!isalpha(lhc) && isalpha(rhc))
1512 return NSOrderedDescending;
1515 return [lhs compare:rhs options:LaxCompareOptions_];
1518 - (NSString *) depictionForPackage:(NSString *)package {
1519 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1522 - (NSString *) supportForPackage:(NSString *)package {
1523 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1526 - (NSArray *) sections {
1527 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1530 - (void) _addSection:(NSString *)section {
1533 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1534 if (![sections containsObject:section]) {
1535 [sections addObject:section];
1539 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1544 - (bool) addSection:(NSString *)section {
1548 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1552 - (void) _removeSection:(NSString *)section {
1556 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1557 if ([sections containsObject:section]) {
1558 [sections removeObject:section];
1563 - (bool) removeSection:(NSString *)section {
1567 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1572 [Sources_ removeObjectForKey:[self key]];
1577 bool value(record_ != nil);
1578 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1582 - (NSDictionary *) record {
1590 - (NSString *) rooturi {
1594 - (NSString *) distribution {
1595 return distribution_;
1598 - (NSString *) type {
1602 - (NSString *) baseuri {
1603 return base_.empty() ? nil : (id) base_;
1606 - (NSString *) iconuri {
1607 if (NSString *base = [self baseuri])
1608 return [base stringByAppendingString:@"CydiaIcon.png"];
1613 - (NSURL *) iconURL {
1614 if (NSString *uri = [self iconuri])
1615 return [NSURL URLWithString:uri];
1619 - (NSString *) key {
1620 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1623 - (NSString *) host {
1627 - (NSString *) name {
1628 return origin_.empty() ? (id) authority_ : origin_;
1631 - (NSString *) shortDescription {
1632 return description_;
1635 - (NSString *) label {
1636 return label_.empty() ? (id) authority_ : label_;
1639 - (NSString *) origin {
1643 - (NSString *) version {
1647 - (NSString *) defaultIcon {
1648 return defaultIcon_;
1653 /* CydiaOperation Class {{{ */
1654 @interface CydiaOperation : NSObject {
1655 _H<NSString> operator_;
1656 _H<NSString> value_;
1659 - (NSString *) operator;
1660 - (NSString *) value;
1664 @implementation CydiaOperation
1666 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1667 if ((self = [super init]) != nil) {
1668 operator_ = [NSString stringWithUTF8String:_operator];
1669 value_ = [NSString stringWithUTF8String:value];
1673 + (NSArray *) _attributeKeys {
1674 return [NSArray arrayWithObjects:
1680 - (NSArray *) attributeKeys {
1681 return [[self class] _attributeKeys];
1684 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1685 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1688 - (NSString *) operator {
1692 - (NSString *) value {
1698 /* CydiaClause Class {{{ */
1699 @interface CydiaClause : NSObject {
1700 _H<NSString> package_;
1701 _H<CydiaOperation> version_;
1704 - (NSString *) package;
1705 - (CydiaOperation *) version;
1709 @implementation CydiaClause
1711 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1712 if ((self = [super init]) != nil) {
1713 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1715 if (const char *version = dep.TargetVer())
1716 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1718 version_ = (id) [NSNull null];
1722 + (NSArray *) _attributeKeys {
1723 return [NSArray arrayWithObjects:
1729 - (NSArray *) attributeKeys {
1730 return [[self class] _attributeKeys];
1733 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1734 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1737 - (NSString *) package {
1741 - (CydiaOperation *) version {
1747 /* CydiaRelation Class {{{ */
1748 @interface CydiaRelation : NSObject {
1749 _H<NSString> relationship_;
1750 _H<NSMutableArray> clauses_;
1753 - (NSString *) relationship;
1754 - (NSArray *) clauses;
1758 @implementation CydiaRelation
1760 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1761 if ((self = [super init]) != nil) {
1762 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1763 clauses_ = [NSMutableArray arrayWithCapacity:8];
1765 pkgCache::DepIterator start;
1766 pkgCache::DepIterator end;
1767 dep.GlobOr(start, end); // ++dep
1770 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1772 // yes, seriously. (wtf?)
1780 + (NSArray *) _attributeKeys {
1781 return [NSArray arrayWithObjects:
1787 - (NSArray *) attributeKeys {
1788 return [[self class] _attributeKeys];
1791 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1792 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1795 - (NSString *) relationship {
1796 return relationship_;
1799 - (NSArray *) clauses {
1803 - (void) addClause:(CydiaClause *)clause {
1804 [clauses_ addObject:clause];
1809 /* Package Class {{{ */
1810 struct ParsedPackage {
1814 CYString architecture_;
1817 CYString depiction_;
1827 @interface Package : NSObject {
1830 uint32_t essential_ : 1;
1831 uint32_t obsolete_ : 1;
1832 uint32_t ignored_ : 1;
1833 uint32_t pooled_ : 1;
1839 _transient Database *database_;
1841 pkgCache::VerIterator version_;
1842 pkgCache::PkgIterator iterator_;
1843 pkgCache::VerFileIterator file_;
1849 CYString installed_;
1851 const char *section_;
1852 _transient NSString *section$_;
1856 PackageValue *metadata_;
1857 ParsedPackage *parsed_;
1859 _H<NSMutableArray> tags_;
1862 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1863 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 - (pkgCache::PkgIterator) iterator;
1868 - (NSString *) section;
1869 - (NSString *) simpleSection;
1871 - (NSString *) longSection;
1872 - (NSString *) shortSection;
1876 - (MIMEAddress *) maintainer;
1878 - (NSString *) longDescription;
1879 - (NSString *) shortDescription;
1882 - (PackageValue *) metadata;
1885 - (bool) subscribed;
1886 - (bool) setSubscribed:(bool)subscribed;
1890 - (NSString *) latest;
1891 - (NSString *) installed;
1892 - (BOOL) uninstalled;
1895 - (BOOL) upgradableAndEssential:(BOOL)essential;
1898 - (BOOL) unfiltered;
1902 - (BOOL) halfConfigured;
1903 - (BOOL) halfInstalled;
1905 - (NSString *) mode;
1908 - (NSString *) name;
1910 - (NSString *) homepage;
1911 - (NSString *) depiction;
1912 - (MIMEAddress *) author;
1914 - (NSString *) support;
1916 - (NSArray *) files;
1917 - (NSArray *) warnings;
1918 - (NSArray *) applications;
1920 - (Source *) source;
1923 - (BOOL) matches:(NSArray *)query;
1925 - (bool) hasSupportingRole;
1926 - (BOOL) hasTag:(NSString *)tag;
1927 - (NSString *) primaryPurpose;
1928 - (NSArray *) purposes;
1929 - (bool) isCommercial;
1931 - (void) setIndex:(size_t)index;
1933 - (CYString &) cyname;
1935 - (uint32_t) compareBySection:(NSArray *)sections;
1940 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1941 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1942 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1943 - (bool) isVisibleInSection:(NSString *)section;
1944 - (bool) isVisibleInSource:(Source *)source;
1948 uint32_t PackageChangesRadix(Package *self, void *) {
1953 uint32_t timestamp : 30;
1954 uint32_t ignored : 1;
1955 uint32_t upgradable : 1;
1959 bool upgradable([self upgradableAndEssential:YES]);
1960 value.bits.upgradable = upgradable ? 1 : 0;
1963 value.bits.timestamp = 0;
1964 value.bits.ignored = [self ignored] ? 0 : 1;
1965 value.bits.upgradable = 1;
1967 value.bits.timestamp = [self seen] >> 2;
1968 value.bits.ignored = 0;
1969 value.bits.upgradable = 0;
1972 return _not(uint32_t) - value.key;
1975 uint32_t PackagePrefixRadix(Package *self, void *context) {
1976 size_t offset(reinterpret_cast<size_t>(context));
1977 CYString &name([self cyname]);
1979 size_t size(name.size());
1982 char *text(name.data());
1985 if (!isdigit(text[0]))
1989 while (size != digits && isdigit(text[digits]))
1997 if (offset == 0 && zeros != 0) {
1998 memset(data, '0', zeros);
1999 memcpy(data + zeros, text, 4 - zeros);
2001 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2002 if (size <= offset - zeros)
2005 text += offset - zeros;
2006 size -= offset - zeros;
2009 memcpy(data, text, 4);
2011 memcpy(data, text, size);
2012 memset(data + size, 0, 4 - size);
2015 for (size_t i(0); i != 4; ++i)
2016 if (isalpha(data[i]))
2024 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2026 /* XXX: ntohl may be more honest */
2027 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2030 CYString &(*PackageName)(Package *self, SEL sel);
2032 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2033 _profile(PackageNameCompare)
2034 CYString &lhi(PackageName(lhs, @selector(cyname)));
2035 CYString &rhi(PackageName(rhs, @selector(cyname)));
2036 CFStringRef lhn(lhi), rhn(rhi);
2039 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2040 else if (rhn == NULL)
2041 return NSOrderedDescending;
2043 _profile(PackageNameCompare$NumbersLast)
2044 if (!lhi.empty() && !rhi.empty()) {
2045 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2046 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2047 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2048 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2049 return lha ? NSOrderedAscending : NSOrderedDescending;
2053 CFIndex length = CFStringGetLength(lhn);
2055 _profile(PackageNameCompare$Compare)
2056 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2061 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2062 return PackageNameCompare(*lhs, *rhs, context);
2065 struct PackageNameOrdering :
2066 std::binary_function<Package *, Package *, bool>
2068 _finline bool operator ()(Package *lhs, Package *rhs) const {
2069 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2073 @implementation Package
2075 - (NSString *) description {
2076 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2081 apr_pool_destroy(pool_);
2082 if (parsed_ != NULL)
2087 + (NSString *) webScriptNameForSelector:(SEL)selector {
2089 else if (selector == @selector(clear))
2091 else if (selector == @selector(getField:))
2093 else if (selector == @selector(hasTag:))
2095 else if (selector == @selector(install))
2097 else if (selector == @selector(remove))
2103 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2104 return [self webScriptNameForSelector:selector] == nil;
2107 + (NSArray *) _attributeKeys {
2108 return [NSArray arrayWithObjects:
2129 @"shortDescription",
2142 - (NSArray *) attributeKeys {
2143 return [[self class] _attributeKeys];
2146 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2147 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2150 - (NSArray *) relations {
2151 @synchronized (database_) {
2152 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2153 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2154 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2158 - (NSString *) architecture {
2160 @synchronized (database_) {
2161 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2164 - (NSString *) getField:(NSString *)name {
2165 @synchronized (database_) {
2166 if ([database_ era] != era_ || file_.end())
2169 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2171 const char *start, *end;
2172 if (!parser.Find([name UTF8String], start, end))
2173 return (NSString *) [NSNull null];
2175 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2179 if (parsed_ != NULL)
2181 @synchronized (database_) {
2182 if ([database_ era] != era_ || file_.end())
2185 ParsedPackage *parsed(new ParsedPackage);
2188 _profile(Package$parse)
2189 pkgRecords::Parser *parser;
2191 _profile(Package$parse$Lookup)
2192 parser = &[database_ records]->Lookup(file_);
2197 _profile(Package$parse$Find)
2202 {"architecture", &parsed->architecture_},
2203 {"icon", &parsed->icon_},
2204 {"depiction", &parsed->depiction_},
2205 {"homepage", &parsed->homepage_},
2206 {"website", &website},
2207 {"bugs", &parsed->bugs_},
2208 {"support", &parsed->support_},
2209 {"sponsor", &parsed->sponsor_},
2210 {"author", &parsed->author_},
2211 {"md5sum", &parsed->md5sum_},
2214 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2215 const char *start, *end;
2217 if (parser->Find(names[i].name_, start, end)) {
2218 CYString &value(*names[i].value_);
2219 _profile(Package$parse$Value)
2220 value.set(pool_, start, end - start);
2226 _profile(Package$parse$Tagline)
2227 const char *start, *end;
2228 if (parser->ShortDesc(start, end)) {
2229 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2232 while (stop != start && stop[-1] == '\r')
2234 parsed->tagline_.set(pool_, start, stop - start);
2238 _profile(Package$parse$Retain)
2239 if (parsed->homepage_.empty())
2240 parsed->homepage_ = website;
2241 if (parsed->homepage_ == parsed->depiction_)
2242 parsed->homepage_.clear();
2247 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2248 if ((self = [super init]) != nil) {
2249 _profile(Package$initWithVersion)
2251 apr_pool_create(&pool_, NULL);
2257 database_ = database;
2258 era_ = [database era];
2262 pkgCache::PkgIterator iterator(version.ParentPkg());
2263 iterator_ = iterator;
2265 _profile(Package$initWithVersion$Version)
2266 if (!version_.end())
2267 file_ = version_.FileList();
2269 pkgCache &cache([database_ cache]);
2270 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2274 _profile(Package$initWithVersion$Cache)
2275 name_.set(NULL, iterator.Display());
2277 latest_.set(NULL, StripVersion_(version_.VerStr()));
2279 pkgCache::VerIterator current(iterator.CurrentVer());
2281 installed_.set(NULL, StripVersion_(current.VerStr()));
2284 _profile(Package$initWithVersion$Tags)
2285 pkgCache::TagIterator tag(iterator.TagList());
2287 tags_ = [NSMutableArray arrayWithCapacity:8];
2289 const char *name(tag.Name());
2290 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2292 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2293 if (strcmp(name + 6, "enduser") == 0)
2295 else if (strcmp(name + 6, "hacker") == 0)
2297 else if (strcmp(name + 6, "developer") == 0)
2299 else if (strcmp(name + 6, "cydia") == 0)
2305 if (strncmp(name, "cydia::", 7) == 0) {
2306 if (strcmp(name + 7, "essential") == 0)
2308 else if (strcmp(name + 7, "obsolete") == 0)
2313 } while (!tag.end());
2317 _profile(Package$initWithVersion$Metadata)
2318 const char *mixed(iterator.Name());
2319 size_t size(strlen(mixed));
2320 char lower[size + 1];
2322 for (size_t i(0); i != size; ++i)
2323 lower[i] = mixed[i] | 0x20;
2326 PackageValue *metadata(PackageFind(lower, size));
2327 metadata_ = metadata;
2329 id_.set(NULL, metadata->name_, size);
2331 const char *latest(version_.VerStr());
2332 size_t length(strlen(latest));
2334 uint16_t vhash(hashlittle(latest, length));
2336 size_t capped(std::min<size_t>(8, length));
2337 latest = latest + length - capped;
2339 if (metadata->first_ == 0)
2340 metadata->first_ = now_;
2342 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2343 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2344 metadata->vhash_ = vhash;
2345 metadata->last_ = now_;
2346 } else if (metadata->last_ == 0)
2347 metadata->last_ = metadata->first_;
2350 _profile(Package$initWithVersion$Section)
2351 section_ = iterator.Section();
2354 _profile(Package$initWithVersion$Flags)
2355 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2356 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2361 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2362 pkgCache::VerIterator version;
2364 _profile(Package$packageWithIterator$GetCandidateVer)
2365 version = [database policy]->GetCandidateVer(iterator);
2373 _profile(Package$packageWithIterator$Allocate)
2374 package = [Package allocWithZone:zone];
2377 _profile(Package$packageWithIterator$Initialize)
2379 initWithVersion:version
2386 _profile(Package$packageWithIterator$Autorelease)
2387 package = [package autorelease];
2393 - (pkgCache::PkgIterator) iterator {
2397 - (NSString *) section {
2398 if (section$_ == nil) {
2399 if (section_ == NULL)
2402 _profile(Package$section$mappedSectionForPointer)
2403 section$_ = [database_ mappedSectionForPointer:section_];
2408 - (NSString *) simpleSection {
2409 if (NSString *section = [self section])
2410 return Simplify(section);
2415 - (NSString *) longSection {
2416 return LocalizeSection([self section]);
2419 - (NSString *) shortSection {
2420 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2423 - (NSString *) uri {
2426 pkgIndexFile *index;
2427 pkgCache::PkgFileIterator file(file_.File());
2428 if (![database_ list].FindIndex(file, index))
2430 return [NSString stringWithUTF8String:iterator_->Path];
2431 //return [NSString stringWithUTF8String:file.Site()];
2432 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2436 - (MIMEAddress *) maintainer {
2437 @synchronized (database_) {
2438 if ([database_ era] != era_ || file_.end())
2441 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2442 const std::string &maintainer(parser->Maintainer());
2443 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2446 - (NSString *) md5sum {
2447 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2451 @synchronized (database_) {
2452 if ([database_ era] != era_ || version_.end())
2455 return version_->InstalledSize;
2458 - (NSString *) longDescription {
2459 @synchronized (database_) {
2460 if ([database_ era] != era_ || file_.end())
2463 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2464 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2466 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2467 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2468 if ([lines count] < 2)
2471 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2472 for (size_t i(1), e([lines count]); i != e; ++i) {
2473 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2474 [trimmed addObject:trim];
2477 return [trimmed componentsJoinedByString:@"\n"];
2480 - (NSString *) shortDescription {
2481 if (parsed_ != NULL)
2482 return static_cast<NSString *>(parsed_->tagline_);
2484 @synchronized (database_) {
2485 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2487 const char *start, *end;
2488 if (!parser.ShortDesc(start, end))
2491 if (end - start > 200)
2495 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2498 while (end != start && end[-1] == '\r')
2502 return [(id) CYStringCreate(start, end - start) autorelease];
2506 _profile(Package$index)
2507 CFStringRef name((CFStringRef) [self name]);
2508 if (CFStringGetLength(name) == 0)
2510 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2511 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2513 return toupper(character);
2517 - (PackageValue *) metadata {
2522 PackageValue *metadata([self metadata]);
2523 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2526 - (bool) subscribed {
2527 return [self metadata]->subscribed_;
2530 - (bool) setSubscribed:(bool)subscribed {
2531 PackageValue *metadata([self metadata]);
2532 if (metadata->subscribed_ == subscribed)
2534 metadata->subscribed_ = subscribed;
2542 - (NSString *) latest {
2546 - (NSString *) installed {
2550 - (BOOL) uninstalled {
2551 return installed_.empty();
2555 return !version_.end();
2558 - (BOOL) upgradableAndEssential:(BOOL)essential {
2559 _profile(Package$upgradableAndEssential)
2560 pkgCache::VerIterator current(iterator_.CurrentVer());
2562 return essential && essential_;
2564 return !version_.end() && version_ != current;
2568 - (BOOL) essential {
2573 return [database_ cache][iterator_].InstBroken();
2576 - (BOOL) unfiltered {
2577 _profile(Package$unfiltered$obsolete)
2578 if (_unlikely(obsolete_))
2582 _profile(Package$unfiltered$hasSupportingRole)
2583 if (_unlikely(![self hasSupportingRole]))
2591 if (![self unfiltered])
2596 _profile(Package$visible$section)
2597 section = [self section];
2600 _profile(Package$visible$isSectionVisible)
2601 if (!isSectionVisible(section))
2609 unsigned char current(iterator_->CurrentState);
2610 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2613 - (BOOL) halfConfigured {
2614 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2617 - (BOOL) halfInstalled {
2618 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2622 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2623 return state.Mode != pkgDepCache::ModeKeep;
2626 - (NSString *) mode {
2627 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2629 switch (state.Mode) {
2630 case pkgDepCache::ModeDelete:
2631 if ((state.iFlags & pkgDepCache::Purge) != 0)
2635 case pkgDepCache::ModeKeep:
2636 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2637 return @"REINSTALL";
2638 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2642 case pkgDepCache::ModeInstall:
2643 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2644 return @"REINSTALL";
2645 else*/ switch (state.Status) {
2647 return @"DOWNGRADE";
2653 return @"NEW_INSTALL";
2664 - (NSString *) name {
2665 return name_.empty() ? id_ : name_;
2668 - (UIImage *) icon {
2669 NSString *section = [self simpleSection];
2672 if (parsed_ != NULL)
2673 if (NSString *href = parsed_->icon_)
2674 if ([href hasPrefix:@"file:///"])
2675 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2676 if (icon == nil) if (section != nil)
2677 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2678 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2679 if ([dicon hasPrefix:@"file:///"])
2680 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2682 icon = [UIImage applicationImageNamed:@"unknown.png"];
2686 - (NSString *) homepage {
2687 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2690 - (NSString *) depiction {
2691 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2694 - (MIMEAddress *) sponsor {
2695 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2698 - (MIMEAddress *) author {
2699 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2702 - (NSString *) support {
2703 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2706 - (NSArray *) files {
2707 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2708 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2711 fin.open([path UTF8String]);
2716 while (std::getline(fin, line))
2717 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2722 - (NSString *) state {
2723 @synchronized (database_) {
2724 if ([database_ era] != era_ || file_.end())
2727 switch (iterator_->CurrentState) {
2728 case pkgCache::State::NotInstalled:
2729 return @"NotInstalled";
2730 case pkgCache::State::UnPacked:
2732 case pkgCache::State::HalfConfigured:
2733 return @"HalfConfigured";
2734 case pkgCache::State::HalfInstalled:
2735 return @"HalfInstalled";
2736 case pkgCache::State::ConfigFiles:
2737 return @"ConfigFiles";
2738 case pkgCache::State::Installed:
2739 return @"Installed";
2740 case pkgCache::State::TriggersAwaited:
2741 return @"TriggersAwaited";
2742 case pkgCache::State::TriggersPending:
2743 return @"TriggersPending";
2746 return (NSString *) [NSNull null];
2749 - (NSString *) selection {
2750 @synchronized (database_) {
2751 if ([database_ era] != era_ || file_.end())
2754 switch (iterator_->SelectedState) {
2755 case pkgCache::State::Unknown:
2757 case pkgCache::State::Install:
2759 case pkgCache::State::Hold:
2761 case pkgCache::State::DeInstall:
2762 return @"DeInstall";
2763 case pkgCache::State::Purge:
2767 return (NSString *) [NSNull null];
2770 - (NSArray *) warnings {
2771 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2772 const char *name(iterator_.Name());
2774 size_t length(strlen(name));
2775 if (length < 2) invalid:
2776 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2777 else for (size_t i(0); i != length; ++i)
2779 /* XXX: technically this is not allowed */
2780 (name[i] < 'A' || name[i] > 'Z') &&
2781 (name[i] < 'a' || name[i] > 'z') &&
2782 (name[i] < '0' || name[i] > '9') &&
2783 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2786 if (strcmp(name, "cydia") != 0) {
2789 bool _private = false;
2792 bool repository = [[self section] isEqualToString:@"Repositories"];
2794 if (NSArray *files = [self files])
2795 for (NSString *file in files)
2796 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2798 else if (!user && [file isEqualToString:@"/User"])
2800 else if (!_private && [file isEqualToString:@"/private"])
2802 else if (!stash && [file isEqualToString:@"/var/stash"])
2805 /* XXX: this is not sensitive enough. only some folders are valid. */
2806 if (cydia && !repository)
2807 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2809 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2811 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2813 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2816 return [warnings count] == 0 ? nil : warnings;
2819 - (NSArray *) applications {
2820 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2822 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2824 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2825 if (NSArray *files = [self files])
2826 for (NSString *file in files)
2827 if (application_r(file)) {
2828 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2829 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2830 if ([id isEqualToString:me])
2833 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2835 display = application_r[1];
2837 NSString *bundle([file stringByDeletingLastPathComponent]);
2838 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2839 if (icon == nil || [icon length] == 0)
2841 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2843 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2844 [applications addObject:application];
2846 [application addObject:id];
2847 [application addObject:display];
2848 [application addObject:url];
2851 return [applications count] == 0 ? nil : applications;
2854 - (Source *) source {
2855 if (source_ == nil) {
2856 @synchronized (database_) {
2857 if ([database_ era] != era_ || file_.end())
2858 source_ = (Source *) [NSNull null];
2860 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2864 return source_ == (Source *) [NSNull null] ? nil : source_;
2871 - (BOOL) matches:(NSArray *)query {
2872 if (query == nil || [query count] == 0)
2881 string = [self name];
2882 length = [string length];
2884 for (NSString *term in query) {
2885 range = [string rangeOfString:term options:MatchCompareOptions_];
2886 if (range.location != NSNotFound)
2887 rank_ -= 6 * 1000000 / length;
2892 length = [string length];
2894 for (NSString *term in query) {
2895 range = [string rangeOfString:term options:MatchCompareOptions_];
2896 if (range.location != NSNotFound)
2897 rank_ -= 6 * 1000000 / length;
2901 string = [self shortDescription];
2902 length = [string length];
2903 NSUInteger stop(std::min<NSUInteger>(length, 200));
2905 for (NSString *term in query) {
2906 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2907 if (range.location != NSNotFound)
2908 rank_ -= 2 * 100000;
2914 - (bool) hasSupportingRole {
2919 if ([Role_ isEqualToString:@"User"])
2923 if ([Role_ isEqualToString:@"Hacker"])
2927 if ([Role_ isEqualToString:@"Developer"])
2932 - (NSArray *) tags {
2936 - (BOOL) hasTag:(NSString *)tag {
2937 return tags_ == nil ? NO : [tags_ containsObject:tag];
2940 - (NSString *) primaryPurpose {
2941 for (NSString *tag in (NSArray *) tags_)
2942 if ([tag hasPrefix:@"purpose::"])
2943 return [tag substringFromIndex:9];
2947 - (NSArray *) purposes {
2948 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2949 for (NSString *tag in (NSArray *) tags_)
2950 if ([tag hasPrefix:@"purpose::"])
2951 [purposes addObject:[tag substringFromIndex:9]];
2952 return [purposes count] == 0 ? nil : purposes;
2955 - (bool) isCommercial {
2956 return [self hasTag:@"cydia::commercial"];
2959 - (void) setIndex:(size_t)index {
2960 if (metadata_->index_ != index)
2961 metadata_->index_ = index;
2964 - (CYString &) cyname {
2965 return name_.empty() ? id_ : name_;
2968 - (uint32_t) compareBySection:(NSArray *)sections {
2969 NSString *section([self section]);
2970 for (size_t i(0), e([sections count]); i != e; ++i) {
2971 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2975 return _not(uint32_t);
2979 @synchronized (database_) {
2980 pkgProblemResolver *resolver = [database_ resolver];
2981 resolver->Clear(iterator_);
2983 pkgCacheFile &cache([database_ cache]);
2984 cache->SetReInstall(iterator_, false);
2985 cache->MarkKeep(iterator_, false);
2989 @synchronized (database_) {
2990 pkgProblemResolver *resolver = [database_ resolver];
2991 resolver->Clear(iterator_);
2992 resolver->Protect(iterator_);
2994 pkgCacheFile &cache([database_ cache]);
2995 cache->SetReInstall(iterator_, false);
2996 cache->MarkInstall(iterator_, false);
2998 pkgDepCache::StateCache &state((*cache)[iterator_]);
2999 if (!state.Install())
3000 cache->SetReInstall(iterator_, true);
3004 @synchronized (database_) {
3005 pkgProblemResolver *resolver = [database_ resolver];
3006 resolver->Clear(iterator_);
3007 resolver->Remove(iterator_);
3008 resolver->Protect(iterator_);
3010 pkgCacheFile &cache([database_ cache]);
3011 cache->SetReInstall(iterator_, false);
3012 cache->MarkDelete(iterator_, true);
3015 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
3016 _profile(Package$isUnfilteredAndSearchedForBy)
3019 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3020 value &= [self unfiltered];
3023 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3024 value &= [self matches:query];
3031 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3032 if ([search length] == 0)
3035 _profile(Package$isUnfilteredAndSelectedForBy)
3038 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3039 value &= [self unfiltered];
3042 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3043 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3050 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3051 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3054 - (bool) isVisibleInSection:(NSString *)name {
3055 NSString *section([self section]);
3059 section == nil && [name length] == 0 ||
3060 [name isEqualToString:section]
3061 ) && [self visible];
3064 - (bool) isVisibleInSource:(Source *)source {
3065 return [self source] == source && [self visible];
3070 /* Section Class {{{ */
3071 @interface Section : NSObject {
3076 _H<NSString> localized_;
3079 - (NSComparisonResult) compareByLocalized:(Section *)section;
3080 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3081 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3082 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3083 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3084 - (NSString *) name;
3091 - (void) addToCount;
3093 - (void) setCount:(size_t)count;
3094 - (NSString *) localized;
3098 @implementation Section
3100 - (NSComparisonResult) compareByLocalized:(Section *)section {
3101 NSString *lhs(localized_);
3102 NSString *rhs([section localized]);
3104 /*if ([lhs length] != 0 && [rhs length] != 0) {
3105 unichar lhc = [lhs characterAtIndex:0];
3106 unichar rhc = [rhs characterAtIndex:0];
3108 if (isalpha(lhc) && !isalpha(rhc))
3109 return NSOrderedAscending;
3110 else if (!isalpha(lhc) && isalpha(rhc))
3111 return NSOrderedDescending;
3114 return [lhs compare:rhs options:LaxCompareOptions_];
3117 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3118 if ((self = [self initWithName:name localize:NO]) != nil) {
3119 if (localized != nil)
3120 localized_ = localized;
3124 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3125 return [self initWithName:name row:0 localize:localize];
3128 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3129 if ((self = [super init]) != nil) {
3134 localized_ = LocalizeSection(name_);
3138 /* XXX: localize the index thingees */
3139 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3140 if ((self = [super init]) != nil) {
3141 name_ = [NSString stringWithCharacters:&index length:1];
3147 - (NSString *) name {
3167 - (void) addToCount {
3171 - (void) setCount:(size_t)count {
3175 - (NSString *) localized {
3182 class CydiaLogCleaner :
3183 public pkgArchiveCleaner
3186 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3191 /* Database Implementation {{{ */
3192 @implementation Database
3194 + (Database *) sharedInstance {
3195 static _H<Database> instance;
3196 if (instance == nil)
3197 instance = [[[Database alloc] init] autorelease];
3205 - (void) releasePackages {
3206 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3207 CFArrayRemoveAllValues(packages_);
3211 // XXX: actually implement this thing
3213 [self releasePackages];
3214 apr_pool_destroy(pool_);
3215 NSRecycleZone(zone_);
3219 - (void) _readCydia:(NSNumber *)fd {
3220 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3221 std::istream is(&ib);
3224 static Pcre finish_r("^finish:([^:]*)$");
3226 while (std::getline(is, line)) {
3227 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3229 const char *data(line.c_str());
3230 size_t size = line.size();
3231 lprintf("C:%s\n", data);
3233 if (finish_r(data, size)) {
3234 NSString *finish = finish_r[1];
3235 int index = [Finishes_ indexOfObject:finish];
3236 if (index != INT_MAX && index > Finish_)
3246 - (void) _readStatus:(NSNumber *)fd {
3247 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3248 std::istream is(&ib);
3251 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3252 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3254 while (std::getline(is, line)) {
3255 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3257 const char *data(line.c_str());
3258 size_t size(line.size());
3259 lprintf("S:%s\n", data);
3261 if (conffile_r(data, size)) {
3262 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3263 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3264 } else if (strncmp(data, "status: ", 8) == 0) {
3265 // status: <package>: {unpacked,half-configured,installed}
3266 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3267 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3268 } else if (strncmp(data, "processing: ", 12) == 0) {
3269 // processing: configure: config-test
3270 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3271 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3272 } else if (pmstatus_r(data, size)) {
3273 std::string type([pmstatus_r[1] UTF8String]);
3275 NSString *package = pmstatus_r[2];
3276 if ([package isEqualToString:@"dpkg-exec"])
3279 float percent([pmstatus_r[3] floatValue]);
3280 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3282 NSString *string = pmstatus_r[4];
3284 if (type == "pmerror") {
3285 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3286 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3287 } else if (type == "pmstatus") {
3288 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3289 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3290 } else if (type == "pmconffile")
3291 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3293 lprintf("E:unknown pmstatus\n");
3295 lprintf("E:unknown status\n");
3303 - (void) _readOutput:(NSNumber *)fd {
3304 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3305 std::istream is(&ib);
3308 while (std::getline(is, line)) {
3309 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3311 lprintf("O:%s\n", line.c_str());
3313 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3314 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3326 - (Package *) packageWithName:(NSString *)name {
3329 @synchronized (self) {
3330 if (static_cast<pkgDepCache *>(cache_) == NULL)
3332 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3333 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3337 if ((self = [super init]) != nil) {
3344 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3345 apr_pool_create(&pool_, NULL);
3347 size_t capacity(MetaFile_->active_);
3353 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3354 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3358 _assert(pipe(fds) != -1);
3361 _config->Set("APT::Keep-Fds::", cydiafd_);
3362 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3365 detachNewThreadSelector:@selector(_readCydia:)
3367 withObject:[NSNumber numberWithInt:fds[0]]
3370 _assert(pipe(fds) != -1);
3374 detachNewThreadSelector:@selector(_readStatus:)
3376 withObject:[NSNumber numberWithInt:fds[0]]
3379 _assert(pipe(fds) != -1);
3380 _assert(dup2(fds[0], 0) != -1);
3381 _assert(close(fds[0]) != -1);
3383 input_ = fdopen(fds[1], "a");
3385 _assert(pipe(fds) != -1);
3386 _assert(dup2(fds[1], 1) != -1);
3387 _assert(close(fds[1]) != -1);
3390 detachNewThreadSelector:@selector(_readOutput:)
3392 withObject:[NSNumber numberWithInt:fds[0]]
3397 - (pkgCacheFile &) cache {
3401 - (pkgDepCache::Policy *) policy {
3405 - (pkgRecords *) records {
3409 - (pkgProblemResolver *) resolver {
3413 - (pkgAcquire &) fetcher {
3417 - (pkgSourceList &) list {
3421 - (NSArray *) packages {
3422 return (NSArray *) packages_;
3425 - (NSArray *) sources {
3429 - (Source *) sourceWithKey:(NSString *)key {
3430 for (Source *source in [self sources]) {
3431 if ([[source key] isEqualToString:key])
3436 - (bool) popErrorWithTitle:(NSString *)title {
3439 while (!_error->empty()) {
3441 bool warning(!_error->PopMessage(error));
3446 size_t size(error.size());
3447 if (size == 0 || error[size - 1] != '\n')
3449 error.resize(size - 1);
3452 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3454 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3455 if (warning && no_pubkey(error.c_str()))
3458 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3464 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3465 return [self popErrorWithTitle:title] || !success;
3468 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3469 @synchronized (self) {
3472 [self releasePackages];
3475 [sourceList_ removeAllObjects];
3495 apr_pool_clear(pool_);
3497 NSRecycleZone(zone_);
3498 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3500 int chk(creat("/tmp/cydia.chk", 0644));
3504 if (invocation != nil)
3505 [invocation invoke];
3507 NSString *title(UCLocalize("DATABASE"));
3510 OpProgress progress;
3511 while (!cache_.Open(progress, true)) { pop:
3513 bool warning(!_error->PopMessage(error));
3514 lprintf("cache_.Open():[%s]\n", error.c_str());
3516 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3517 [delegate_ repairWithSelector:@selector(configure)];
3518 else if (error == "The package lists or status file could not be parsed or opened.")
3519 [delegate_ repairWithSelector:@selector(update)];
3520 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3521 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3522 // else if (error == "Malformed Status line")
3523 // else if (error == "The list of sources could not be read.")
3525 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3535 unlink("/tmp/cydia.chk");
3537 now_ = [[NSDate date] timeIntervalSince1970];
3539 policy_ = new pkgDepCache::Policy();
3540 records_ = new pkgRecords(cache_);
3541 resolver_ = new pkgProblemResolver(cache_);
3542 fetcher_ = new pkgAcquire(&status_);
3545 list_ = new pkgSourceList();
3546 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3549 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3550 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3554 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3557 if (cache_->BrokenCount() != 0) {
3558 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3561 if (cache_->BrokenCount() != 0) {
3562 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3566 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3570 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3571 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3572 [sourceList_ addObject:object];
3574 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3575 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3576 // XXX: this could be more intelligent
3577 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3578 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3580 sourceMap_[cached->ID] = object;
3585 /*std::vector<Package *> packages;
3586 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3591 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3592 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3593 //packages.push_back(package);
3594 CFArrayAppendValue(packages_, CFRetain(package));
3598 /*if (packages.empty())
3599 packages_ = [[NSArray alloc] init];
3601 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3604 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3605 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3606 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3614 /*if (!packages.empty())
3615 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3616 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3618 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3620 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3622 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3626 size_t count(CFArrayGetCount(packages_));
3627 MetaFile_->active_ = count;
3629 for (size_t index(0); index != count; ++index)
3630 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3637 @synchronized (self) {
3639 resolver_ = new pkgProblemResolver(cache_);
3641 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3642 if (!cache_[iterator].Keep())
3643 cache_->MarkKeep(iterator, false);
3644 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3645 cache_->SetReInstall(iterator, false);
3648 - (void) configure {
3649 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3651 system([dpkg UTF8String]);
3656 // XXX: I don't remember this condition
3661 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3663 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3665 if ([self popErrorWithTitle:title])
3669 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3671 CydiaLogCleaner cleaner;
3672 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3679 fetcher_->Shutdown();
3681 pkgRecords records(cache_);
3683 lock_ = new FileFd();
3684 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3686 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3688 if ([self popErrorWithTitle:title])
3692 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3695 manager_ = (_system->CreatePM(cache_));
3696 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3703 bool substrate(RestartSubstrate_);
3704 RestartSubstrate_ = false;
3706 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3708 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3710 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3712 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3713 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3716 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3718 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3720 [self popErrorWithTitle:title];
3724 bool failed = false;
3725 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3726 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3728 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3734 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3742 RestartSubstrate_ = true;
3745 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3747 if (_error->PendingError()) {
3752 if (result == pkgPackageManager::Failed) {
3757 if (result != pkgPackageManager::Completed) {
3762 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3764 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3766 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3767 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3770 if (![before isEqualToArray:after])
3775 NSString *title(UCLocalize("UPGRADE"));
3776 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3782 [self updateWithStatus:status_];
3785 - (void) updateWithStatus:(Status &)status {
3786 NSString *title(UCLocalize("REFRESHING_DATA"));
3789 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3793 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3794 if ([self popErrorWithTitle:title])
3797 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3799 bool success(ListUpdate(status, list, PulseInterval_));
3800 if (status.WasCancelled())
3803 [self popErrorWithTitle:title forOperation:success];
3804 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3808 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3811 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3812 delegate_ = delegate;
3815 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3816 progress_ = delegate;
3817 status_.setDelegate(delegate);
3820 - (NSObject<ProgressDelegate> *) progressDelegate {
3824 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3825 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3826 return i == sourceMap_.end() ? nil : i->second;
3829 - (NSString *) mappedSectionForPointer:(const char *)section {
3830 _H<NSString> *mapped;
3832 _profile(Database$mappedSectionForPointer$Cache)
3833 mapped = §ions_[section];
3836 if (*mapped == NULL) {
3837 size_t length(strlen(section));
3838 char spaced[length + 1];
3840 _profile(Database$mappedSectionForPointer$Replace)
3841 for (size_t index(0); index != length; ++index)
3842 spaced[index] = section[index] == '_' ? ' ' : section[index];
3843 spaced[length] = '\0';
3848 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3849 string = [NSString stringWithUTF8String:spaced];
3852 _profile(Database$mappedSectionForPointer$Map)
3853 string = [SectionMap_ objectForKey:string] ?: string;
3863 static _H<NSMutableSet> Diversions_;
3865 @interface Diversion : NSObject {
3868 _H<NSString> format_;
3873 @implementation Diversion
3875 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3876 if ((self = [super init]) != nil) {
3877 pattern_ = [from UTF8String];
3883 - (NSString *) divert:(NSString *)url {
3884 return !pattern_(url) ? nil : pattern_->*format_;
3887 + (NSURL *) divertURL:(NSURL *)url {
3889 NSString *href([url absoluteString]);
3891 for (Diversion *diversion in (id) Diversions_)
3892 if (NSString *diverted = [diversion divert:href]) {
3894 NSLog(@"div: %@", diverted);
3896 url = [NSURL URLWithString:diverted];
3903 - (NSString *) key {
3907 - (NSUInteger) hash {
3911 - (BOOL) isEqual:(Diversion *)object {
3912 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3917 @interface CydiaObject : NSObject {
3918 _H<IndirectDelegate> indirect_;
3919 _transient id delegate_;
3922 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3926 @interface CydiaWebViewController : CyteWebViewController {
3927 _H<CydiaObject> cydia_;
3930 + (void) addDiversion:(Diversion *)diversion;
3934 /* Web Scripting {{{ */
3935 @implementation CydiaObject
3937 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3938 if ((self = [super init]) != nil) {
3939 indirect_ = indirect;
3943 - (void) setDelegate:(id)delegate {
3944 delegate_ = delegate;
3947 + (NSArray *) _attributeKeys {
3948 return [NSArray arrayWithObjects:
3965 - (NSArray *) attributeKeys {
3966 return [[self class] _attributeKeys];
3969 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3970 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3973 - (NSString *) version {
3977 - (NSString *) device {
3978 return [[UIDevice currentDevice] uniqueIdentifier];
3981 - (NSString *) firmware {
3982 return [[UIDevice currentDevice] systemVersion];
3985 - (NSString *) hostname {
3986 return [[UIDevice currentDevice] name];
3989 - (NSString *) idiom {
3990 return (id) Idiom_ ?: [NSNull null];
3993 - (NSString *) plmn {
3994 return (id) PLMN_ ?: [NSNull null];
3997 - (NSString *) bbsnum {
3998 return (id) BBSNum_ ?: [NSNull null];
4001 - (NSString *) ecid {
4002 return (id) ChipID_ ?: [NSNull null];
4005 - (NSString *) serial {
4006 return SerialNumber_;
4009 - (NSString *) role {
4010 return (id) Role_ ?: [NSNull null];
4013 - (NSString *) model {
4014 return [NSString stringWithUTF8String:Machine_];
4017 - (NSString *) token {
4018 return (id) Token_ ?: [NSNull null];
4021 + (NSString *) webScriptNameForSelector:(SEL)selector {
4023 else if (selector == @selector(addBridgedHost:))
4024 return @"addBridgedHost";
4025 else if (selector == @selector(addInsecureHost:))
4026 return @"addInsecureHost";
4027 else if (selector == @selector(addInternalRedirect::))
4028 return @"addInternalRedirect";
4029 else if (selector == @selector(addPipelinedHost:scheme:))
4030 return @"addPipelinedHost";
4031 else if (selector == @selector(addSource:::))
4032 return @"addSource";
4033 else if (selector == @selector(addTokenHost:))
4034 return @"addTokenHost";
4035 else if (selector == @selector(addTrivialSource:))
4036 return @"addTrivialSource";
4037 else if (selector == @selector(close))
4039 else if (selector == @selector(du:))
4041 else if (selector == @selector(stringWithFormat:arguments:))
4043 else if (selector == @selector(getAllSources))
4044 return @"getAllSourcs";
4045 else if (selector == @selector(getKernelNumber:))
4046 return @"getKernelNumber";
4047 else if (selector == @selector(getKernelString:))
4048 return @"getKernelString";
4049 else if (selector == @selector(getInstalledPackages))
4050 return @"getInstalledPackages";
4051 else if (selector == @selector(getIORegistryEntry::))
4052 return @"getIORegistryEntry";
4053 else if (selector == @selector(getLocaleIdentifier))
4054 return @"getLocaleIdentifier";
4055 else if (selector == @selector(getPreferredLanguages))
4056 return @"getPreferredLanguages";
4057 else if (selector == @selector(getPackageById:))
4058 return @"getPackageById";
4059 else if (selector == @selector(getMetadataKeys))
4060 return @"getMetadataKeys";
4061 else if (selector == @selector(getMetadataValue:))
4062 return @"getMetadataValue";
4063 else if (selector == @selector(getSessionValue:))
4064 return @"getSessionValue";
4065 else if (selector == @selector(installPackages:))
4066 return @"installPackages";
4067 else if (selector == @selector(localizedStringForKey:value:table:))
4069 else if (selector == @selector(popViewController:))
4070 return @"popViewController";
4071 else if (selector == @selector(refreshSources))
4072 return @"refreshSources";
4073 else if (selector == @selector(removeButton))
4074 return @"removeButton";
4075 else if (selector == @selector(saveConfig))
4076 return @"saveConfig";
4077 else if (selector == @selector(setCydiaSource:))
4078 return @"setCydiaSource";
4079 else if (selector == @selector(setMetadataValue::))
4080 return @"setMetadataValue";
4081 else if (selector == @selector(setSessionValue::))
4082 return @"setSessionValue";
4083 else if (selector == @selector(substitutePackageNames:))
4084 return @"substitutePackageNames";
4085 else if (selector == @selector(scrollToBottom:))
4086 return @"scrollToBottom";
4087 else if (selector == @selector(setAllowsNavigationAction:))
4088 return @"setAllowsNavigationAction";
4089 else if (selector == @selector(setBadgeValue:))
4090 return @"setBadgeValue";
4091 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4092 return @"setButtonImage";
4093 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4094 return @"setButtonTitle";
4095 else if (selector == @selector(setHidesBackButton:))
4096 return @"setHidesBackButton";
4097 else if (selector == @selector(setHidesNavigationBar:))
4098 return @"setHidesNavigationBar";
4099 else if (selector == @selector(setNavigationBarStyle:))
4100 return @"setNavigationBarStyle";
4101 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4102 return @"setNavigationBarTintColor";
4103 else if (selector == @selector(setPasteboardString:))
4104 return @"setPasteboardString";
4105 else if (selector == @selector(setPasteboardURL:))
4106 return @"setPasteboardURL";
4107 else if (selector == @selector(setToken:))
4109 else if (selector == @selector(setViewportWidth:))
4110 return @"setViewportWidth";
4111 else if (selector == @selector(statfs:))
4113 else if (selector == @selector(supports:))
4115 else if (selector == @selector(unload))
4121 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4122 return [self webScriptNameForSelector:selector] == nil;
4125 - (BOOL) supports:(NSString *)feature {
4126 return [feature isEqualToString:@"window.open"];
4130 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4133 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4134 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4137 - (NSNumber *) getKernelNumber:(NSString *)name {
4138 const char *string([name UTF8String]);
4141 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4142 return (id) [NSNull null];
4144 if (size != sizeof(int))
4145 return (id) [NSNull null];
4148 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4149 return (id) [NSNull null];
4151 return [NSNumber numberWithInt:value];
4154 - (NSString *) getKernelString:(NSString *)name {
4155 const char *string([name UTF8String]);
4158 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4159 return (id) [NSNull null];
4161 char value[size + 1];
4162 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4163 return (id) [NSNull null];
4165 // XXX: just in case you request something ludicrous
4168 return [NSString stringWithCString:value];
4171 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4172 NSObject *value(CYIOGetValue([path UTF8String], entry));
4175 if ([value isKindOfClass:[NSData class]])
4176 value = CYHex((NSData *) value);
4181 - (void) _setCydiaSource:(NSString *)source {
4182 @synchronized (HostConfig_) {
4183 CydiaSource_ = source;
4184 [Metadata_ setObject:source forKey:@"CydiaSource"];
4190 - (void) setCydiaSource:(NSString *)source {
4191 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4194 - (NSString *) cydiaSource {
4195 @synchronized (HostConfig_) {
4196 return (id) CydiaSource_ ?: [NSNull null];
4200 - (NSArray *) getMetadataKeys {
4201 @synchronized (Values_) {
4202 return [Values_ allKeys];
4205 - (id) getMetadataValue:(NSString *)key {
4206 @synchronized (Values_) {
4207 return [Values_ objectForKey:key];
4210 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4211 @synchronized (Values_) {
4212 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4213 [Values_ removeObjectForKey:key];
4215 [Values_ setObject:value forKey:key];
4217 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4220 - (id) getSessionValue:(NSString *)key {
4221 @synchronized (SessionData_) {
4222 return [SessionData_ objectForKey:key];
4225 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4226 @synchronized (SessionData_) {
4227 if (value == (id) [WebUndefined undefined])
4228 [SessionData_ removeObjectForKey:key];
4230 [SessionData_ setObject:value forKey:key];
4233 - (void) addBridgedHost:(NSString *)host {
4234 @synchronized (HostConfig_) {
4235 [BridgedHosts_ addObject:host];
4238 - (void) addInsecureHost:(NSString *)host {
4239 @synchronized (HostConfig_) {
4240 [InsecureHosts_ addObject:host];
4243 - (void) addTokenHost:(NSString *)host {
4244 @synchronized (HostConfig_) {
4245 [TokenHosts_ addObject:host];
4248 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4249 @synchronized (HostConfig_) {
4250 if (scheme != (id) [WebUndefined undefined])
4251 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4253 [PipelinedHosts_ addObject:host];
4256 - (void) popViewController:(NSNumber *)value {
4257 if (value == (id) [WebUndefined undefined])
4258 value = [NSNumber numberWithBool:YES];
4259 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4262 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4263 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4265 for (NSString *section in sections)
4266 [array addObject:section];
4268 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4271 distribution, @"Distribution",
4273 nil] waitUntilDone:NO];
4276 - (void) addTrivialSource:(NSString *)href {
4277 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4280 - (void) refreshSources {
4281 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4284 - (void) saveConfig {
4285 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4288 - (NSArray *) getAllSources {
4289 return [[Database sharedInstance] sources];
4292 - (NSArray *) getInstalledPackages {
4293 Database *database([Database sharedInstance]);
4294 @synchronized (database) {
4295 NSArray *packages([database packages]);
4296 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4297 for (Package *package in packages)
4298 if (![package uninstalled])
4299 [installed addObject:package];
4303 - (Package *) getPackageById:(NSString *)id {
4304 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4308 return (Package *) [NSNull null];
4311 - (NSString *) getLocaleIdentifier {
4312 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4315 - (NSArray *) getPreferredLanguages {
4319 - (NSArray *) statfs:(NSString *)path {
4322 if (path == nil || statfs([path UTF8String], &stat) == -1)
4325 return [NSArray arrayWithObjects:
4326 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4327 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4328 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4332 - (NSNumber *) du:(NSString *)path {
4333 NSNumber *value(nil);
4336 _assert(pipe(fds) != -1);
4338 pid_t pid(ExecFork());
4340 _assert(dup2(fds[1], 1) != -1);
4341 _assert(close(fds[0]) != -1);
4342 _assert(close(fds[1]) != -1);
4343 /* XXX: this should probably not use du */
4344 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4349 _assert(close(fds[1]) != -1);
4351 if (FILE *du = fdopen(fds[0], "r")) {
4353 while (fgets(line, sizeof(line), du) != NULL) {
4354 size_t length(strlen(line));
4355 while (length != 0 && line[length - 1] == '\n')
4356 line[--length] = '\0';
4357 if (char *tab = strchr(line, '\t')) {
4359 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4364 } else _assert(close(fds[0]));
4368 if (waitpid(pid, &status, 0) == -1)
4371 else _assert(false);
4377 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4380 - (void) installPackages:(NSArray *)packages {
4381 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4384 - (NSString *) substitutePackageNames:(NSString *)message {
4385 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4386 for (size_t i(0), e([words count]); i != e; ++i) {
4387 NSString *word([words objectAtIndex:i]);
4388 if (Package *package = [[Database sharedInstance] packageWithName:word])
4389 [words replaceObjectAtIndex:i withObject:[package name]];
4392 return [words componentsJoinedByString:@" "];
4395 - (void) removeButton {
4396 [indirect_ removeButton];
4399 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4400 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4403 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4404 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4407 - (void) setBadgeValue:(id)value {
4408 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4411 - (void) setAllowsNavigationAction:(NSString *)value {
4412 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4415 - (void) setHidesBackButton:(NSString *)value {
4416 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4419 - (void) setHidesNavigationBar:(NSString *)value {
4420 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4423 - (void) setNavigationBarStyle:(NSString *)value {
4424 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4427 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4428 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4429 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4430 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4433 - (void) setPasteboardString:(NSString *)value {
4434 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4437 - (void) setPasteboardURL:(NSString *)value {
4438 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4441 - (void) _setToken:(NSString *)token {
4445 [Metadata_ removeObjectForKey:@"Token"];
4447 [Metadata_ setObject:Token_ forKey:@"Token"];
4452 - (void) setToken:(NSString *)token {
4453 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4456 - (void) scrollToBottom:(NSNumber *)animated {
4457 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4460 - (void) setViewportWidth:(float)width {
4461 [indirect_ setViewportWidthOnMainThread:width];
4464 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4465 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4466 unsigned count([arguments count]);
4468 for (unsigned i(0); i != count; ++i)
4469 values[i] = [arguments objectAtIndex:i];
4470 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4473 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4474 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4476 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4478 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4484 @interface NSURL (CydiaSecure)
4487 @implementation NSURL (CydiaSecure)
4489 - (bool) isCydiaSecure {
4490 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4493 @synchronized (HostConfig_) {
4494 if ([InsecureHosts_ containsObject:[self host]])
4503 /* Cydia Browser Controller {{{ */
4504 @implementation CydiaWebViewController
4506 - (NSURL *) navigationURL {
4507 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4510 + (void) _initialize {
4511 [super _initialize];
4513 Diversions_ = [NSMutableSet setWithCapacity:0];
4516 + (void) addDiversion:(Diversion *)diversion {
4517 [Diversions_ addObject:diversion];
4520 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4521 [super webView:view didClearWindowObject:window forFrame:frame];
4523 WebDataSource *source([frame dataSource]);
4524 NSURLResponse *response([source response]);
4525 NSURL *url([response URL]);
4526 NSString *scheme([[url scheme] lowercaseString]);
4528 bool bridged(false);
4530 @synchronized (HostConfig_) {
4531 if ([scheme isEqualToString:@"file"])
4533 else if ([scheme isEqualToString:@"https"])
4534 if ([BridgedHosts_ containsObject:[url host]])
4539 [window setValue:cydia_ forKey:@"cydia"];
4542 - (void) _setupMail:(MFMailComposeViewController *)controller {
4543 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4545 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4546 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4549 - (NSURL *) URLWithURL:(NSURL *)url {
4550 return [Diversion divertURL:url];
4553 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4554 NSURL *url([request URL]);
4555 NSString *host([url host]);
4557 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4559 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4560 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4561 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4562 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4567 @synchronized (HostConfig_) {
4568 bridged = [BridgedHosts_ containsObject:host];
4569 token = [TokenHosts_ containsObject:host];
4572 if ([url isCydiaSecure]) {
4574 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4575 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4577 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4578 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4585 - (void) setDelegate:(id)delegate {
4586 [super setDelegate:delegate];
4587 [cydia_ setDelegate:delegate];
4590 - (NSString *) applicationNameForUserAgent {
4591 NSString *application([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
4594 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4596 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4597 if (Product_ != nil)
4598 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4604 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4605 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4611 @interface AppCacheController : CydiaWebViewController {
4616 @implementation AppCacheController
4618 - (void) didReceiveMemoryWarning {
4625 @interface NSObject (CydiaScript)
4626 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4629 @implementation NSObject (CydiaScript)
4631 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4637 @implementation NSArray (CydiaScript)
4639 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4640 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4641 for (size_t i(0), e([self count]); i != e; ++i)
4642 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4648 @implementation NSDictionary (CydiaScript)
4650 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4651 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4653 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4660 /* Confirmation Controller {{{ */
4661 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4662 if (!iterator.end())
4663 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4664 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4666 pkgCache::PkgIterator package(dep.TargetPkg());
4669 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4676 @protocol ConfirmationControllerDelegate
4677 - (void) cancelAndClear:(bool)clear;
4678 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4682 @interface ConfirmationController : CydiaWebViewController {
4683 _transient Database *database_;
4685 _H<UIAlertView> essential_;
4687 _H<NSDictionary> changes_;
4688 _H<NSMutableArray> issues_;
4689 _H<NSDictionary> sizes_;
4694 - (id) initWithDatabase:(Database *)database;
4698 @implementation ConfirmationController
4702 RestartSubstrate_ = true;
4703 [delegate_ confirmWithNavigationController:[self navigationController]];
4706 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4707 NSString *context([alert context]);
4709 if ([context isEqualToString:@"remove"]) {
4710 if (button == [alert cancelButtonIndex])
4711 [self dismissModalViewControllerAnimated:YES];
4712 else if (button == [alert firstOtherButtonIndex]) {
4716 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4717 } else if ([context isEqualToString:@"unable"]) {
4718 [self dismissModalViewControllerAnimated:YES];
4719 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4721 [super alertView:alert clickedButtonAtIndex:button];
4725 - (void) _doContinue {
4726 [delegate_ cancelAndClear:NO];
4727 [self dismissModalViewControllerAnimated:YES];
4730 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4731 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4735 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4736 [super webView:view didClearWindowObject:window forFrame:frame];
4738 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4739 (id) changes_, @"changes",
4740 (id) issues_, @"issues",
4741 (id) sizes_, @"sizes",
4743 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4746 - (id) initWithDatabase:(Database *)database {
4747 if ((self = [super init]) != nil) {
4748 database_ = database;
4750 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4751 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4752 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4753 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4754 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4758 pkgCacheFile &cache([database_ cache]);
4759 NSArray *packages([database_ packages]);
4760 pkgDepCache::Policy *policy([database_ policy]);
4762 issues_ = [NSMutableArray arrayWithCapacity:4];
4764 for (Package *package in packages) {
4765 pkgCache::PkgIterator iterator([package iterator]);
4766 NSString *name([package id]);
4768 if ([package broken]) {
4769 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4771 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4773 reasons, @"reasons",
4776 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4780 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4781 pkgCache::DepIterator start;
4782 pkgCache::DepIterator end;
4783 dep.GlobOr(start, end); // ++dep
4785 if (!cache->IsImportantDep(end))
4787 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4790 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4792 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4793 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4794 clauses, @"clauses",
4798 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4800 pkgCache::PkgIterator target(start.TargetPkg());
4801 if (target->ProvidesList != 0)
4802 reason = @"missing";
4804 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4806 reason = @"installed";
4807 installed = [NSString stringWithUTF8String:ver.VerStr()];
4808 } else if (!cache[target].CandidateVerIter(cache).end())
4809 reason = @"uninstalled";
4810 else if (target->ProvidesList == 0)
4811 reason = @"uninstallable";
4813 reason = @"virtual";
4816 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4817 [NSString stringWithUTF8String:start.CompType()], @"operator",
4818 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4821 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4822 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4823 version, @"version",
4825 installed, @"installed",
4828 // yes, seriously. (wtf?)
4836 pkgDepCache::StateCache &state(cache[iterator]);
4838 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4840 if (state.NewInstall())
4841 [installs addObject:name];
4842 // XXX: else if (state.Install())
4843 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4844 [reinstalls addObject:name];
4845 // XXX: move before previous if
4846 else if (state.Upgrade())
4847 [upgrades addObject:name];
4848 else if (state.Downgrade())
4849 [downgrades addObject:name];
4850 else if (!state.Delete())
4851 // XXX: _assert(state.Keep());
4853 else if (special_r(name))
4854 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4855 [NSNull null], @"package",
4856 [NSArray arrayWithObjects:
4857 [NSDictionary dictionaryWithObjectsAndKeys:
4858 @"Conflicts", @"relationship",
4859 [NSArray arrayWithObjects:
4860 [NSDictionary dictionaryWithObjectsAndKeys:
4862 [NSNull null], @"version",
4863 @"installed", @"reason",
4870 if ([package essential])
4872 [removes addObject:name];
4875 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4876 substrate_ |= DepSubstrate(iterator.CurrentVer());
4881 else if (Advanced_) {
4882 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4884 essential_ = [[[UIAlertView alloc]
4885 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4886 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4888 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4890 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4894 [essential_ setContext:@"remove"];
4896 essential_ = [[[UIAlertView alloc]
4897 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4898 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4900 cancelButtonTitle:UCLocalize("OKAY")
4901 otherButtonTitles:nil
4904 [essential_ setContext:@"unable"];
4907 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4908 installs, @"installs",
4909 reinstalls, @"reinstalls",
4910 upgrades, @"upgrades",
4911 downgrades, @"downgrades",
4912 removes, @"removes",
4915 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4916 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4917 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4920 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4924 - (UIBarButtonItem *) leftButton {
4925 return [[[UIBarButtonItem alloc]
4926 initWithTitle:UCLocalize("CANCEL")
4927 style:UIBarButtonItemStylePlain
4929 action:@selector(cancelButtonClicked)
4934 - (void) applyRightButton {
4935 if ([issues_ count] == 0 && ![self isLoading])
4936 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4937 initWithTitle:UCLocalize("CONFIRM")
4938 style:UIBarButtonItemStyleDone
4940 action:@selector(confirmButtonClicked)
4943 [[self navigationItem] setRightBarButtonItem:nil];
4947 - (void) cancelButtonClicked {
4948 [self dismissModalViewControllerAnimated:YES];
4949 [delegate_ cancelAndClear:YES];
4953 - (void) confirmButtonClicked {
4954 if (essential_ != nil)
4964 /* Progress Data {{{ */
4965 @interface CydiaProgressData : NSObject {
4966 _transient id delegate_;
4975 _H<NSMutableArray> events_;
4976 _H<NSString> title_;
4978 _H<NSString> status_;
4979 _H<NSString> finish_;
4984 @implementation CydiaProgressData
4986 + (NSArray *) _attributeKeys {
4987 return [NSArray arrayWithObjects:
4999 - (NSArray *) attributeKeys {
5000 return [[self class] _attributeKeys];
5003 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5004 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5008 if ((self = [super init]) != nil) {
5009 events_ = [NSMutableArray arrayWithCapacity:32];
5013 - (void) setDelegate:(id)delegate {
5014 delegate_ = delegate;
5017 - (void) setPercent:(float)value {
5021 - (NSNumber *) percent {
5022 return [NSNumber numberWithFloat:percent_];
5025 - (void) setCurrent:(float)value {
5029 - (NSNumber *) current {
5030 return [NSNumber numberWithFloat:current_];
5033 - (void) setTotal:(float)value {
5037 - (NSNumber *) total {
5038 return [NSNumber numberWithFloat:total_];
5041 - (void) setSpeed:(float)value {
5045 - (NSNumber *) speed {
5046 return [NSNumber numberWithFloat:speed_];
5049 - (NSArray *) events {
5053 - (void) removeAllEvents {
5054 [events_ removeAllObjects];
5057 - (void) addEvent:(CydiaProgressEvent *)event {
5058 [events_ addObject:event];
5061 - (void) setTitle:(NSString *)text {
5065 - (NSString *) title {
5069 - (void) setFinish:(NSString *)text {
5073 - (NSString *) finish {
5074 return (id) finish_ ?: [NSNull null];
5077 - (void) setRunning:(bool)running {
5081 - (NSNumber *) running {
5082 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5087 /* Progress Controller {{{ */
5088 @interface ProgressController : CydiaWebViewController <
5091 _transient Database *database_;
5092 _H<CydiaProgressData, 1> progress_;
5096 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5098 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5100 - (void) setTitle:(NSString *)title;
5101 - (void) setCancellable:(bool)cancellable;
5105 @implementation ProgressController
5108 [database_ setProgressDelegate:nil];
5112 - (UIBarButtonItem *) leftButton {
5113 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5114 initWithTitle:UCLocalize("CANCEL")
5115 style:UIBarButtonItemStylePlain
5117 action:@selector(cancel)
5118 ] autorelease] : nil;
5121 - (void) updateCancel {
5122 [super applyLeftButton];
5125 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5126 if ((self = [super init]) != nil) {
5127 database_ = database;
5128 delegate_ = delegate;
5130 [database_ setProgressDelegate:self];
5132 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5133 [progress_ setDelegate:self];
5135 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5137 [scroller_ setBackgroundColor:[UIColor blackColor]];
5139 [[self navigationItem] setHidesBackButton:YES];
5141 [self updateCancel];
5145 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5146 [super webView:view didClearWindowObject:window forFrame:frame];
5147 [window setValue:progress_ forKey:@"cydiaProgress"];
5150 - (void) updateProgress {
5151 [self dispatchEvent:@"CydiaProgressUpdate"];
5154 - (void) viewWillAppear:(BOOL)animated {
5155 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5156 [super viewWillAppear:animated];
5160 UpdateExternalStatus(0);
5163 [delegate_ saveState];
5167 [delegate_ returnToCydia];
5171 [delegate_ terminateWithSuccess];
5172 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5173 [delegate_ suspendWithAnimation:YES];
5175 [delegate_ suspend];*/
5187 system("/usr/bin/sbreload");
5193 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5194 SBReboot(SBSSpringBoardServerPort());
5196 reboot2(RB_AUTOBOOT);
5203 - (void) setTitle:(NSString *)title {
5204 [progress_ setTitle:title];
5205 [self updateProgress];
5208 - (UIBarButtonItem *) rightButton {
5209 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5210 initWithTitle:UCLocalize("CLOSE")
5211 style:UIBarButtonItemStylePlain
5213 action:@selector(close)
5219 system("su -c /usr/bin/uicache mobile");
5223 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5224 UpdateExternalStatus(1);
5226 [progress_ setRunning:true];
5227 [self setTitle:title];
5228 // implicit updateProgress
5230 SHA1SumValue notifyconf; {
5232 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5235 MMap mmap(file, MMap::ReadOnly);
5237 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5238 notifyconf = sha1.Result();
5242 SHA1SumValue springlist; {
5244 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5247 MMap mmap(file, MMap::ReadOnly);
5249 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5250 springlist = sha1.Result();
5254 if (invocation != nil) {
5255 [invocation yieldToSelector:@selector(invoke)];
5256 [self setTitle:@"COMPLETE"];
5261 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5264 MMap mmap(file, MMap::ReadOnly);
5266 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5267 if (!(notifyconf == sha1.Result()))
5274 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5277 MMap mmap(file, MMap::ReadOnly);
5279 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5280 if (!(springlist == sha1.Result()))
5286 if (RestartSubstrate_)
5290 RestartSubstrate_ = false;
5293 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5294 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5295 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5296 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5297 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5300 UIProgressHUD *hud([delegate_ addProgressHUD]);
5301 [hud setText:UCLocalize("LOADING")];
5302 [self yieldToSelector:@selector(uicache)];
5303 [delegate_ removeProgressHUD:hud];
5305 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5307 [progress_ setRunning:false];
5308 [self updateProgress];
5310 [self applyRightButton];
5313 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5314 [progress_ addEvent:event];
5315 [self updateProgress];
5318 - (bool) isProgressCancelled {
5319 return cancel_ == 2;
5324 [self updateCancel];
5327 - (void) setCancellable:(bool)cancellable {
5328 unsigned cancel(cancel_);
5332 else if (cancel_ == 0)
5335 if (cancel != cancel_)
5336 [self updateCancel];
5339 - (void) setProgressCancellable:(NSNumber *)cancellable {
5340 [self setCancellable:[cancellable boolValue]];
5343 - (void) setProgressPercent:(NSNumber *)percent {
5344 [progress_ setPercent:[percent floatValue]];
5345 [self updateProgress];
5348 - (void) setProgressStatus:(NSDictionary *)status {
5349 if (status == nil) {
5350 [progress_ setCurrent:0];
5351 [progress_ setTotal:0];
5352 [progress_ setSpeed:0];
5354 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5356 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5357 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5358 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5361 [self updateProgress];
5367 /* Package Cell {{{ */
5368 @interface PackageCell : CyteTableViewCell <
5369 CyteTableViewCellDelegate
5373 _H<NSString> description_;
5375 _H<NSString> source_;
5377 _H<UIImage> placard_;
5381 - (PackageCell *) init;
5382 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5384 - (void) drawContentRect:(CGRect)rect;
5388 @implementation PackageCell
5390 - (PackageCell *) init {
5391 CGRect frame(CGRectMake(0, 0, 320, 74));
5392 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5393 UIView *content([self contentView]);
5394 CGRect bounds([content bounds]);
5396 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5397 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5398 [content addSubview:content_];
5400 [content_ setDelegate:self];
5401 [content_ setOpaque:YES];
5405 - (NSString *) accessibilityLabel {
5406 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5409 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5410 summarized_ = summary;
5420 [content_ setBackgroundColor:[UIColor whiteColor]];
5424 Source *source = [package source];
5426 icon_ = [package icon];
5428 if (NSString *name = [package name])
5429 name_ = [NSString stringWithString:name];
5431 NSString *description(nil);
5433 if (description == nil && IsWildcat_)
5434 description = [package longDescription];
5435 if (description == nil)
5436 description = [package shortDescription];
5438 if (description != nil)
5439 description_ = [NSString stringWithString:description];
5441 commercial_ = [package isCommercial];
5443 NSString *label = nil;
5444 bool trusted = false;
5446 if (source != nil) {
5447 label = [source label];
5448 trusted = [source trusted];
5449 } else if ([[package id] isEqualToString:@"firmware"])
5450 label = UCLocalize("APPLE");
5452 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5454 NSString *from(label);
5456 NSString *section = [package simpleSection];
5457 if (section != nil && ![section isEqualToString:label]) {
5458 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5459 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5462 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5464 if (NSString *purpose = [package primaryPurpose])
5465 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5470 if (NSString *mode = [package mode]) {
5471 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5472 color = RemovingColor_;
5473 //placard = @"removing";
5475 color = InstallingColor_;
5476 //placard = @"installing";
5479 // XXX: the removing/installing placards are not @2x
5482 color = [UIColor whiteColor];
5484 if ([package installed] != nil)
5485 placard = @"installed";
5490 [content_ setBackgroundColor:color];
5493 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5496 [self setNeedsDisplay];
5497 [content_ setNeedsDisplay];
5500 - (void) drawSummaryContentRect:(CGRect)rect {
5501 bool highlighted(highlighted_);
5502 float width([self bounds].size.width);
5506 rect.size = [(UIImage *) icon_ size];
5508 while (rect.size.width > 16 || rect.size.height > 16) {
5509 rect.size.width /= 2;
5510 rect.size.height /= 2;
5513 rect.origin.x = 18 - rect.size.width / 2;
5514 rect.origin.y = 18 - rect.size.height / 2;
5516 [icon_ drawInRect:rect];
5519 if (badge_ != nil) {
5521 rect.size = [(UIImage *) badge_ size];
5523 rect.size.width /= 4;
5524 rect.size.height /= 4;
5526 rect.origin.x = 23 - rect.size.width / 2;
5527 rect.origin.y = 23 - rect.size.height / 2;
5529 [badge_ drawInRect:rect];
5536 UISetColor(commercial_ ? Purple_ : Black_);
5537 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5539 if (placard_ != nil)
5540 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5543 - (void) drawNormalContentRect:(CGRect)rect {
5544 bool highlighted(highlighted_);
5545 float width([self bounds].size.width);
5549 rect.size = [(UIImage *) icon_ size];
5551 while (rect.size.width > 32 || rect.size.height > 32) {
5552 rect.size.width /= 2;
5553 rect.size.height /= 2;
5556 rect.origin.x = 25 - rect.size.width / 2;
5557 rect.origin.y = 25 - rect.size.height / 2;
5559 [icon_ drawInRect:rect];
5562 if (badge_ != nil) {
5564 rect.size = [(UIImage *) badge_ size];
5566 rect.size.width /= 2;
5567 rect.size.height /= 2;
5569 rect.origin.x = 36 - rect.size.width / 2;
5570 rect.origin.y = 36 - rect.size.height / 2;
5572 [badge_ drawInRect:rect];
5579 UISetColor(commercial_ ? Purple_ : Black_);
5580 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5581 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5584 UISetColor(commercial_ ? Purplish_ : Gray_);
5585 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5587 if (placard_ != nil)
5588 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5591 - (void) drawContentRect:(CGRect)rect {
5593 [self drawSummaryContentRect:rect];
5595 [self drawNormalContentRect:rect];
5600 /* Section Cell {{{ */
5601 @interface SectionCell : CyteTableViewCell <
5602 CyteTableViewCellDelegate
5604 _H<NSString> basic_;
5605 _H<NSString> section_;
5607 _H<NSString> count_;
5609 _H<UISwitch> switch_;
5613 - (void) setSection:(Section *)section editing:(BOOL)editing;
5617 @implementation SectionCell
5619 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5620 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5621 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5622 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5623 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5625 UIView *content([self contentView]);
5626 CGRect bounds([content bounds]);
5628 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5629 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5630 [content addSubview:content_];
5631 [content_ setBackgroundColor:[UIColor whiteColor]];
5633 [content_ setDelegate:self];
5637 - (void) onSwitch:(id)sender {
5638 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5639 if (metadata == nil) {
5640 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5641 [Sections_ setObject:metadata forKey:basic_];
5644 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5648 - (void) setSection:(Section *)section editing:(BOOL)editing {
5649 if (editing != editing_) {
5651 [switch_ removeFromSuperview];
5653 [self addSubview:switch_];
5662 if (section == nil) {
5663 name_ = UCLocalize("ALL_PACKAGES");
5666 basic_ = [section name];
5667 section_ = [section localized];
5669 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5670 count_ = [NSString stringWithFormat:@"%d", [section count]];
5673 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5676 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5677 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5679 [content_ setNeedsDisplay];
5682 - (void) setFrame:(CGRect)frame {
5683 [super setFrame:frame];
5685 CGRect rect([switch_ frame]);
5686 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5689 - (NSString *) accessibilityLabel {
5693 - (void) drawContentRect:(CGRect)rect {
5694 bool highlighted(highlighted_ && !editing_);
5696 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5701 float width(rect.size.width);
5707 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5709 CGSize size = [count_ sizeWithFont:Font14_];
5713 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5719 /* File Table {{{ */
5720 @interface FileTable : CyteViewController <
5721 UITableViewDataSource,
5724 _transient Database *database_;
5725 _H<Package> package_;
5727 _H<NSMutableArray> files_;
5728 _H<UITableView, 2> list_;
5731 - (id) initWithDatabase:(Database *)database;
5732 - (void) setPackage:(Package *)package;
5736 @implementation FileTable
5738 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5739 return files_ == nil ? 0 : [files_ count];
5742 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5746 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5747 static NSString *reuseIdentifier = @"Cell";
5749 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5751 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5752 [cell setFont:[UIFont systemFontOfSize:16]];
5754 [cell setText:[files_ objectAtIndex:indexPath.row]];
5755 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5760 - (NSURL *) navigationURL {
5761 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5765 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5767 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5768 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5769 [list_ setRowHeight:24.0f];
5770 [(UITableView *) list_ setDataSource:self];
5771 [list_ setDelegate:self];
5772 [[self view] addSubview:list_];
5775 - (void) viewDidLoad {
5776 [super viewDidLoad];
5778 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5781 - (void) releaseSubviews {
5787 [super releaseSubviews];
5790 - (id) initWithDatabase:(Database *)database {
5791 if ((self = [super init]) != nil) {
5792 database_ = database;
5796 - (void) setPackage:(Package *)package {
5800 files_ = [NSMutableArray arrayWithCapacity:32];
5802 if (package != nil) {
5804 name_ = [package id];
5806 if (NSArray *files = [package files])
5807 [files_ addObjectsFromArray:files];
5809 if ([files_ count] != 0) {
5810 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5811 [files_ removeObjectAtIndex:0];
5812 [files_ sortUsingSelector:@selector(compareByPath:)];
5814 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5815 [stack addObject:@"/"];
5817 for (int i(0), e([files_ count]); i != e; ++i) {
5818 NSString *file = [files_ objectAtIndex:i];
5819 while (![file hasPrefix:[stack lastObject]])
5820 [stack removeLastObject];
5821 NSString *directory = [stack lastObject];
5822 [stack addObject:[file stringByAppendingString:@"/"]];
5823 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5824 ([stack count] - 2) * 3, "",
5825 [file substringFromIndex:[directory length]]
5834 - (void) reloadData {
5837 [self setPackage:[database_ packageWithName:name_]];
5842 /* Package Controller {{{ */
5843 @interface CYPackageController : CydiaWebViewController <
5844 UIActionSheetDelegate
5846 _transient Database *database_;
5847 _H<Package> package_;
5850 _H<NSMutableArray> buttons_;
5851 _H<UIBarButtonItem> button_;
5854 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5858 @implementation CYPackageController
5860 - (NSURL *) navigationURL {
5861 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5864 /* XXX: this is not safe at all... localization of /fail/ */
5865 - (void) _clickButtonWithName:(NSString *)name {
5866 if ([name isEqualToString:UCLocalize("CLEAR")])
5867 [delegate_ clearPackage:package_];
5868 else if ([name isEqualToString:UCLocalize("INSTALL")])
5869 [delegate_ installPackage:package_];
5870 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5871 [delegate_ installPackage:package_];
5872 else if ([name isEqualToString:UCLocalize("REMOVE")])
5873 [delegate_ removePackage:package_];
5874 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5875 [delegate_ installPackage:package_];
5876 else _assert(false);
5879 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5880 NSString *context([sheet context]);
5882 if ([context isEqualToString:@"modify"]) {
5883 if (button != [sheet cancelButtonIndex]) {
5884 NSString *buttonName = [buttons_ objectAtIndex:button];
5885 [self _clickButtonWithName:buttonName];
5888 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5892 - (bool) _allowJavaScriptPanel {
5897 - (void) _customButtonClicked {
5898 int count([buttons_ count]);
5903 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5905 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5906 [buttons addObjectsFromArray:buttons_];
5908 UIActionSheet *sheet = [[[UIActionSheet alloc]
5911 cancelButtonTitle:nil
5912 destructiveButtonTitle:nil
5913 otherButtonTitles:nil
5916 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5918 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5919 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5921 [sheet setContext:@"modify"];
5923 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5927 // We don't want to allow non-commercial packages to do custom things to the install button,
5928 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5929 - (void) customButtonClicked {
5931 [super customButtonClicked];
5933 [self _customButtonClicked];
5936 - (void) reloadButtonClicked {
5937 // Don't reload a commerical package by tapping the loading button,
5938 // but if it's not an Install button, we should forward it on.
5939 if (![package_ uninstalled])
5940 [self _customButtonClicked];
5943 - (void) applyLoadingTitle {
5944 // Don't show "Loading" as the title. Ever.
5947 - (UIBarButtonItem *) rightButton {
5952 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5953 if ((self = [super init]) != nil) {
5954 database_ = database;
5955 buttons_ = [NSMutableArray arrayWithCapacity:4];
5956 name_ = name == nil ? @"" : [NSString stringWithString:name];
5957 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5961 - (void) reloadData {
5964 package_ = [database_ packageWithName:name_];
5966 [buttons_ removeAllObjects];
5968 if (package_ != nil) {
5969 [(Package *) package_ parse];
5971 commercial_ = [package_ isCommercial];
5973 if ([package_ mode] != nil)
5974 [buttons_ addObject:UCLocalize("CLEAR")];
5975 if ([package_ source] == nil);
5976 else if ([package_ upgradableAndEssential:NO])
5977 [buttons_ addObject:UCLocalize("UPGRADE")];
5978 else if ([package_ uninstalled])
5979 [buttons_ addObject:UCLocalize("INSTALL")];
5981 [buttons_ addObject:UCLocalize("REINSTALL")];
5982 if (![package_ uninstalled])
5983 [buttons_ addObject:UCLocalize("REMOVE")];
5987 switch ([buttons_ count]) {
5988 case 0: title = nil; break;
5989 case 1: title = [buttons_ objectAtIndex:0]; break;
5990 default: title = UCLocalize("MODIFY"); break;
5993 button_ = [[[UIBarButtonItem alloc]
5995 style:UIBarButtonItemStylePlain
5997 action:@selector(customButtonClicked)
6001 - (bool) isLoading {
6002 return commercial_ ? [super isLoading] : false;
6008 /* Package List Controller {{{ */
6009 @interface PackageListController : CyteViewController <
6010 UITableViewDataSource,
6013 _transient Database *database_;
6015 _H<NSArray> packages_;
6016 _H<NSMutableArray> sections_;
6017 _H<UITableView, 2> list_;
6018 _H<NSMutableArray> index_;
6019 _H<NSMutableDictionary> indices_;
6020 _H<NSString> title_;
6021 unsigned reloading_;
6024 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6025 - (void) setDelegate:(id)delegate;
6026 - (void) resetCursor;
6031 @implementation PackageListController
6033 - (bool) isSummarized {
6037 - (bool) showsSections {
6041 - (void) deselectWithAnimation:(BOOL)animated {
6042 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6045 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6046 CGRect base = [[self view] bounds];
6047 base.size.height -= bounds.size.height;
6048 base.origin = [list_ frame].origin;
6050 [UIView beginAnimations:nil context:NULL];
6051 [UIView setAnimationBeginsFromCurrentState:YES];
6052 [UIView setAnimationCurve:curve];
6053 [UIView setAnimationDuration:duration];
6054 [list_ setFrame:base];
6055 [UIView commitAnimations];
6058 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6059 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6062 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6063 [self resizeForKeyboardBounds:bounds duration:0];
6066 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6067 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6068 *curve = UIViewAnimationCurveEaseInOut;
6070 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6072 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6075 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6078 - (void) keyboardWillShow:(NSNotification *)notification {
6081 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6082 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6084 NSTimeInterval duration;
6085 UIViewAnimationCurve curve;
6086 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6088 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);
6089 UIViewController *base = self;
6090 while ([base parentViewController] != nil)
6091 base = [base parentViewController];
6092 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6093 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6095 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6096 intersection.size.height += CYStatusBarHeight();
6098 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6101 - (void) keyboardWillHide:(NSNotification *)notification {
6102 NSTimeInterval duration;
6103 UIViewAnimationCurve curve;
6104 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6106 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6109 - (void) viewWillAppear:(BOOL)animated {
6110 [super viewWillAppear:animated];
6112 [self resizeForKeyboardBounds:CGRectZero];
6113 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6114 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6117 - (void) viewWillDisappear:(BOOL)animated {
6118 [super viewWillDisappear:animated];
6120 [self resizeForKeyboardBounds:CGRectZero];
6121 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6122 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6125 - (void) viewDidAppear:(BOOL)animated {
6126 [super viewDidAppear:animated];
6127 [self deselectWithAnimation:animated];
6130 - (void) didSelectPackage:(Package *)package {
6131 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6132 [view setDelegate:delegate_];
6133 [[self navigationController] pushViewController:view animated:YES];
6136 #if TryIndexedCollation
6137 + (BOOL) hasIndexedCollation {
6138 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6142 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6143 NSInteger count([sections_ count]);
6144 return count == 0 ? 1 : count;
6147 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6148 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6150 return [[sections_ objectAtIndex:section] name];
6153 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6154 if ([sections_ count] == 0)
6156 return [[sections_ objectAtIndex:section] count];
6159 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6160 @synchronized (database_) {
6161 if ([database_ era] != era_)
6164 Section *section([sections_ objectAtIndex:[path section]]);
6165 NSInteger row([path row]);
6166 Package *package([packages_ objectAtIndex:([section row] + row)]);
6167 return [[package retain] autorelease];
6170 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6171 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6173 cell = [[[PackageCell alloc] init] autorelease];
6175 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6176 [cell setPackage:package asSummary:[self isSummarized]];
6180 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6181 Package *package([self packageAtIndexPath:path]);
6182 package = [database_ packageWithName:[package id]];
6183 [self didSelectPackage:package];
6186 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6187 if (![self showsSections])
6193 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6194 #if TryIndexedCollation
6195 if ([[self class] hasIndexedCollation]) {
6196 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6203 - (void) updateHeight {
6204 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6207 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6208 if ((self = [super init]) != nil) {
6209 database_ = database;
6210 title_ = [title copy];
6211 [[self navigationItem] setTitle:title_];
6216 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6218 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6219 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6220 [[self view] addSubview:list_];
6222 // XXX: is 20 the most optimal number here?
6223 [list_ setSectionIndexMinimumDisplayRowCount:20];
6225 [(UITableView *) list_ setDataSource:self];
6226 [list_ setDelegate:self];
6228 [self updateHeight];
6231 - (void) releaseSubviews {
6239 [super releaseSubviews];
6242 - (void) setDelegate:(id)delegate {
6243 delegate_ = delegate;
6246 - (bool) shouldYield {
6250 - (bool) shouldBlock {
6254 - (NSMutableArray *) _reloadPackages {
6255 @synchronized (database_) {
6256 era_ = [database_ era];
6257 NSArray *packages([database_ packages]);
6259 return [NSMutableArray arrayWithArray:packages];
6262 - (void) _reloadData {
6263 if (reloading_ != 0) {
6270 if ([self shouldYield]) {
6274 if (![self shouldBlock])
6277 hud = [delegate_ addProgressHUD];
6278 [hud setText:UCLocalize("LOADING")];
6282 packages = [self yieldToSelector:@selector(_reloadPackages)];
6285 [delegate_ removeProgressHUD:hud];
6286 } while (reloading_ == 2);
6290 packages = [self _reloadPackages];
6293 packages_ = packages;
6295 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6296 sections_ = [NSMutableArray arrayWithCapacity:16];
6298 Section *section = nil;
6300 #if TryIndexedCollation
6301 if ([[self class] hasIndexedCollation]) {
6302 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6304 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6305 NSArray *titles = [collation sectionIndexTitles];
6308 _profile(PackageTable$reloadData$Section)
6309 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6313 _profile(PackageTable$reloadData$Section$Package)
6314 package = [packages_ objectAtIndex:offset];
6315 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6318 while (secidx < index) {
6321 _profile(PackageTable$reloadData$Section$Allocate)
6322 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6325 _profile(PackageTable$reloadData$Section$Add)
6326 [sections_ addObject:section];
6330 [section addToCount];
6336 index_ = [NSMutableArray arrayWithCapacity:32];
6338 bool sectioned([self showsSections]);
6340 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6341 [sections_ addObject:section];
6344 _profile(PackageTable$reloadData$Section)
6345 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6349 _profile(PackageTable$reloadData$Section$Package)
6350 package = [packages_ objectAtIndex:offset];
6351 index = [package index];
6354 if (sectioned && (section == nil || [section index] != index)) {
6355 _profile(PackageTable$reloadData$Section$Allocate)
6356 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6359 [index_ addObject:[section name]];
6360 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6362 _profile(PackageTable$reloadData$Section$Add)
6363 [sections_ addObject:section];
6367 [section addToCount];
6372 [self updateHeight];
6374 _profile(PackageTable$reloadData$List)
6375 [(UITableView *) list_ setDataSource:self];
6380 - (void) reloadData {
6383 if ([self shouldYield])
6384 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6389 - (void) resetCursor {
6390 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6393 - (void) clearData {
6394 [self updateHeight];
6396 [list_ setDataSource:nil];
6404 /* Filtered Package List Controller {{{ */
6405 @interface FilteredPackageListController : PackageListController {
6408 _H<NSObject> object_;
6411 - (void) setObject:(id)object;
6412 - (void) setObject:(id)object forFilter:(SEL)filter;
6415 - (void) setFilter:(SEL)filter;
6417 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6421 @implementation FilteredPackageListController
6427 - (void) setFilter:(SEL)filter {
6428 @synchronized (self) {
6431 /* XXX: this is an unsafe optimization of doomy hell */
6432 Method method(class_getInstanceMethod([Package class], filter));
6433 _assert(method != NULL);
6434 imp_ = method_getImplementation(method);
6435 _assert(imp_ != NULL);
6438 - (void) setObject:(id)object {
6439 @synchronized (self) {
6443 - (void) setObject:(id)object forFilter:(SEL)filter {
6444 @synchronized (self) {
6445 [self setFilter:filter];
6446 [self setObject:object];
6449 - (NSMutableArray *) _reloadPackages {
6450 @synchronized (database_) {
6451 era_ = [database_ era];
6452 NSArray *packages([database_ packages]);
6454 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6458 _H<NSObject> object;
6460 @synchronized (self) {
6466 _profile(PackageTable$reloadData$Filter)
6467 for (Package *package in packages)
6468 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6469 [filtered addObject:package];
6475 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6476 if ((self = [super initWithDatabase:database title:title]) != nil) {
6477 [self setFilter:filter];
6478 [self setObject:object];
6485 /* Home Controller {{{ */
6486 @interface HomeController : CydiaWebViewController {
6491 @implementation HomeController
6494 if ((self = [super init]) != nil) {
6495 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6500 - (NSURL *) navigationURL {
6501 return [NSURL URLWithString:@"cydia://home"];
6504 - (void) didReceiveMemoryWarning {
6507 - (void) aboutButtonClicked {
6508 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6510 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6511 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6512 [alert setCancelButtonIndex:0];
6515 @"Copyright \u00a9 2008-2011\n"
6518 "Jay Freeman (saurik)\n"
6519 "saurik@saurik.com\n"
6520 "http://www.saurik.com/"
6526 - (UIBarButtonItem *) leftButton {
6527 return [[[UIBarButtonItem alloc]
6528 initWithTitle:UCLocalize("ABOUT")
6529 style:UIBarButtonItemStylePlain
6531 action:@selector(aboutButtonClicked)
6537 /* Manage Controller {{{ */
6538 @interface ManageController : CydiaWebViewController {
6541 - (void) queueStatusDidChange;
6545 @implementation ManageController
6548 if ((self = [super init]) != nil) {
6549 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6553 - (NSURL *) navigationURL {
6554 return [NSURL URLWithString:@"cydia://manage"];
6557 - (UIBarButtonItem *) leftButton {
6558 return [[[UIBarButtonItem alloc]
6559 initWithTitle:UCLocalize("SETTINGS")
6560 style:UIBarButtonItemStylePlain
6562 action:@selector(settingsButtonClicked)
6566 - (void) settingsButtonClicked {
6567 [delegate_ showSettings];
6570 - (void) queueButtonClicked {
6574 - (UIBarButtonItem *) customButton {
6575 return Queuing_ ? [[[UIBarButtonItem alloc]
6576 initWithTitle:UCLocalize("QUEUE")
6577 style:UIBarButtonItemStyleDone
6579 action:@selector(queueButtonClicked)
6580 ] autorelease] : [super customButton];
6583 - (void) queueStatusDidChange {
6584 [self applyRightButton];
6587 - (bool) isLoading {
6588 return !Queuing_ && [super isLoading];
6594 /* Refresh Bar {{{ */
6595 @interface RefreshBar : UINavigationBar {
6596 _H<UIProgressIndicator> indicator_;
6597 _H<UITextLabel> prompt_;
6598 _H<UIProgressBar> progress_;
6599 _H<UINavigationButton> cancel_;
6604 @implementation RefreshBar
6606 - (void) positionViews {
6607 CGRect frame = [cancel_ frame];
6608 frame.size = [cancel_ sizeThatFits:frame.size];
6609 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6610 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6611 [cancel_ setFrame:frame];
6613 CGSize prgsize = {75, 100};
6615 [self frame].size.width - prgsize.width - 10,
6616 ([self frame].size.height - prgsize.height) / 2
6618 [progress_ setFrame:prgrect];
6620 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6621 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6622 CGRect indrect = {{indoffset, indoffset}, indsize};
6623 [indicator_ setFrame:indrect];
6625 CGSize prmsize = {215, indsize.height + 4};
6627 indoffset * 2 + indsize.width,
6628 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6630 [prompt_ setFrame:prmrect];
6633 - (void) setFrame:(CGRect)frame {
6634 [super setFrame:frame];
6635 [self positionViews];
6638 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6639 if ((self = [super initWithFrame:frame]) != nil) {
6640 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6642 [self setBarStyle:UIBarStyleBlack];
6644 UIBarStyle barstyle([self _barStyle:NO]);
6645 bool ugly(barstyle == UIBarStyleDefault);
6647 UIProgressIndicatorStyle style = ugly ?
6648 UIProgressIndicatorStyleMediumBrown :
6649 UIProgressIndicatorStyleMediumWhite;
6651 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6652 [(UIProgressIndicator *) indicator_ setStyle:style];
6653 [indicator_ startAnimation];
6654 [self addSubview:indicator_];
6656 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6657 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6658 [prompt_ setBackgroundColor:[UIColor clearColor]];
6659 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6660 [self addSubview:prompt_];
6662 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6663 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6664 [(UIProgressBar *) progress_ setStyle:0];
6665 [self addSubview:progress_];
6667 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6668 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6669 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6670 [cancel_ setBarStyle:barstyle];
6672 [self positionViews];
6676 - (void) setCancellable:(bool)cancellable {
6678 [self addSubview:cancel_];
6680 [cancel_ removeFromSuperview];
6684 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6685 [progress_ setProgress:0];
6689 [self setCancellable:NO];
6692 - (void) setPrompt:(NSString *)prompt {
6693 [prompt_ setText:prompt];
6696 - (void) setProgress:(float)progress {
6697 [progress_ setProgress:progress];
6703 /* Cydia Navigation Controller Interface {{{ */
6704 @interface UINavigationController (Cydia)
6706 - (NSArray *) navigationURLCollection;
6707 - (void) unloadData;
6712 /* Cydia Tab Bar Controller {{{ */
6713 @interface CYTabBarController : UITabBarController <
6714 UITabBarControllerDelegate,
6717 _transient Database *database_;
6718 _H<RefreshBar, 1> refreshbar_;
6722 // XXX: ok, "updatedelegate_"?...
6723 _transient NSObject<CydiaDelegate> *updatedelegate_;
6725 _H<UIViewController> remembered_;
6726 _transient UIViewController *transient_;
6729 - (NSArray *) navigationURLCollection;
6730 - (void) dropBar:(BOOL)animated;
6731 - (void) beginUpdate;
6732 - (void) raiseBar:(BOOL)animated;
6734 - (void) unloadData;
6738 @implementation CYTabBarController
6740 - (void) setUnselectedViewController:(UIViewController *)transient {
6741 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6742 if (transient != nil) {
6743 if (transient_ == nil)
6744 remembered_ = [controllers objectAtIndex:0];
6745 transient_ = transient;
6746 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6747 [controllers replaceObjectAtIndex:0 withObject:transient_];
6748 [self setSelectedIndex:0];
6749 [self setViewControllers:controllers];
6750 [self concealTabBarSelection];
6751 } else if (remembered_ != nil) {
6752 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6753 transient_ = transient;
6754 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6756 [self setViewControllers:controllers];
6757 [self revealTabBarSelection];
6761 - (UIViewController *) unselectedViewController {
6765 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6766 if ([self unselectedViewController])
6767 [self setUnselectedViewController:nil];
6770 - (NSArray *) navigationURLCollection {
6771 NSMutableArray *items([NSMutableArray array]);
6773 // XXX: Should this deal with transient view controllers?
6774 for (id navigation in [self viewControllers]) {
6775 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6777 [items addObject:stack];
6783 - (void) dismissModalViewControllerAnimated:(BOOL)animated {
6784 if ([self modalViewController] == nil && [self unselectedViewController] != nil)
6785 [self setUnselectedViewController:nil];
6787 [super dismissModalViewControllerAnimated:YES];
6790 - (void) unloadData {
6793 for (UINavigationController *controller in [self viewControllers])
6794 [controller unloadData];
6796 if (UIViewController *selected = [self selectedViewController])
6797 [selected reloadData];
6799 if (UIViewController *unselected = [self unselectedViewController]) {
6800 [unselected unloadData];
6801 [unselected reloadData];
6806 [[NSNotificationCenter defaultCenter] removeObserver:self];
6811 - (id) initWithDatabase:(Database *)database {
6812 if ((self = [super init]) != nil) {
6813 database_ = database;
6814 [self setDelegate:self];
6816 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6817 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6819 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6823 - (void) setUpdate:(NSDate *)date {
6827 - (void) beginUpdate {
6828 [(RefreshBar *) refreshbar_ start];
6831 [updatedelegate_ retainNetworkActivityIndicator];
6835 detachNewThreadSelector:@selector(performUpdate)
6841 - (void) performUpdate {
6842 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6845 status.setDelegate(self);
6846 [database_ updateWithStatus:status];
6849 performSelectorOnMainThread:@selector(completeUpdate)
6857 - (void) stopUpdateWithSelector:(SEL)selector {
6859 [updatedelegate_ releaseNetworkActivityIndicator];
6861 [self raiseBar:YES];
6864 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6867 - (void) completeUpdate {
6870 [self stopUpdateWithSelector:@selector(reloadData)];
6873 - (void) cancelUpdate {
6874 [self stopUpdateWithSelector:@selector(updateData)];
6877 - (void) cancelPressed {
6878 [self cancelUpdate];
6885 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6886 [refreshbar_ setPrompt:[event compoundMessage]];
6889 - (bool) isProgressCancelled {
6893 - (void) setProgressCancellable:(NSNumber *)cancellable {
6894 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6897 - (void) setProgressPercent:(NSNumber *)percent {
6898 [refreshbar_ setProgress:[percent floatValue]];
6901 - (void) setProgressStatus:(NSDictionary *)status {
6903 [self setProgressPercent:[status objectForKey:@"Percent"]];
6906 - (void) setUpdateDelegate:(id)delegate {
6907 updatedelegate_ = delegate;
6910 - (UIView *) transitionView {
6911 if ([self respondsToSelector:@selector(_transitionView)])
6912 return [self _transitionView];
6914 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6917 - (void) dropBar:(BOOL)animated {
6922 UIView *transition([self transitionView]);
6923 [[self view] addSubview:refreshbar_];
6925 CGRect barframe([refreshbar_ frame]);
6927 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6928 barframe.origin.y = CYStatusBarHeight();
6930 barframe.origin.y = 0;
6932 [refreshbar_ setFrame:barframe];
6935 [UIView beginAnimations:nil context:NULL];
6937 CGRect viewframe = [transition frame];
6938 viewframe.origin.y += barframe.size.height;
6939 viewframe.size.height -= barframe.size.height;
6940 [transition setFrame:viewframe];
6943 [UIView commitAnimations];
6945 // Ensure bar has the proper width for our view, it might have changed
6946 barframe.size.width = viewframe.size.width;
6947 [refreshbar_ setFrame:barframe];
6950 - (void) raiseBar:(BOOL)animated {
6955 UIView *transition([self transitionView]);
6956 [refreshbar_ removeFromSuperview];
6958 CGRect barframe([refreshbar_ frame]);
6961 [UIView beginAnimations:nil context:NULL];
6963 CGRect viewframe = [transition frame];
6964 viewframe.origin.y -= barframe.size.height;
6965 viewframe.size.height += barframe.size.height;
6966 [transition setFrame:viewframe];
6969 [UIView commitAnimations];
6972 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6973 bool dropped(dropped_);
6978 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6984 - (void) statusBarFrameChanged:(NSNotification *)notification {
6994 /* Cydia Navigation Controller Implementation {{{ */
6995 @implementation UINavigationController (Cydia)
6997 - (NSArray *) navigationURLCollection {
6998 NSMutableArray *stack([NSMutableArray array]);
7000 for (CyteViewController *controller in [self viewControllers]) {
7001 NSString *url = [[controller navigationURL] absoluteString];
7003 [stack addObject:url];
7009 - (void) reloadData {
7012 UIViewController *visible([self visibleViewController]);
7014 [visible reloadData];
7016 // on the iPad, this view controller is ALSO visible. :(
7018 if (UIViewController *top = [self topViewController])
7023 - (void) unloadData {
7024 for (CyteViewController *page in [self viewControllers])
7033 /* Cydia:// Protocol {{{ */
7034 @interface CydiaURLProtocol : NSURLProtocol {
7039 @implementation CydiaURLProtocol
7041 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7042 NSURL *url([request URL]);
7046 NSString *scheme([[url scheme] lowercaseString]);
7047 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7049 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7055 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7059 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7060 id<NSURLProtocolClient> client([self client]);
7062 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7064 NSData *data(UIImagePNGRepresentation(icon));
7066 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7067 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7068 [client URLProtocol:self didLoadData:data];
7069 [client URLProtocolDidFinishLoading:self];
7073 - (void) startLoading {
7074 id<NSURLProtocolClient> client([self client]);
7075 NSURLRequest *request([self request]);
7077 NSURL *url([request URL]);
7078 NSString *href([url absoluteString]);
7079 NSString *scheme([[url scheme] lowercaseString]);
7083 if ([scheme isEqualToString:@"cydia"])
7084 path = [href substringFromIndex:8];
7085 else if ([scheme isEqualToString:@"about"])
7086 path = [href substringFromIndex:12];
7087 else _assert(false);
7089 NSRange slash([path rangeOfString:@"/"]);
7092 if (slash.location == NSNotFound) {
7096 command = [path substringToIndex:slash.location];
7097 path = [path substringFromIndex:(slash.location + 1)];
7100 Database *database([Database sharedInstance]);
7102 if ([command isEqualToString:@"package-icon"]) {
7105 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7106 Package *package([database packageWithName:path]);
7110 UIImage *icon([package icon]);
7111 [self _returnPNGWithImage:icon forRequest:request];
7112 } else if ([command isEqualToString:@"uikit-image"]) {
7115 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7116 UIImage *icon(_UIImageWithName(path));
7117 [self _returnPNGWithImage:icon forRequest:request];
7118 } else if ([command isEqualToString:@"section-icon"]) {
7121 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7122 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7124 icon = [UIImage applicationImageNamed:@"unknown.png"];
7125 [self _returnPNGWithImage:icon forRequest:request];
7127 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7131 - (void) stopLoading {
7137 /* Section Controller {{{ */
7138 @interface SectionController : FilteredPackageListController {
7139 _H<NSString> section_;
7142 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7146 @implementation SectionController
7148 - (NSURL *) navigationURL {
7149 NSString *name = section_;
7153 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7156 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7159 title = UCLocalize("ALL_PACKAGES");
7160 else if (![name isEqual:@""])
7161 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7163 title = UCLocalize("NO_SECTION");
7165 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7172 /* Sections Controller {{{ */
7173 @interface SectionsController : CyteViewController <
7174 UITableViewDataSource,
7177 _transient Database *database_;
7178 _H<NSMutableArray> sections_;
7179 _H<NSMutableArray> filtered_;
7180 _H<UITableView, 2> list_;
7183 - (id) initWithDatabase:(Database *)database;
7184 - (void) editButtonClicked;
7188 @implementation SectionsController
7190 - (NSURL *) navigationURL {
7191 return [NSURL URLWithString:@"cydia://sections"];
7194 - (void) updateNavigationItem {
7195 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7196 if ([sections_ count] == 0) {
7197 [[self navigationItem] setRightBarButtonItem:nil];
7199 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7200 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7202 action:@selector(editButtonClicked)
7203 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7207 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7208 [super setEditing:editing animated:animated];
7213 [delegate_ updateData];
7215 [self updateNavigationItem];
7218 - (void) viewDidAppear:(BOOL)animated {
7219 [super viewDidAppear:animated];
7220 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7223 - (void) viewWillDisappear:(BOOL)animated {
7224 [super viewWillDisappear:animated];
7225 if ([self isEditing]) [self setEditing:NO];
7228 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7229 Section *section = nil;
7230 int index = [indexPath row];
7231 if (![self isEditing]) {
7234 section = [filtered_ objectAtIndex:index];
7236 section = [sections_ objectAtIndex:index];
7241 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7242 if ([self isEditing])
7243 return [sections_ count];
7245 return [filtered_ count] + 1;
7248 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7252 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7253 static NSString *reuseIdentifier = @"SectionCell";
7255 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7257 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7259 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7264 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7265 if ([self isEditing])
7268 Section *section = [self sectionAtIndexPath:indexPath];
7270 SectionController *controller = [[[SectionController alloc]
7271 initWithDatabase:database_
7272 section:[section name]
7274 [controller setDelegate:delegate_];
7276 [[self navigationController] pushViewController:controller animated:YES];
7280 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7282 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7283 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7284 [list_ setRowHeight:45.0f];
7285 [(UITableView *) list_ setDataSource:self];
7286 [list_ setDelegate:self];
7287 [[self view] addSubview:list_];
7290 - (void) viewDidLoad {
7291 [super viewDidLoad];
7293 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7296 - (void) releaseSubviews {
7302 [super releaseSubviews];
7305 - (id) initWithDatabase:(Database *)database {
7306 if ((self = [super init]) != nil) {
7307 database_ = database;
7311 - (void) reloadData {
7314 NSArray *packages = [database_ packages];
7316 sections_ = [NSMutableArray arrayWithCapacity:16];
7317 filtered_ = [NSMutableArray arrayWithCapacity:16];
7319 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7322 for (Package *package in packages) {
7323 NSString *name([package section]);
7324 NSString *key(name == nil ? @"" : name);
7328 _profile(SectionsView$reloadData$Section)
7329 section = [sections objectForKey:key];
7330 if (section == nil) {
7331 _profile(SectionsView$reloadData$Section$Allocate)
7332 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7333 [sections setObject:section forKey:key];
7338 [section addToCount];
7340 _profile(SectionsView$reloadData$Filter)
7341 if (![package valid] || ![package visible])
7349 [sections_ addObjectsFromArray:[sections allValues]];
7351 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7353 for (Section *section in (id) sections_) {
7354 size_t count([section row]);
7358 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7359 [section setCount:count];
7360 [filtered_ addObject:section];
7363 [self updateNavigationItem];
7368 - (void) editButtonClicked {
7369 [self setEditing:![self isEditing] animated:YES];
7375 /* Changes Controller {{{ */
7376 @interface ChangesController : CyteViewController <
7377 UITableViewDataSource,
7380 _transient Database *database_;
7382 _H<NSArray> packages_;
7383 _H<NSMutableArray> sections_;
7384 _H<UITableView, 2> list_;
7388 - (id) initWithDatabase:(Database *)database;
7392 @implementation ChangesController
7394 - (NSURL *) navigationURL {
7395 return [NSURL URLWithString:@"cydia://changes"];
7398 - (void) viewDidAppear:(BOOL)animated {
7399 [super viewDidAppear:animated];
7400 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7403 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7404 NSInteger count([sections_ count]);
7405 return count == 0 ? 1 : count;
7408 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7409 if ([sections_ count] == 0)
7411 return [[sections_ objectAtIndex:section] name];
7414 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7415 if ([sections_ count] == 0)
7417 return [[sections_ objectAtIndex:section] count];
7420 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7421 @synchronized (database_) {
7422 if ([database_ era] != era_)
7425 NSUInteger sectionIndex([path section]);
7426 if (sectionIndex >= [sections_ count])
7428 Section *section([sections_ objectAtIndex:sectionIndex]);
7429 NSInteger row([path row]);
7430 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7433 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7434 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7436 cell = [[[PackageCell alloc] init] autorelease];
7438 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
7439 [cell setPackage:package asSummary:false];
7443 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7444 Package *package([self packageAtIndexPath:path]);
7445 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7446 [view setDelegate:delegate_];
7447 [[self navigationController] pushViewController:view animated:YES];
7451 - (void) refreshButtonClicked {
7452 [delegate_ beginUpdate];
7453 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7456 - (void) upgradeButtonClicked {
7457 [delegate_ distUpgrade];
7458 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7462 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7464 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7465 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7466 [list_ setRowHeight:73];
7467 [(UITableView *) list_ setDataSource:self];
7468 [list_ setDelegate:self];
7469 [[self view] addSubview:list_];
7472 - (void) viewDidLoad {
7473 [super viewDidLoad];
7475 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7478 - (void) releaseSubviews {
7484 [super releaseSubviews];
7487 - (id) initWithDatabase:(Database *)database {
7488 if ((self = [super init]) != nil) {
7489 database_ = database;
7493 - (NSMutableArray *) _reloadPackages {
7494 @synchronized (database_) {
7495 era_ = [database_ era];
7496 NSArray *packages([database_ packages]);
7498 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7501 _profile(ChangesController$_reloadPackages$Filter)
7502 for (Package *package in packages)
7503 if ([package upgradableAndEssential:YES] || [package visible])
7504 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7507 _profile(ChangesController$_reloadPackages$radixSort)
7508 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7515 - (void) _reloadData {
7520 UIProgressHUD *hud([delegate_ addProgressHUD]);
7521 [hud setText:UCLocalize("LOADING")];
7522 //NSLog(@"HUD:%@::%@", delegate_, hud);
7523 packages = [self yieldToSelector:@selector(_reloadPackages)];
7524 [delegate_ removeProgressHUD:hud];
7526 packages = [self _reloadPackages];
7529 @synchronized (database_) {
7530 if (era_ != [database_ era])
7533 packages_ = packages;
7534 sections_ = [NSMutableArray arrayWithCapacity:16];
7536 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7537 Section *ignored = nil;
7538 Section *section = nil;
7542 bool unseens = false;
7544 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7546 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7547 Package *package = [packages_ objectAtIndex:offset];
7549 BOOL uae = [package upgradableAndEssential:YES];
7553 time_t seen([package seen]);
7555 if (section == nil || last != seen) {
7559 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7562 _profile(ChangesController$reloadData$Allocate)
7563 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7564 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7565 [sections_ addObject:section];
7569 [section addToCount];
7570 } else if ([package ignored]) {
7571 if (ignored == nil) {
7572 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7574 [ignored addToCount];
7577 [upgradable addToCount];
7582 CFRelease(formatter);
7585 Section *last = [sections_ lastObject];
7586 size_t count = [last count];
7587 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7588 [sections_ removeLastObject];
7591 if ([ignored count] != 0)
7592 [sections_ insertObject:ignored atIndex:0];
7594 [sections_ insertObject:upgradable atIndex:0];
7598 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7599 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7600 style:UIBarButtonItemStylePlain
7602 action:@selector(upgradeButtonClicked)
7603 ] autorelease]) animated:YES];
7605 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7606 initWithTitle:UCLocalize("REFRESH")
7607 style:UIBarButtonItemStylePlain
7609 action:@selector(refreshButtonClicked)
7610 ] autorelease]) animated:YES];
7615 - (void) reloadData {
7617 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7622 /* Search Controller {{{ */
7623 @interface SearchController : FilteredPackageListController <
7626 _H<UISearchBar, 1> search_;
7630 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7631 - (void) reloadData;
7635 @implementation SearchController
7637 - (NSURL *) navigationURL {
7638 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7639 return [NSURL URLWithString:@"cydia://search"];
7641 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7644 - (void) useSearch {
7645 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7650 - (void) viewWillAppear:(BOOL)animated {
7651 [super viewWillAppear:animated];
7653 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7657 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7658 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7663 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7664 [search_ resignFirstResponder];
7668 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7669 [search_ setText:@""];
7670 [self searchBarButtonClicked:searchBar];
7673 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7674 [self searchBarButtonClicked:searchBar];
7677 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7678 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7682 - (bool) shouldYield {
7686 - (bool) shouldBlock {
7687 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7690 - (bool) isSummarized {
7691 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7694 - (bool) showsSections {
7698 - (NSMutableArray *) _reloadPackages {
7699 NSMutableArray *packages([super _reloadPackages]);
7700 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7701 [packages radixSortUsingSelector:@selector(rank)];
7705 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7706 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7707 search_ = [[[UISearchBar alloc] init] autorelease];
7708 [search_ setDelegate:self];
7711 [search_ setText:query];
7715 - (void) viewDidAppear:(BOOL)animated {
7716 [super viewDidAppear:animated];
7718 if (!searchloaded_) {
7719 searchloaded_ = YES;
7720 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7721 [search_ layoutSubviews];
7722 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7724 UITextField *textField;
7725 if ([search_ respondsToSelector:@selector(searchField)])
7726 textField = [search_ searchField];
7728 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7730 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7731 [textField setEnablesReturnKeyAutomatically:NO];
7732 [[self navigationItem] setTitleView:textField];
7736 - (void) reloadData {
7737 id object([search_ text]);
7738 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7739 object = [object componentsSeparatedByString:@" "];
7741 [self setObject:object];
7747 - (void) didSelectPackage:(Package *)package {
7748 [search_ resignFirstResponder];
7749 [super didSelectPackage:package];
7754 /* Package Settings Controller {{{ */
7755 @interface PackageSettingsController : CyteViewController <
7756 UITableViewDataSource,
7759 _transient Database *database_;
7761 _H<Package> package_;
7762 _H<UITableView, 2> table_;
7763 _H<UISwitch> subscribedSwitch_;
7764 _H<UISwitch> ignoredSwitch_;
7765 _H<UITableViewCell> subscribedCell_;
7766 _H<UITableViewCell> ignoredCell_;
7769 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7773 @implementation PackageSettingsController
7775 - (NSURL *) navigationURL {
7776 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7779 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7780 if (package_ == nil)
7783 if ([package_ installed] == nil)
7789 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7790 if (package_ == nil)
7793 // both sections contain just one item right now.
7797 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7801 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7803 return UCLocalize("SHOW_ALL_CHANGES_EX");
7805 return UCLocalize("IGNORE_UPGRADES_EX");
7808 - (void) onSubscribed:(id)control {
7809 bool value([control isOn]);
7810 if (package_ == nil)
7812 if ([package_ setSubscribed:value])
7813 [delegate_ updateData];
7816 - (void) _updateIgnored {
7817 const char *package([name_ UTF8String]);
7818 bool on([ignoredSwitch_ isOn]);
7820 pid_t pid(ExecFork());
7822 FILE *dpkg(popen("dpkg --set-selections", "w"));
7823 fwrite(package, strlen(package), 1, dpkg);
7826 fwrite(" hold\n", 6, 1, dpkg);
7828 fwrite(" install\n", 9, 1, dpkg);
7838 int result(waitpid(pid, &status, 0));
7841 _assert(result == pid);
7847 - (void) onIgnored:(id)control {
7848 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7849 [invocation setTarget:self];
7850 [invocation setSelector:@selector(_updateIgnored)];
7852 [delegate_ reloadDataWithInvocation:invocation];
7855 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7856 if (package_ == nil)
7859 switch ([indexPath section]) {
7860 case 0: return subscribedCell_;
7861 case 1: return ignoredCell_;
7870 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7872 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7873 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7874 [(UITableView *) table_ setDataSource:self];
7875 [table_ setDelegate:self];
7876 [[self view] addSubview:table_];
7878 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7879 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7880 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7882 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7883 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7884 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7886 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7887 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7888 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7889 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7891 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7892 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7893 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7894 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7897 - (void) viewDidLoad {
7898 [super viewDidLoad];
7900 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7903 - (void) releaseSubviews {
7905 subscribedCell_ = nil;
7907 ignoredSwitch_ = nil;
7908 subscribedSwitch_ = nil;
7910 [super releaseSubviews];
7913 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7914 if ((self = [super init]) != nil) {
7915 database_ = database;
7920 - (void) reloadData {
7923 package_ = [database_ packageWithName:name_];
7925 if (package_ != nil) {
7926 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7927 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7928 } // XXX: what now, G?
7930 [table_ reloadData];
7936 /* Installed Controller {{{ */
7937 @interface InstalledController : FilteredPackageListController {
7941 - (id) initWithDatabase:(Database *)database;
7943 - (void) updateRoleButton;
7944 - (void) queueStatusDidChange;
7948 @implementation InstalledController
7950 - (NSURL *) navigationURL {
7951 return [NSURL URLWithString:@"cydia://installed"];
7954 - (id) initWithDatabase:(Database *)database {
7955 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7956 [self updateRoleButton];
7957 [self queueStatusDidChange];
7962 - (void) queueButtonClicked {
7967 - (void) queueStatusDidChange {
7971 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7972 initWithTitle:UCLocalize("QUEUE")
7973 style:UIBarButtonItemStyleDone
7975 action:@selector(queueButtonClicked)
7978 [[self navigationItem] setLeftBarButtonItem:nil];
7984 - (void) updateRoleButton {
7985 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7986 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7987 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7988 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7990 action:@selector(roleButtonClicked)
7994 - (void) roleButtonClicked {
7995 [self setObject:[NSNumber numberWithBool:expert_]];
7999 [self updateRoleButton];
8005 /* Source Cell {{{ */
8006 @interface SourceCell : CyteTableViewCell <
8007 CyteTableViewCellDelegate
8011 _H<NSString> origin_;
8012 _H<NSString> label_;
8015 - (void) setSource:(Source *)source;
8019 @implementation SourceCell
8021 - (void) _setImage:(NSArray *)data {
8022 if ([url_ isEqual:[data objectAtIndex:0]]) {
8023 icon_ = [data objectAtIndex:1];
8024 [content_ setNeedsDisplay];
8028 - (void) _setSource:(NSURL *) url {
8029 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8031 if (NSData *data = [NSURLConnection
8032 sendSynchronousRequest:[NSURLRequest
8034 //cachePolicy:NSURLRequestUseProtocolCachePolicy
8038 returningResponse:NULL
8041 if (UIImage *image = [UIImage imageWithData:data])
8042 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8047 - (void) setSource:(Source *)source {
8048 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8050 origin_ = [source name];
8051 label_ = [source rooturi];
8053 [content_ setNeedsDisplay];
8055 url_ = [source iconURL];
8056 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8059 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8060 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8061 UIView *content([self contentView]);
8062 CGRect bounds([content bounds]);
8064 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8065 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8066 [content_ setBackgroundColor:[UIColor whiteColor]];
8067 [content addSubview:content_];
8069 [content_ setDelegate:self];
8070 [content_ setOpaque:YES];
8072 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8076 - (NSString *) accessibilityLabel {
8080 - (void) drawContentRect:(CGRect)rect {
8081 bool highlighted(highlighted_);
8082 float width(rect.size.width);
8086 rect.size = [(UIImage *) icon_ size];
8088 while (rect.size.width > 32 || rect.size.height > 32) {
8089 rect.size.width /= 2;
8090 rect.size.height /= 2;
8093 rect.origin.x = 25 - rect.size.width / 2;
8094 rect.origin.y = 25 - rect.size.height / 2;
8096 [icon_ drawInRect:rect];
8104 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 60) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8108 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 75) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8113 /* Source Controller {{{ */
8114 @interface SourceController : FilteredPackageListController {
8115 _transient Source *source_;
8119 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8123 @implementation SourceController
8125 - (NSURL *) navigationURL {
8126 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
8129 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8130 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8132 key_ = [source key];
8136 - (void) reloadData {
8137 source_ = [database_ sourceWithKey:key_];
8138 key_ = [source_ key];
8139 [self setObject:source_];
8141 [[self navigationItem] setTitle:[source_ label]];
8148 /* Sources Controller {{{ */
8149 @interface SourcesController : CyteViewController <
8150 UITableViewDataSource,
8153 _transient Database *database_;
8156 _H<UITableView, 2> list_;
8157 _H<NSMutableArray> sources_;
8161 _H<UIProgressHUD> hud_;
8164 //NSURLConnection *installer_;
8165 NSURLConnection *trivial_;
8166 NSURLConnection *trivial_bz2_;
8167 NSURLConnection *trivial_gz_;
8168 //NSURLConnection *automatic_;
8173 - (id) initWithDatabase:(Database *)database;
8174 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8178 @implementation SourcesController
8180 - (void) _releaseConnection:(NSURLConnection *)connection {
8181 if (connection != nil) {
8182 [connection cancel];
8183 //[connection setDelegate:nil];
8184 [connection release];
8189 //[self _releaseConnection:installer_];
8190 [self _releaseConnection:trivial_];
8191 [self _releaseConnection:trivial_gz_];
8192 [self _releaseConnection:trivial_bz2_];
8193 //[self _releaseConnection:automatic_];
8198 - (NSURL *) navigationURL {
8199 return [NSURL URLWithString:@"cydia://sources"];
8202 - (void) viewDidAppear:(BOOL)animated {
8203 [super viewDidAppear:animated];
8204 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8207 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8211 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8215 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8216 return [sources_ count];
8219 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8220 @synchronized (database_) {
8221 if ([database_ era] != era_)
8224 return [sources_ objectAtIndex:[indexPath row]];
8227 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8228 static NSString *cellIdentifier = @"SourceCell";
8230 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8231 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8232 [cell setSource:[self sourceAtIndexPath:indexPath]];
8233 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8238 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8239 Source *source = [self sourceAtIndexPath:indexPath];
8241 SourceController *controller = [[[SourceController alloc]
8242 initWithDatabase:database_
8246 [controller setDelegate:delegate_];
8248 [[self navigationController] pushViewController:controller animated:YES];
8251 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8252 Source *source = [self sourceAtIndexPath:indexPath];
8253 return [source record] != nil;
8256 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8257 if (editingStyle == UITableViewCellEditingStyleDelete) {
8258 Source *source = [self sourceAtIndexPath:indexPath];
8259 [Sources_ removeObjectForKey:[source key]];
8260 [delegate_ syncData];
8265 [delegate_ addTrivialSource:href_];
8266 [delegate_ syncData];
8269 - (NSString *) getWarning {
8270 NSString *href(href_);
8271 NSRange colon([href rangeOfString:@"://"]);
8272 if (colon.location != NSNotFound)
8273 href = [href substringFromIndex:(colon.location + 3)];
8274 href = [href stringByAddingPercentEscapes];
8275 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8276 href = [href stringByCachingURLWithCurrentCDN];
8278 NSURL *url([NSURL URLWithString:href]);
8280 NSStringEncoding encoding;
8281 NSError *error(nil);
8283 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8284 return [warning length] == 0 ? nil : warning;
8288 - (void) _endConnection:(NSURLConnection *)connection {
8289 // XXX: the memory management in this method is horribly awkward
8291 NSURLConnection **field = NULL;
8292 if (connection == trivial_)
8294 else if (connection == trivial_bz2_)
8295 field = &trivial_bz2_;
8296 else if (connection == trivial_gz_)
8297 field = &trivial_gz_;
8298 _assert(field != NULL);
8299 [connection release];
8304 trivial_bz2_ == nil &&
8307 [delegate_ releaseNetworkActivityIndicator];
8309 [delegate_ removeProgressHUD:hud_];
8313 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8314 UIAlertView *alert = [[[UIAlertView alloc]
8315 initWithTitle:UCLocalize("SOURCE_WARNING")
8318 cancelButtonTitle:UCLocalize("CANCEL")
8320 UCLocalize("ADD_ANYWAY"),
8324 [alert setContext:@"warning"];
8325 [alert setNumberOfRows:1];
8328 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8334 } else if (error_ != nil) {
8335 UIAlertView *alert = [[[UIAlertView alloc]
8336 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8337 message:[error_ localizedDescription]
8339 cancelButtonTitle:UCLocalize("OK")
8340 otherButtonTitles:nil
8343 [alert setContext:@"urlerror"];
8346 UIAlertView *alert = [[[UIAlertView alloc]
8347 initWithTitle:UCLocalize("NOT_REPOSITORY")
8348 message:UCLocalize("NOT_REPOSITORY_EX")
8350 cancelButtonTitle:UCLocalize("OK")
8351 otherButtonTitles:nil
8354 [alert setContext:@"trivial"];
8363 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8364 switch ([response statusCode]) {
8370 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8371 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8373 [self _endConnection:connection];
8376 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8377 [self _endConnection:connection];
8380 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8381 NSURL *url([NSURL URLWithString:href]);
8383 NSMutableURLRequest *request = [NSMutableURLRequest
8385 cachePolicy:NSURLRequestUseProtocolCachePolicy
8386 timeoutInterval:120.0
8389 [request setHTTPMethod:method];
8391 if (Machine_ != NULL)
8392 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8394 if ([url isCydiaSecure]) {
8395 if (UniqueID_ != nil) {
8396 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8397 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8401 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8404 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8405 NSString *context([alert context]);
8407 if ([context isEqualToString:@"source"]) {
8410 NSString *href = [[alert textField] text];
8412 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8414 if (![href hasSuffix:@"/"])
8415 href_ = [href stringByAppendingString:@"/"];
8419 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8420 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8421 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8422 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8426 // XXX: this is stupid
8427 hud_ = [delegate_ addProgressHUD];
8428 [hud_ setText:UCLocalize("VERIFYING_URL")];
8429 [delegate_ retainNetworkActivityIndicator];
8438 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8439 } else if ([context isEqualToString:@"trivial"])
8440 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8441 else if ([context isEqualToString:@"urlerror"])
8442 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8443 else if ([context isEqualToString:@"warning"]) {
8457 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8462 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8464 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8465 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8466 [list_ setRowHeight:53];
8467 [(UITableView *) list_ setDataSource:self];
8468 [list_ setDelegate:self];
8469 [[self view] addSubview:list_];
8472 - (void) viewDidLoad {
8473 [super viewDidLoad];
8475 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8476 [self updateButtonsForEditingStatus:NO animated:NO];
8479 - (void) releaseSubviews {
8484 [super releaseSubviews];
8487 - (id) initWithDatabase:(Database *)database {
8488 if ((self = [super init]) != nil) {
8489 database_ = database;
8493 - (void) reloadData {
8496 @synchronized (database_) {
8497 era_ = [database_ era];
8500 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8503 sources_ = [NSMutableArray arrayWithCapacity:16];
8504 [sources_ addObjectsFromArray:[database_ sources]];
8506 [sources_ sortUsingSelector:@selector(compareByName:)];
8509 int count([sources_ count]);
8511 for (int i = 0; i != count; i++) {
8512 if ([[sources_ objectAtIndex:i] record] == nil)
8517 [list_ setEditing:NO];
8518 [self updateButtonsForEditingStatus:NO animated:NO];
8522 - (void) showAddSourcePrompt {
8523 UIAlertView *alert = [[[UIAlertView alloc]
8524 initWithTitle:UCLocalize("ENTER_APT_URL")
8527 cancelButtonTitle:UCLocalize("CANCEL")
8529 UCLocalize("ADD_SOURCE"),
8533 [alert setContext:@"source"];
8535 [alert setNumberOfRows:1];
8536 [alert addTextFieldWithValue:@"http://" label:@""];
8538 UITextInputTraits *traits = [[alert textField] textInputTraits];
8539 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8540 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8541 [traits setKeyboardType:UIKeyboardTypeURL];
8542 // XXX: UIReturnKeyDone
8543 [traits setReturnKeyType:UIReturnKeyNext];
8548 - (void) addButtonClicked {
8549 [self showAddSourcePrompt];
8552 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8553 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8554 initWithTitle:UCLocalize("ADD")
8555 style:UIBarButtonItemStylePlain
8557 action:@selector(addButtonClicked)
8558 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8560 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8561 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8562 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8564 action:@selector(editButtonClicked)
8565 ] autorelease] animated:animated];
8567 if (IsWildcat_ && !editing)
8568 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8569 initWithTitle:UCLocalize("SETTINGS")
8570 style:UIBarButtonItemStylePlain
8572 action:@selector(settingsButtonClicked)
8576 - (void) settingsButtonClicked {
8577 [delegate_ showSettings];
8580 - (void) editButtonClicked {
8581 [list_ setEditing:![list_ isEditing] animated:YES];
8583 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8589 /* Settings Controller {{{ */
8590 @interface SettingsController : CyteViewController <
8591 UITableViewDataSource,
8594 _transient Database *database_;
8595 // XXX: ok, "roledelegate_"?...
8596 _transient id roledelegate_;
8597 _H<UITableView, 2> table_;
8598 _H<UISegmentedControl> segment_;
8599 _H<UIView> container_;
8602 - (void) showDoneButton;
8603 - (void) resizeSegmentedControl;
8607 @implementation SettingsController
8610 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8612 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8613 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8614 [table_ setDelegate:self];
8615 [(UITableView *) table_ setDataSource:self];
8616 [[self view] addSubview:table_];
8618 NSArray *items = [NSArray arrayWithObjects:
8620 UCLocalize("HACKER"),
8621 UCLocalize("DEVELOPER"),
8623 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8624 [segment_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin)];
8625 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8626 [container_ addSubview:segment_];
8629 - (void) viewDidLoad {
8630 [super viewDidLoad];
8632 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8635 if ([Role_ isEqualToString:@"User"]) index = 0;
8636 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8637 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8639 [segment_ setSelectedSegmentIndex:index];
8640 [self showDoneButton];
8643 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8644 [self resizeSegmentedControl];
8647 - (void) releaseSubviews {
8652 [super releaseSubviews];
8655 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8656 if ((self = [super init]) != nil) {
8657 database_ = database;
8658 roledelegate_ = delegate;
8662 - (void) resizeSegmentedControl {
8663 CGFloat width = [[self view] frame].size.width;
8664 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8667 - (void) viewWillAppear:(BOOL)animated {
8668 [super viewWillAppear:animated];
8670 [self resizeSegmentedControl];
8673 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8674 [self resizeSegmentedControl];
8677 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8678 [self resizeSegmentedControl];
8682 NSString *role(nil);
8684 switch ([segment_ selectedSegmentIndex]) {
8685 case 0: role = @"User"; break;
8686 case 1: role = @"Hacker"; break;
8687 case 2: role = @"Developer"; break;
8692 if (![role isEqualToString:Role_]) {
8693 bool rolling(Role_ == nil);
8696 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8700 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8704 [roledelegate_ loadData];
8706 [roledelegate_ updateData];
8710 - (void) segmentChanged:(UISegmentedControl *)control {
8711 [self showDoneButton];
8714 - (void) saveAndClose {
8717 [[self navigationItem] setRightBarButtonItem:nil];
8718 [[self navigationController] dismissModalViewControllerAnimated:YES];
8721 - (void) doneButtonClicked {
8722 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8723 [spinner startAnimating];
8724 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8725 [[self navigationItem] setRightBarButtonItem:spinItem];
8727 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8730 - (void) showDoneButton {
8731 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8732 initWithTitle:UCLocalize("DONE")
8733 style:UIBarButtonItemStyleDone
8735 action:@selector(doneButtonClicked)
8736 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8739 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8740 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8744 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8748 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8749 return nil; // This method is required by the protocol.
8752 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8754 return UCLocalize("ROLE_EX");
8756 return [NSString stringWithFormat:
8757 @"%@: %@\n%@: %@\n%@: %@",
8758 UCLocalize("USER"), UCLocalize("USER_EX"),
8759 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8760 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8765 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8766 return section == 3 ? 44.0f : 0;
8769 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8770 return section == 3 ? container_ : nil;
8773 - (void) reloadData {
8776 [table_ reloadData];
8781 /* Stash Controller {{{ */
8782 @interface StashController : CyteViewController {
8783 _H<UIActivityIndicatorView> spinner_;
8784 _H<UILabel> status_;
8785 _H<UILabel> caption_;
8790 @implementation StashController
8793 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8794 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8796 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8797 CGRect spinrect = [spinner_ frame];
8798 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8799 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8800 [spinner_ setFrame:spinrect];
8801 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8802 [[self view] addSubview:spinner_];
8803 [spinner_ startAnimating];
8806 captrect.size.width = [[self view] frame].size.width;
8807 captrect.size.height = 40.0f;
8808 captrect.origin.x = 0;
8809 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8810 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8811 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8812 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8813 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8814 [caption_ setTextColor:[UIColor whiteColor]];
8815 [caption_ setBackgroundColor:[UIColor clearColor]];
8816 [caption_ setShadowColor:[UIColor blackColor]];
8817 [caption_ setTextAlignment:UITextAlignmentCenter];
8818 [[self view] addSubview:caption_];
8821 statusrect.size.width = [[self view] frame].size.width;
8822 statusrect.size.height = 30.0f;
8823 statusrect.origin.x = 0;
8824 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8825 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8826 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8827 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8828 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8829 [status_ setTextColor:[UIColor whiteColor]];
8830 [status_ setBackgroundColor:[UIColor clearColor]];
8831 [status_ setShadowColor:[UIColor blackColor]];
8832 [status_ setTextAlignment:UITextAlignmentCenter];
8833 [[self view] addSubview:status_];
8836 - (void) releaseSubviews {
8841 [super releaseSubviews];
8847 @interface CYURLCache : SDURLCache {
8852 @implementation CYURLCache
8854 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8857 else if ([event isEqualToString:@"no-cache"])
8859 else if ([event isEqualToString:@"store"])
8861 else if ([event isEqualToString:@"invalid"])
8863 else if ([event isEqualToString:@"memory"])
8865 else if ([event isEqualToString:@"disk"])
8867 else if ([event isEqualToString:@"miss"])
8870 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8874 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8875 if (NSURLResponse *response = [cached response])
8876 if (NSString *mime = [response MIMEType])
8877 if ([mime isEqualToString:@"text/cache-manifest"]) {
8878 NSURL *url([response URL]);
8881 NSLog(@"###: %@", [url absoluteString]);
8884 @synchronized (HostConfig_) {
8885 [CachedURLs_ addObject:url];
8889 [super storeCachedResponse:cached forRequest:request];
8894 @interface Cydia : UIApplication <
8895 ConfirmationControllerDelegate,
8898 UINavigationControllerDelegate,
8899 UITabBarControllerDelegate
8901 _H<UIWindow> window_;
8902 _H<CYTabBarController> tabbar_;
8903 _H<CydiaLoadingViewController> emulated_;
8905 _H<NSMutableArray> essential_;
8906 _H<NSMutableArray> broken_;
8908 Database *database_;
8910 _H<NSURL> starturl_;
8915 _H<StashController> stash_;
8924 @implementation Cydia
8926 - (void) beginUpdate {
8927 [tabbar_ beginUpdate];
8931 return [tabbar_ updating];
8935 if ([broken_ count] != 0) {
8936 int count = [broken_ count];
8938 UIAlertView *alert = [[[UIAlertView alloc]
8939 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8940 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8942 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8944 UCLocalize("TEMPORARY_IGNORE"),
8948 [alert setContext:@"fixhalf"];
8949 [alert setNumberOfRows:2];
8951 } else if (!Ignored_ && [essential_ count] != 0) {
8952 int count = [essential_ count];
8954 UIAlertView *alert = [[[UIAlertView alloc]
8955 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8956 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8958 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8960 UCLocalize("UPGRADE_ESSENTIAL"),
8961 UCLocalize("COMPLETE_UPGRADE"),
8965 [alert setContext:@"upgrade"];
8970 - (void) returnToCydia {
8974 - (void) _saveConfig {
8980 NSString *error(nil);
8982 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8984 NSError *error(nil);
8985 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8986 NSLog(@"failure to save metadata data: %@", error);
8991 NSLog(@"failure to serialize metadata: %@", error);
8995 CydiaWriteSources();
8998 // Navigation controller for the queuing badge.
8999 - (UINavigationController *) queueNavigationController {
9000 NSArray *controllers = [tabbar_ viewControllers];
9001 return [controllers objectAtIndex:3];
9004 - (void) unloadData {
9005 [tabbar_ unloadData];
9008 - (void) _updateData {
9012 UINavigationController *navigation = [self queueNavigationController];
9014 id queuedelegate = nil;
9015 if ([[navigation viewControllers] count] > 0)
9016 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9018 [queuedelegate queueStatusDidChange];
9019 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9022 - (void) _refreshIfPossible:(NSDate *)update {
9023 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9025 bool recently = false;
9026 if (update != nil) {
9027 NSTimeInterval interval([update timeIntervalSinceNow]);
9028 if (interval <= 0 && interval > -(15*60))
9032 // Don't automatic refresh if:
9033 // - We already refreshed recently.
9034 // - We already auto-refreshed this launch.
9035 // - Auto-refresh is disabled.
9036 if (recently || loaded_ || ManualRefresh) {
9037 // If we are cancelling, we need to make sure it knows it's already loaded.
9040 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9042 // We are going to load, so remember that.
9045 SCNetworkReachabilityFlags flags; {
9046 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9047 SCNetworkReachabilityGetFlags(reachability, &flags);
9048 CFRelease(reachability);
9051 // XXX: this elaborate mess is what Apple is using to determine this? :(
9052 // XXX: do we care if the user has to intervene? maybe that's ok?
9054 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9055 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9056 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9057 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9058 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9059 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9063 // If we can reach the server, auto-refresh!
9065 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9071 - (void) refreshIfPossible {
9072 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9075 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9076 @synchronized (self) {
9077 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9078 [hud setText:UCLocalize("RELOADING_DATA")];
9080 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9084 [essential_ removeAllObjects];
9085 [broken_ removeAllObjects];
9087 NSArray *packages([database_ packages]);
9088 for (Package *package in packages) {
9090 [broken_ addObject:package];
9091 if ([package upgradableAndEssential:NO]) {
9092 if ([package essential])
9093 [essential_ addObject:package];
9098 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9101 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9102 [changesItem setBadgeValue:badge];
9103 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9104 [self setApplicationIconBadgeNumber:changes];
9107 [changesItem setBadgeValue:nil];
9108 [changesItem setAnimatedBadge:NO];
9109 [self setApplicationIconBadgeNumber:0];
9115 [self removeProgressHUD:hud];
9118 - (void) updateData {
9124 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9127 - (void) disemulate {
9128 if (emulated_ == nil)
9131 [window_ addSubview:[tabbar_ view]];
9132 [[emulated_ view] removeFromSuperview];
9134 [window_ setUserInteractionEnabled:YES];
9137 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9138 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9140 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9142 UIViewController *parent;
9143 if (emulated_ == nil)
9152 [parent presentModalViewController:navigation animated:YES];
9155 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9156 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9158 if (navigation != nil)
9159 [navigation pushViewController:progress animated:YES];
9161 [self presentModalViewController:progress force:YES];
9163 [progress invoke:invocation withTitle:title];
9167 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9168 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9171 - (void) repairWithInvocation:(NSInvocation *)invocation {
9173 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9177 - (void) repairWithSelector:(SEL)selector {
9178 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9181 - (void) reloadData {
9182 [self reloadDataWithInvocation:nil];
9183 if ([database_ progressDelegate] == nil)
9189 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9192 - (void) addSource:(NSDictionary *) source {
9193 CydiaAddSource(source);
9196 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9197 CydiaAddSource(href, distribution, sections);
9200 - (void) addTrivialSource:(NSString *)href {
9201 CydiaAddSource(href, @"./");
9204 - (void) updateValues {
9209 pkgProblemResolver *resolver = [database_ resolver];
9211 resolver->InstallProtect();
9212 if (!resolver->Resolve(true))
9217 // XXX: this is a really crappy way of doing this.
9218 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9219 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9220 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9221 if ([tabbar_ updating])
9222 [tabbar_ cancelUpdate];
9224 if (![database_ prepare])
9227 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9228 [page setDelegate:self];
9229 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9232 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9233 [tabbar_ presentModalViewController:confirm_ animated:YES];
9239 @synchronized (self) {
9244 - (void) clearPackage:(Package *)package {
9245 @synchronized (self) {
9252 - (void) installPackages:(NSArray *)packages {
9253 @synchronized (self) {
9254 for (Package *package in packages)
9261 - (void) installPackage:(Package *)package {
9262 @synchronized (self) {
9269 - (void) removePackage:(Package *)package {
9270 @synchronized (self) {
9277 - (void) distUpgrade {
9278 @synchronized (self) {
9279 if (![database_ upgrade])
9286 [database_ perform];
9287 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9290 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9293 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9295 [self refreshIfPossible];
9298 - (void) showSettings {
9299 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9302 - (void) retainNetworkActivityIndicator {
9303 if (activity_++ == 0)
9304 [self setNetworkActivityIndicatorVisible:YES];
9307 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9311 - (void) releaseNetworkActivityIndicator {
9312 if (--activity_ == 0)
9313 [self setNetworkActivityIndicatorVisible:NO];
9316 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9321 - (void) cancelAndClear:(bool)clear {
9322 @synchronized (self) {
9334 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9335 NSString *context([alert context]);
9337 if ([context isEqualToString:@"conffile"]) {
9338 FILE *input = [database_ input];
9339 if (button == [alert cancelButtonIndex])
9340 fprintf(input, "N\n");
9341 else if (button == [alert firstOtherButtonIndex])
9342 fprintf(input, "Y\n");
9345 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9346 } else if ([context isEqualToString:@"fixhalf"]) {
9347 if (button == [alert cancelButtonIndex]) {
9348 @synchronized (self) {
9349 for (Package *broken in (id) broken_) {
9352 NSString *id = [broken id];
9353 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9354 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9355 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9356 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9362 } else if (button == [alert firstOtherButtonIndex]) {
9363 [broken_ removeAllObjects];
9367 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9368 } else if ([context isEqualToString:@"upgrade"]) {
9369 if (button == [alert firstOtherButtonIndex]) {
9370 @synchronized (self) {
9371 for (Package *essential in (id) essential_)
9372 [essential install];
9377 } else if (button == [alert firstOtherButtonIndex] + 1) {
9379 } else if (button == [alert cancelButtonIndex]) {
9383 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9387 - (void) system:(NSString *)command {
9388 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9391 system([command UTF8String]);
9397 - (void) applicationWillSuspend {
9399 [super applicationWillSuspend];
9402 - (BOOL) isSafeToSuspend {
9405 NSLog(@"isSafeToSuspend: locked_ != 0");
9410 // Use external process status API internally.
9411 // This is probably a really bad idea.
9412 // XXX: what is the point of this? does this solve anything at all?
9413 uint64_t status = 0;
9415 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9416 notify_get_state(notify_token, &status);
9417 notify_cancel(notify_token);
9422 NSLog(@"isSafeToSuspend: status != 0");
9428 NSLog(@"isSafeToSuspend: -> true");
9433 - (void) applicationSuspend:(__GSEvent *)event {
9434 if ([self isSafeToSuspend])
9435 [super applicationSuspend:event];
9438 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9439 if ([self isSafeToSuspend])
9440 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9443 - (void) _setSuspended:(BOOL)value {
9444 if ([self isSafeToSuspend])
9445 [super _setSuspended:value];
9448 - (UIProgressHUD *) addProgressHUD {
9449 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9450 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9452 [window_ setUserInteractionEnabled:NO];
9454 UIViewController *target(tabbar_);
9455 if (UIViewController *modal = [target modalViewController])
9458 [hud showInView:[target view]];
9464 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9467 [hud removeFromSuperview];
9468 [window_ setUserInteractionEnabled:YES];
9471 - (CyteViewController *) pageForPackage:(NSString *)name {
9472 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9475 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9476 NSString *scheme([[url scheme] lowercaseString]);
9477 if ([[url absoluteString] length] <= [scheme length] + 3)
9479 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9480 NSArray *components([path componentsSeparatedByString:@"/"]);
9482 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9483 return [self pageForPackage:[components objectAtIndex:1]];
9485 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9488 NSString *base([components objectAtIndex:0]);
9490 CyteViewController *controller = nil;
9492 if ([base isEqualToString:@"url"]) {
9493 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9494 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9495 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9496 } else if (!external && [components count] == 1) {
9497 if ([base isEqualToString:@"manage"]) {
9498 controller = [[[ManageController alloc] init] autorelease];
9501 if ([base isEqualToString:@"sources"]) {
9502 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9505 if ([base isEqualToString:@"home"]) {
9506 controller = [[[HomeController alloc] init] autorelease];
9509 if ([base isEqualToString:@"sections"]) {
9510 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9513 if ([base isEqualToString:@"search"]) {
9514 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9517 if ([base isEqualToString:@"changes"]) {
9518 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9521 if ([base isEqualToString:@"installed"]) {
9522 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9524 } else if ([components count] == 2) {
9525 NSString *argument = [components objectAtIndex:1];
9527 if ([base isEqualToString:@"package"]) {
9528 controller = [self pageForPackage:argument];
9531 if (!external && [base isEqualToString:@"search"]) {
9532 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9535 if (!external && [base isEqualToString:@"sections"]) {
9536 if ([argument isEqualToString:@"all"])
9538 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9541 if (!external && [base isEqualToString:@"sources"]) {
9542 if ([argument isEqualToString:@"add"]) {
9543 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9544 [(SourcesController *)controller showAddSourcePrompt];
9546 Source *source = [database_ sourceWithKey:[argument stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
9547 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9551 if (!external && [base isEqualToString:@"launch"]) {
9552 [self launchApplicationWithIdentifier:argument suspended:NO];
9555 } else if (!external && [components count] == 3) {
9556 NSString *arg1 = [components objectAtIndex:1];
9557 NSString *arg2 = [components objectAtIndex:2];
9559 if ([base isEqualToString:@"package"]) {
9560 if ([arg2 isEqualToString:@"settings"]) {
9561 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9562 } else if ([arg2 isEqualToString:@"files"]) {
9563 if (Package *package = [database_ packageWithName:arg1]) {
9564 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9565 [(FileTable *)controller setPackage:package];
9571 [controller setDelegate:self];
9575 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9576 CyteViewController *page([self pageForURL:url forExternal:external]);
9579 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9580 [nav setViewControllers:[NSArray arrayWithObject:page]];
9581 [tabbar_ setUnselectedViewController:nav];
9587 - (void) applicationOpenURL:(NSURL *)url {
9588 [super applicationOpenURL:url];
9593 [self openCydiaURL:url forExternal:YES];
9596 - (void) applicationWillResignActive:(UIApplication *)application {
9597 // Stop refreshing if you get a phone call or lock the device.
9598 if ([tabbar_ updating])
9599 [tabbar_ cancelUpdate];
9601 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9602 [super applicationWillResignActive:application];
9605 - (void) saveState {
9606 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9607 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9608 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9614 - (void) applicationWillTerminate:(UIApplication *)application {
9618 - (void) setConfigurationData:(NSString *)data {
9619 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9621 if (!conffile_r(data)) {
9622 lprintf("E:invalid conffile\n");
9626 NSString *ofile = conffile_r[1];
9627 //NSString *nfile = conffile_r[2];
9629 UIAlertView *alert = [[[UIAlertView alloc]
9630 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9631 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9633 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9635 UCLocalize("ACCEPT_NEW_COPY"),
9636 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9640 [alert setContext:@"conffile"];
9641 [alert setNumberOfRows:2];
9645 - (void) addStashController {
9647 stash_ = [[[StashController alloc] init] autorelease];
9648 [window_ addSubview:[stash_ view]];
9651 - (void) removeStashController {
9652 [[stash_ view] removeFromSuperview];
9658 [self setIdleTimerDisabled:YES];
9660 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9661 UpdateExternalStatus(1);
9662 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9663 UpdateExternalStatus(0);
9665 [self removeStashController];
9667 if (ExecFork() == 0) {
9668 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9669 perror("launchctl stop");
9673 - (void) setupViewControllers {
9674 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9676 NSMutableArray *items([NSMutableArray arrayWithObjects:
9677 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9678 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9679 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9680 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9684 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9685 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9687 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9690 NSMutableArray *controllers([NSMutableArray array]);
9691 for (UITabBarItem *item in items) {
9692 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9693 [controller setTabBarItem:item];
9694 [controllers addObject:controller];
9696 [tabbar_ setViewControllers:controllers];
9698 [tabbar_ setUpdateDelegate:self];
9701 - (void) _sendMemoryWarningNotification {
9702 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9705 - (void) _sendMemoryWarningNotifications {
9707 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9712 - (void) applicationDidFinishLaunching:(id)unused {
9713 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9716 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9717 [self setApplicationSupportsShakeToEdit:NO];
9719 @synchronized (HostConfig_) {
9720 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9723 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9724 initWithMemoryCapacity:524288
9725 diskCapacity:10485760
9726 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9729 [CydiaWebViewController _initialize];
9731 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9733 // this would disallow http{,s} URLs from accessing this data
9734 //[WebView registerURLSchemeAsLocal:@"cydia"];
9736 Font12_ = [UIFont systemFontOfSize:12];
9737 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9738 Font14_ = [UIFont systemFontOfSize:14];
9739 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9740 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9742 essential_ = [NSMutableArray arrayWithCapacity:4];
9743 broken_ = [NSMutableArray arrayWithCapacity:4];
9745 // XXX: I really need this thing... like, seriously... I'm sorry
9746 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9748 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9749 [window_ orderFront:self];
9750 [window_ makeKey:self];
9751 [window_ setHidden:NO];
9754 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9755 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9756 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9757 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9758 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9759 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9760 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9761 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9762 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9765 [self addStashController];
9766 // XXX: this would be much cleaner as a yieldToSelector:
9767 // that way the removeStashController could happen right here inline
9768 // we also could no longer require the useless stash_ field anymore
9769 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9773 database_ = [Database sharedInstance];
9774 [database_ setDelegate:self];
9776 [window_ setUserInteractionEnabled:NO];
9777 [self setupViewControllers];
9779 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9780 [window_ addSubview:[emulated_ view]];
9782 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9786 - (NSArray *) defaultStartPages {
9787 NSMutableArray *standard = [NSMutableArray array];
9788 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9789 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9790 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9792 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9794 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9795 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9797 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9804 [window_ setUserInteractionEnabled:YES];
9805 [self showSettings];
9808 if ([emulated_ modalViewController] != nil)
9809 [emulated_ dismissModalViewControllerAnimated:YES];
9810 [window_ setUserInteractionEnabled:NO];
9813 [self reloadDataWithInvocation:nil];
9814 [self refreshIfPossible];
9819 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9820 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9821 int standardIndex = 0;
9822 NSArray *standard = [self defaultStartPages];
9829 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9830 if (valid && closed != nil) {
9831 NSTimeInterval interval([closed timeIntervalSinceNow]);
9832 // XXX: Is 15 minutes the optimal time here?
9833 if (interval > 0 && interval <= -(15*60))
9837 if (valid && [saved count] != [standard count])
9841 for (unsigned int i = 0; i < [standard count]; i++) {
9842 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9843 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9844 // but it's good enough for now.
9845 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9852 NSArray *items = nil;
9854 [tabbar_ setSelectedIndex:savedIndex];
9857 [tabbar_ setSelectedIndex:standardIndex];
9861 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9862 NSArray *stack = [items objectAtIndex:tab];
9863 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9864 NSMutableArray *current = [NSMutableArray array];
9866 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9867 NSString *addr = [stack objectAtIndex:nav];
9868 NSURL *url = [NSURL URLWithString:addr];
9869 CyteViewController *page = [self pageForURL:url forExternal:NO];
9871 [current addObject:page];
9874 [navigation setViewControllers:current];
9877 // (Try to) show the startup URL.
9878 if (starturl_ != nil) {
9879 [self openCydiaURL:starturl_ forExternal:NO];
9884 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9885 if (item != nil && IsWildcat_) {
9886 [sheet showFromBarButtonItem:item animated:YES];
9888 [sheet showInView:window_];
9892 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9893 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9894 [progress setTitle:task];
9895 [progress addProgressEvent:event];
9898 - (void) addProgressEventForTask:(NSArray *)data {
9899 CydiaProgressEvent *event([data objectAtIndex:0]);
9900 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9901 [self addProgressEvent:event forTask:task];
9904 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9905 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9911 id Alloc_(id self, SEL selector) {
9912 id object = alloc_(self, selector);
9913 lprintf("[%s]A-%p\n", self->isa->name, object);
9918 id Dealloc_(id self, SEL selector) {
9919 id object = dealloc_(self, selector);
9920 lprintf("[%s]D-%p\n", self->isa->name, object);
9924 Class $WebDefaultUIKitDelegate;
9926 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9927 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9928 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9929 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9932 static NSSet *MobilizedFiles_;
9934 static NSURL *MobilizeURL(NSURL *url) {
9935 NSString *path([url path]);
9936 if ([path hasPrefix:@"/var/root/"]) {
9937 NSString *file([path substringFromIndex:10]);
9938 if ([MobilizedFiles_ containsObject:file])
9939 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9945 Class $CFXPreferencesPropertyListSource;
9946 @class CFXPreferencesPropertyListSource;
9948 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9949 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9950 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9951 url = MobilizeURL(url);
9952 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9953 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9959 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9960 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9961 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9962 url = MobilizeURL(url);
9963 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9964 //NSLog(@"%@ %@", [url absoluteString], value);
9970 Class $NSURLConnection;
9972 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9973 NSMutableURLRequest *copy([request mutableCopy]);
9975 NSURL *url([copy URL]);
9977 NSString *href([url absoluteString]);
9978 NSString *host([url host]);
9979 NSString *scheme([[url scheme] lowercaseString]);
9981 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9983 @synchronized (HostConfig_) {
9984 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9985 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9986 [copy setHTTPShouldUsePipelining:YES];
9988 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9989 if ([control isEqualToString:@"max-age=0"])
9990 if ([CachedURLs_ containsObject:href]) {
9992 NSLog(@"~~~: %@", href);
9995 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9997 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9998 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9999 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10003 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10007 int main(int argc, char *argv[]) {
10008 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10012 UpdateExternalStatus(0);
10014 if (Class $UIDevice = objc_getClass("UIDevice")) {
10015 UIDevice *device([$UIDevice currentDevice]);
10016 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
10018 IsWildcat_ = false;
10020 UIScreen *screen([UIScreen mainScreen]);
10021 if ([screen respondsToSelector:@selector(scale)])
10022 ScreenScale_ = [screen scale];
10026 UIDevice *device([UIDevice currentDevice]);
10027 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
10028 Idiom_ = @"iphone";
10030 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10031 if (idiom == UIUserInterfaceIdiomPhone)
10032 Idiom_ = @"iphone";
10033 else if (idiom == UIUserInterfaceIdiomPad)
10036 NSLog(@"unknown UIUserInterfaceIdiom!");
10039 Pcre pattern("^([0-9]+\\.[0-9]+)");
10041 if (pattern([device systemVersion]))
10042 Firmware_ = pattern[1];
10043 if (pattern(Cydia_))
10044 Major_ = pattern[1];
10046 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10048 HostConfig_ = [[[NSObject alloc] init] autorelease];
10049 @synchronized (HostConfig_) {
10050 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10051 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10052 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10053 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10054 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10057 NSString *ui(@"ui/ios");
10059 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10060 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10061 UI_ = CydiaURL(ui);
10063 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10065 MobilizedFiles_ = [NSMutableSet setWithObjects:
10066 @"Library/Preferences/com.apple.Accessibility.plist",
10067 @"Library/Preferences/com.apple.preferences.sounds.plist",
10070 /* Library Hacks {{{ */
10071 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10073 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10075 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10076 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10077 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10078 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10081 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10082 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10083 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10084 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10087 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10088 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10089 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10090 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10091 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10094 $NSURLConnection = objc_getClass("NSURLConnection");
10095 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10096 if (NSURLConnection$init$ != NULL) {
10097 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10098 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10101 /* Set Locale {{{ */
10102 Locale_ = CFLocaleCopyCurrent();
10103 Languages_ = [NSLocale preferredLanguages];
10105 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10106 //NSLog(@"%@", [Languages_ description]);
10109 if (Locale_ != NULL)
10110 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10111 else if (Languages_ != nil && [Languages_ count] != 0)
10112 lang = [[Languages_ objectAtIndex:0] UTF8String];
10114 // XXX: consider just setting to C and then falling through?
10117 if (lang != NULL) {
10118 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10119 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10122 NSLog(@"Setting Language: %s", lang);
10124 if (lang != NULL) {
10125 setenv("LANG", lang, true);
10126 std::setlocale(LC_ALL, lang);
10130 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10132 /* Parse Arguments {{{ */
10133 bool substrate(false);
10139 for (int argi(1); argi != argc; ++argi)
10140 if (strcmp(argv[argi], "--") == 0) {
10142 argv[argi] = argv[0];
10148 for (int argi(1); argi != arge; ++argi)
10149 if (strcmp(args[argi], "--substrate") == 0)
10152 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10156 App_ = [[NSBundle mainBundle] bundlePath];
10162 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10163 alloc_ = alloc->method_imp;
10164 alloc->method_imp = (IMP) &Alloc_;*/
10166 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10167 dealloc_ = dealloc->method_imp;
10168 dealloc->method_imp = (IMP) &Dealloc_;*/
10170 /* System Information {{{ */
10174 size = sizeof(maxproc);
10175 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10176 perror("sysctlbyname(\"kern.maxproc\", ?)");
10177 else if (maxproc < 64) {
10179 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10180 perror("sysctlbyname(\"kern.maxproc\", #)");
10183 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10184 char *osversion = new char[size];
10185 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10186 perror("sysctlbyname(\"kern.osversion\", ?)");
10188 System_ = [NSString stringWithUTF8String:osversion];
10190 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10191 char *machine = new char[size];
10192 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10193 perror("sysctlbyname(\"hw.machine\", ?)");
10195 Machine_ = machine;
10197 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10198 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10199 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10201 UniqueID_ = [device uniqueIdentifier];
10203 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10204 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10205 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10207 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10208 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10209 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10211 if (mcc != NULL && mnc != NULL)
10212 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10219 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10220 Build_ = [system objectForKey:@"ProductBuildVersion"];
10221 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10222 Product_ = [info objectForKey:@"SafariProductVersion"];
10223 Safari_ = [info objectForKey:@"CFBundleVersion"];
10226 /* Load Database {{{ */
10228 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10230 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10232 if (Metadata_ == NULL)
10233 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10235 Settings_ = [Metadata_ objectForKey:@"Settings"];
10237 Packages_ = [Metadata_ objectForKey:@"Packages"];
10239 Values_ = [Metadata_ objectForKey:@"Values"];
10240 Sections_ = [Metadata_ objectForKey:@"Sections"];
10241 Sources_ = [Metadata_ objectForKey:@"Sources"];
10243 Token_ = [Metadata_ objectForKey:@"Token"];
10245 Version_ = [Metadata_ objectForKey:@"Version"];
10247 @synchronized (HostConfig_) {
10248 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10252 if (Settings_ != nil)
10253 Role_ = [Settings_ objectForKey:@"Role"];
10255 if (Values_ == nil) {
10256 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10257 [Metadata_ setObject:Values_ forKey:@"Values"];
10260 if (Sections_ == nil) {
10261 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10262 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10265 if (Sources_ == nil) {
10266 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10267 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10270 if (Version_ == nil) {
10271 Version_ = [NSNumber numberWithUnsignedInt:0];
10272 [Metadata_ setObject:Version_ forKey:@"Version"];
10275 @synchronized (HostConfig_) {
10276 if (CydiaSource_ == nil) {
10277 CydiaSource_ = @"apt.saurik.com";
10278 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10282 if ([Version_ unsignedIntValue] == 0) {
10283 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10284 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10285 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10286 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10288 Version_ = [NSNumber numberWithUnsignedInt:1];
10289 [Metadata_ setObject:Version_ forKey:@"Version"];
10291 [Metadata_ removeObjectForKey:@"LastUpdate"];
10297 CydiaWriteSources();
10300 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10303 if (Packages_ != nil) {
10305 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10309 [Metadata_ removeObjectForKey:@"Packages"];
10315 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10317 #define MobileSubstrate_(name) \
10318 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10319 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10320 if (handle == NULL) \
10321 NSLog(@"%s", dlerror()); \
10324 MobileSubstrate_(Activator)
10325 MobileSubstrate_(libstatusbar)
10326 MobileSubstrate_(SimulatedKeyEvents)
10327 MobileSubstrate_(WinterBoard)
10329 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10330 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10332 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10334 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10335 unlink("/tmp/.cydia.fw");
10337 } else if (access("/User", F_OK) != 0 || version < 4) {
10340 system("/usr/libexec/cydia/firmware.sh");
10344 _assert([[NSFileManager defaultManager]
10345 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10346 withIntermediateDirectories:YES
10351 if (access("/tmp/cydia.chk", F_OK) == 0) {
10352 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10353 _assert(errno == ENOENT);
10354 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10355 _assert(errno == ENOENT);
10358 /* APT Initialization {{{ */
10359 _assert(pkgInitConfig(*_config));
10360 _assert(pkgInitSystem(*_config, _system));
10363 _config->Set("APT::Acquire::Translation", lang);
10365 // XXX: this timeout might be important :(
10366 //_config->Set("Acquire::http::Timeout", 15);
10368 _config->Set("Acquire::http::MaxParallel", 3);
10370 /* Color Choices {{{ */
10371 space_ = CGColorSpaceCreateDeviceRGB();
10373 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10374 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10375 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10376 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10377 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10378 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10379 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10380 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10381 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10383 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10384 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10386 /* UIKit Configuration {{{ */
10387 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10388 if ($GSFontSetUseLegacyFontMetrics != NULL)
10389 $GSFontSetUseLegacyFontMetrics(YES);
10391 // XXX: I have a feeling this was important
10392 //UIKeyboardDisableAutomaticAppearance();
10395 Colon_ = UCLocalize("COLON_DELIMITED");
10396 Elision_ = UCLocalize("ELISION");
10397 Error_ = UCLocalize("ERROR");
10398 Warning_ = UCLocalize("WARNING");
10401 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10403 CGColorSpaceRelease(space_);
10404 CFRelease(Locale_);