1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <QuartzCore/CALayer.h>
53 #include <WebCore/WebCoreThread.h>
62 #include "fdstream.hpp"
67 #include <apt-pkg/acquire.h>
68 #include <apt-pkg/acquire-item.h>
69 #include <apt-pkg/algorithms.h>
70 #include <apt-pkg/cachefile.h>
71 #include <apt-pkg/clean.h>
72 #include <apt-pkg/configuration.h>
73 #include <apt-pkg/debindexfile.h>
74 #include <apt-pkg/debmetaindex.h>
75 #include <apt-pkg/error.h>
76 #include <apt-pkg/init.h>
77 #include <apt-pkg/mmap.h>
78 #include <apt-pkg/pkgrecords.h>
79 #include <apt-pkg/sha1.h>
80 #include <apt-pkg/sourcelist.h>
81 #include <apt-pkg/sptr.h>
82 #include <apt-pkg/strutl.h>
83 #include <apt-pkg/tagfile.h>
85 #include <sys/types.h>
87 #include <sys/sysctl.h>
88 #include <sys/param.h>
89 #include <sys/mount.h>
90 #include <sys/reboot.h>
98 #include <mach-o/nlist.h>
107 #include <Cytore.hpp>
110 #include "Substrate.hpp"
111 #include "Menes/Menes.h"
113 #include "CyteKit/CyteKit.h"
114 #include "CyteKit/RegEx.hpp"
116 #include "Cydia/MIMEAddress.h"
117 #include "Cydia/LoadingViewController.h"
118 #include "Cydia/ProgressEvent.h"
125 #define _timestamp ({ \
127 gettimeofday(&tv, NULL); \
128 tv.tv_sec * 1000000 + tv.tv_usec; \
131 typedef std::vector<class ProfileTime *> TimeList;
141 ProfileTime(const char *name) :
145 times_.push_back(this);
148 void AddTime(uint64_t time) {
155 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
167 ProfileTimer(ProfileTime &time) :
174 time_.AddTime(_timestamp - start_);
179 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
181 std::cerr << "========" << std::endl;
184 #define _profile(name) { \
185 static ProfileTime name(#name); \
186 ProfileTimer _ ## name(name);
191 extern NSString *Cydia_;
193 #define lprintf(args...) fprintf(stderr, args)
196 #define TraceLogging (1 && !ForRelease)
197 #define HistogramInsertionSort (0 && !ForRelease)
198 #define ProfileTimes (0 && !ForRelease)
199 #define ForSaurik (0 && !ForRelease)
200 #define LogBrowser (0 && !ForRelease)
201 #define TrackResize (0 && !ForRelease)
202 #define ManualRefresh (1 && !ForRelease)
203 #define ShowInternals (0 && !ForRelease)
204 #define AlwaysReload (0 && !ForRelease)
208 #define _trace(args...)
213 #define _profile(name) {
216 #define PrintTimes() do {} while (false)
219 // Hash Functions/Structures {{{
220 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
228 static NSString *Colon_;
230 static NSString *Error_;
231 static NSString *Warning_;
233 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
234 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
236 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
238 static NSString *UniqueIdentifier(UIDevice *device = nil) {
239 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
240 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
242 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
245 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
247 static _finline NSString *CydiaURL(NSString *path) {
249 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
250 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
251 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
252 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
253 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
255 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
258 static NSString *ShellEscape(NSString *value) {
259 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
262 static _finline void UpdateExternalStatus(uint64_t newStatus) {
264 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
265 notify_set_state(notify_token, newStatus);
266 notify_cancel(notify_token);
268 notify_post("com.saurik.Cydia.status");
271 /* NSForcedOrderingSearch doesn't work on the iPhone */
272 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
273 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
274 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
276 /* Insertion Sort {{{ */
278 template <typename Type_>
279 size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
280 const char *ptr = (const char *)list;
282 size_t half = count / 2;
283 const char *probe = ptr + sizeof(Type_) * half;
284 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
285 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
286 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
287 count = (cr < 0) ? half : (half + (count & 1) - 1);
289 return (ptr - (const char *)list) / sizeof(Type_);
292 template <typename Type_>
293 void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
297 #if HistogramInsertionSort > 0
298 uint32_t total(0), *offsets(new uint32_t[length]);
301 for (size_t index(1); index != length; ++index) {
302 Type_ value(values[index]);
304 size_t correct(CFBSearch_(value, values, index, comparator, context));
306 size_t correct(index);
307 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
308 #if HistogramInsertionSort > 1
309 NSLog(@"%@ < %@", value, values[correct - 1]);
313 if (index - correct >= 8) {
314 correct = CFBSearch_(value, values, correct, comparator, context);
319 if (correct != index) {
320 size_t offset(index - correct);
321 #if HistogramInsertionSort
325 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
327 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
328 values[correct] = value;
332 #if HistogramInsertionSort > 0
333 for (size_t index(0); index != range.length; ++index)
334 if (offsets[index] != 0)
335 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
336 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
343 /* Cydia NSString Additions {{{ */
344 @interface NSString (Cydia)
345 - (NSComparisonResult) compareByPath:(NSString *)other;
346 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
349 @implementation NSString (Cydia)
351 - (NSComparisonResult) compareByPath:(NSString *)other {
352 NSString *prefix = [self commonPrefixWithString:other options:0];
353 size_t length = [prefix length];
355 NSRange lrange = NSMakeRange(length, [self length] - length);
356 NSRange rrange = NSMakeRange(length, [other length] - length);
358 lrange = [self rangeOfString:@"/" options:0 range:lrange];
359 rrange = [other rangeOfString:@"/" options:0 range:rrange];
361 NSComparisonResult value;
363 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
364 value = NSOrderedSame;
365 else if (lrange.location == NSNotFound)
366 value = NSOrderedAscending;
367 else if (rrange.location == NSNotFound)
368 value = NSOrderedDescending;
370 value = NSOrderedSame;
372 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
373 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
374 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
375 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
377 NSComparisonResult result = [lpath compare:rpath];
378 return result == NSOrderedSame ? value : result;
381 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
382 return [(id)CFURLCreateStringByAddingPercentEscapes(
387 kCFStringEncodingUTF8
394 /* C++ NSString Wrapper Cache {{{ */
395 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
396 return size == 0 ? NULL :
397 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
398 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
401 static _finline CFStringRef CYStringCreate(const std::string &data) {
402 return CYStringCreate(data.data(), data.size());
405 static _finline CFStringRef CYStringCreate(const char *data) {
406 return CYStringCreate(data, strlen(data));
415 _finline void clear_() {
416 if (cache_ != NULL) {
423 _finline bool empty() const {
427 _finline size_t size() const {
431 _finline char *data() const {
435 _finline void clear() {
440 _finline CYString() :
447 _finline ~CYString() {
451 void operator =(const CYString &rhs) {
455 if (rhs.cache_ == nil)
458 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
461 void copy(CYPool *pool) {
462 char *temp(pool->malloc<char>(size_ + 1));
463 memcpy(temp, data_, size_);
468 void set(CYPool *pool, const char *data, size_t size) {
474 data_ = const_cast<char *>(data);
482 _finline void set(CYPool *pool, const char *data) {
483 set(pool, data, data == NULL ? 0 : strlen(data));
486 _finline void set(CYPool *pool, const std::string &rhs) {
487 set(pool, rhs.data(), rhs.size());
490 bool operator ==(const CYString &rhs) const {
491 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
494 _finline operator CFStringRef() {
496 cache_ = CYStringCreate(data_, size_);
500 _finline operator id() {
501 return (NSString *) static_cast<CFStringRef>(*this);
504 _finline operator const char *() {
505 return reinterpret_cast<const char *>(data_);
509 /* C++ NSString Algorithm Adapters {{{ */
511 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
514 struct NSStringMapHash :
515 std::unary_function<NSString *, size_t>
517 _finline size_t operator ()(NSString *value) const {
518 return CFStringHashNSString((CFStringRef) value);
522 struct NSStringMapLess :
523 std::binary_function<NSString *, NSString *, bool>
525 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
526 return [lhs compare:rhs] == NSOrderedAscending;
530 struct NSStringMapEqual :
531 std::binary_function<NSString *, NSString *, bool>
533 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
534 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
535 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
536 //[lhs isEqualToString:rhs];
541 /* CoreGraphics Primitives {{{ */
546 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
547 CGFloat color[] = {red, green, blue, alpha};
548 return CGColorCreate(space, color);
557 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
558 color_(Create_(space, red, green, blue, alpha))
560 Set(space, red, green, blue, alpha);
565 CGColorRelease(color_);
572 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
574 color_ = Create_(space, red, green, blue, alpha);
577 operator CGColorRef() {
583 /* Random Global Variables {{{ */
584 static int PulseInterval_ = 500000;
586 static const NSString *UI_;
589 static bool RestartSubstrate_;
590 static NSArray *Finishes_;
592 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
593 #define NotifyConfig_ "/etc/notify.conf"
595 static bool Queuing_;
597 static CYColor Blue_;
598 static CYColor Blueish_;
599 static CYColor Black_;
600 static CYColor Folder_;
602 static CYColor White_;
603 static CYColor Gray_;
604 static CYColor Green_;
605 static CYColor Purple_;
606 static CYColor Purplish_;
608 static UIColor *InstallingColor_;
609 static UIColor *RemovingColor_;
611 static NSString *App_;
613 static BOOL Advanced_;
614 static BOOL Ignored_;
616 static _H<UIFont> Font12_;
617 static _H<UIFont> Font12Bold_;
618 static _H<UIFont> Font14_;
619 static _H<UIFont> Font18_;
620 static _H<UIFont> Font18Bold_;
621 static _H<UIFont> Font22Bold_;
623 static _H<NSString> UniqueID_;
625 static _H<NSLocale> CollationLocale_;
626 static _H<NSArray> CollationThumbs_;
627 static std::vector<NSInteger> CollationOffset_;
628 static _H<NSArray> CollationTitles_;
629 static _H<NSArray> CollationStarts_;
630 static UTransliterator *CollationTransl_;
631 //static Function<NSString *, NSString *> CollationModify_;
633 typedef std::basic_string<UChar> ustring;
634 static ustring CollationString_;
636 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
637 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
638 static struct UReplaceableCallbacks CollationUCalls_ = {
639 .length = [](const UReplaceable *rep) -> int32_t { CUC;
643 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
644 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
645 if (offset >= str.size())
650 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
651 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
652 if (offset >= str.size())
655 U16_GET(str.data(), 0, offset, str.size(), c);
659 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
660 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
661 str.replace(start, limit - start, text, length);
664 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
665 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
666 str.copy(dst, limit - start, start);
669 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
670 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
671 str.replace(dest, 0, str, start, limit - start);
675 static CFLocaleRef Locale_;
676 static NSArray *Languages_;
677 static CGColorSpaceRef space_;
679 #define CacheState_ Cache("CacheState.plist")
680 #define SavedState_ Cache("SavedState.plist")
682 static NSDictionary *SectionMap_;
683 static _H<NSDate> Backgrounded_;
684 static _transient NSMutableDictionary *Values_;
685 static _transient NSMutableDictionary *Sections_;
686 _H<NSMutableDictionary> Sources_;
687 static _transient NSNumber *Version_;
690 static _H<NSMutableDictionary> SessionData_;
691 static _H<NSMutableSet> BridgedHosts_;
692 static _H<NSMutableSet> InsecureHosts_;
694 static NSString *kCydiaProgressEventTypeError = @"Error";
695 static NSString *kCydiaProgressEventTypeInformation = @"Information";
696 static NSString *kCydiaProgressEventTypeStatus = @"Status";
697 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
700 /* Display Helpers {{{ */
701 static _finline const char *StripVersion_(const char *version) {
702 const char *colon(strchr(version, ':'));
703 return colon == NULL ? version : colon + 1;
706 NSString *LocalizeSection(NSString *section) {
707 static RegEx title_r("(.*?) \\((.*)\\)");
708 if (title_r(section)) {
709 NSString *parent(title_r[1]);
710 NSString *child(title_r[2]);
712 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
713 LocalizeSection(parent),
714 LocalizeSection(child)
718 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
721 NSString *Simplify(NSString *title) {
722 const char *data = [title UTF8String];
723 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
725 static RegEx square_r("\\[(.*)\\]");
726 if (square_r(data, size))
727 return Simplify(square_r[1]);
729 static RegEx paren_r("\\((.*)\\)");
730 if (paren_r(data, size))
731 return Simplify(paren_r[1]);
733 static RegEx title_r("(.*?) \\((.*)\\)");
734 if (title_r(data, size))
735 return Simplify(title_r[1]);
741 bool isSectionVisible(NSString *section) {
742 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
743 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
744 return hidden == nil || ![hidden boolValue];
747 static NSString *VerifySource(NSString *href) {
748 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
750 [[[[UIAlertView alloc]
751 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
752 message:UCLocalize("INVALID_URL_EX")
754 cancelButtonTitle:UCLocalize("OK")
755 otherButtonTitles:nil
756 ] autorelease] show];
761 if (![href hasSuffix:@"/"])
762 href = [href stringByAppendingString:@"/"];
768 /* Delegate Prototypes {{{ */
771 @class CydiaProgressEvent;
773 @protocol DatabaseDelegate
774 - (void) repairWithSelector:(SEL)selector;
775 - (void) setConfigurationData:(NSString *)data;
776 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
779 @class CYPackageController;
781 @protocol SourceDelegate
782 - (void) setFetch:(NSNumber *)fetch;
785 @protocol FetchDelegate
786 - (bool) isSourceCancelled;
787 - (void) startSourceFetch:(NSString *)uri;
788 - (void) stopSourceFetch:(NSString *)uri;
791 @protocol CydiaDelegate
792 - (void) returnToCydia;
794 - (void) retainNetworkActivityIndicator;
795 - (void) releaseNetworkActivityIndicator;
796 - (void) clearPackage:(Package *)package;
797 - (void) installPackage:(Package *)package;
798 - (void) installPackages:(NSArray *)packages;
799 - (void) removePackage:(Package *)package;
800 - (void) beginUpdate;
802 - (bool) requestUpdate;
803 - (void) distUpgrade;
806 - (void) _saveConfig;
808 - (void) addSource:(NSDictionary *)source;
809 - (BOOL) addTrivialSource:(NSString *)href;
810 - (UIProgressHUD *) addProgressHUD;
811 - (void) removeProgressHUD:(UIProgressHUD *)hud;
812 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
813 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
817 /* CancelStatus {{{ */
819 public pkgAcquireStatus
830 virtual bool MediaChange(std::string media, std::string drive) {
834 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
838 virtual bool Pulse_(pkgAcquire *Owner) = 0;
840 virtual bool Pulse(pkgAcquire *Owner) {
841 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
849 _finline bool WasCancelled() const {
854 /* DelegateStatus {{{ */
859 _transient NSObject<ProgressDelegate> *delegate_;
867 void setDelegate(NSObject<ProgressDelegate> *delegate) {
868 delegate_ = delegate;
871 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
872 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
873 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
874 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
877 virtual void Done(pkgAcquire::ItemDesc &desc) {
878 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
879 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
880 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
883 virtual void Fail(pkgAcquire::ItemDesc &desc) {
885 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
886 desc.Owner->Status == pkgAcquire::Item::StatDone
890 std::string &error(desc.Owner->ErrorText);
894 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
895 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
898 virtual bool Pulse_(pkgAcquire *Owner) {
900 double(CurrentBytes + CurrentItems) /
901 double(TotalBytes + TotalItems)
904 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
905 [NSNumber numberWithDouble:percent], @"Percent",
907 [NSNumber numberWithDouble:CurrentBytes], @"Current",
908 [NSNumber numberWithDouble:TotalBytes], @"Total",
909 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
910 nil] waitUntilDone:YES];
912 return ![delegate_ isProgressCancelled];
915 virtual void Start() {
916 pkgAcquireStatus::Start();
917 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
920 virtual void Stop() {
921 pkgAcquireStatus::Stop();
922 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
923 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
927 /* Database Interface {{{ */
928 typedef std::map< unsigned long, _H<Source> > SourceMap;
930 @interface Database : NSObject {
938 pkgDepCache::Policy *policy_;
939 pkgRecords *records_;
940 pkgProblemResolver *resolver_;
941 pkgAcquire *fetcher_;
943 SPtr<pkgPackageManager> manager_;
944 pkgSourceList *list_;
946 SourceMap sourceMap_;
947 _H<NSMutableArray> sourceList_;
949 _H<NSArray> packages_;
951 _transient NSObject<DatabaseDelegate> *delegate_;
952 _transient NSObject<ProgressDelegate> *progress_;
960 std::map<const char *, _H<NSString> > sections_;
963 + (Database *) sharedInstance;
965 - (bool) hasPackages;
967 - (void) _readCydia:(NSNumber *)fd;
968 - (void) _readStatus:(NSNumber *)fd;
969 - (void) _readOutput:(NSNumber *)fd;
973 - (Package *) packageWithName:(NSString *)name;
975 - (pkgCacheFile &) cache;
976 - (pkgDepCache::Policy *) policy;
977 - (pkgRecords *) records;
978 - (pkgProblemResolver *) resolver;
979 - (pkgAcquire &) fetcher;
980 - (pkgSourceList &) list;
981 - (NSArray *) packages;
982 - (NSArray *) sources;
983 - (Source *) sourceWithKey:(NSString *)key;
984 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
992 - (void) updateWithStatus:(CancelStatus &)status;
994 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
996 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
997 - (NSObject<ProgressDelegate> *) progressDelegate;
999 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1000 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1001 - (void) resetFetch;
1003 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1007 /* SourceStatus {{{ */
1008 class SourceStatus :
1012 _transient NSObject<FetchDelegate> *delegate_;
1013 _transient Database *database_;
1014 std::set<std::string> fetches_;
1017 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1018 delegate_(delegate),
1023 void Set(bool fetch, const std::string &uri) {
1025 if (!fetches_.insert(uri).second)
1028 if (fetches_.erase(uri) == 0)
1032 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1034 auto slash(uri.rfind('/'));
1035 if (slash != std::string::npos)
1036 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1039 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1040 /*unsigned long ID(fetch ? 1 : 0);
1044 Set(fetch, item->DescURI());
1047 void Log(const char *tag, pkgAcquire::Item *item) {
1048 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1051 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1052 Log("Fetch", desc.Owner);
1053 Set(true, desc.Owner);
1056 virtual void Done(pkgAcquire::ItemDesc &desc) {
1057 Log("Done", desc.Owner);
1058 Set(false, desc.Owner);
1061 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1062 Log("Fail", desc.Owner);
1063 Set(false, desc.Owner);
1066 virtual bool Pulse_(pkgAcquire *Owner) {
1067 std::set<std::string> fetches;
1068 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1070 if ((*item)->QueueCounter == 0)
1072 else switch ((*item)->Status) {
1073 case pkgAcquire::Item::StatFetching:
1074 fetches.insert((*item)->DescURI());
1083 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1087 std::vector<std::string> stops;
1088 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1089 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1090 //printf("Stop(%s)\n", stop->c_str());
1094 return ![delegate_ isSourceCancelled];
1097 virtual void Stop() {
1098 pkgAcquireStatus::Stop();
1099 [database_ resetFetch];
1103 /* ProgressEvent Implementation {{{ */
1104 @implementation CydiaProgressEvent
1106 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1107 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1110 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1111 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1112 [event setPackage:package];
1116 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1117 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1119 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1120 NSArray *fields([description componentsSeparatedByString:@" "]);
1121 [event setItem:fields];
1123 if ([fields count] > 3) {
1124 [event setPackage:[fields objectAtIndex:2]];
1125 [event setVersion:[fields objectAtIndex:3]];
1128 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1133 + (NSArray *) _attributeKeys {
1134 return [NSArray arrayWithObjects:
1144 - (NSArray *) attributeKeys {
1145 return [[self class] _attributeKeys];
1148 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1149 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1152 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1153 if ((self = [super init]) != nil) {
1159 - (NSString *) message {
1163 - (NSString *) type {
1167 - (NSArray *) item {
1168 return (id) item_ ?: [NSNull null];
1171 - (void) setItem:(NSArray *)item {
1175 - (NSString *) package {
1176 return (id) package_ ?: [NSNull null];
1179 - (void) setPackage:(NSString *)package {
1183 - (NSString *) url {
1184 return (id) url_ ?: [NSNull null];
1187 - (void) setURL:(NSString *)url {
1191 - (void) setVersion:(NSString *)version {
1195 - (NSString *) version {
1196 return (id) version_ ?: [NSNull null];
1199 - (NSString *) compound:(NSString *)value {
1201 NSString *mode(nil); {
1202 NSString *type([self type]);
1203 if ([type isEqualToString:kCydiaProgressEventTypeError])
1204 mode = UCLocalize("ERROR");
1205 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1206 mode = UCLocalize("WARNING");
1210 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1216 - (NSString *) compoundMessage {
1217 return [self compound:[self message]];
1220 - (NSString *) compoundTitle {
1223 if (package_ == nil)
1225 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1226 title = [package name];
1230 return [self compound:title];
1236 // Cytore Definitions {{{
1237 struct PackageValue :
1240 Cytore::Offset<PackageValue> next_;
1242 uint32_t index_ : 23;
1243 uint32_t subscribed_ : 1;
1260 Cytore::Offset<PackageValue> packages_[1 << 16];
1263 static Cytore::File<MetaValue> MetaFile_;
1265 // Cytore Helper Functions {{{
1266 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1267 SplitHash nhash = { hashlittle(name, length) };
1269 PackageValue *metadata;
1271 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1272 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1273 *offset = MetaFile_.New<PackageValue>(length + 1);
1274 metadata = &MetaFile_.Get(*offset);
1276 if (metadata == NULL) {
1280 metadata = new PackageValue();
1281 memset(metadata, 0, sizeof(*metadata));
1284 memcpy(metadata->name_, name, length);
1285 metadata->name_[length] = '\0';
1286 metadata->nhash_ = nhash.u16[1];
1288 metadata = &MetaFile_.Get(*offset);
1289 if (metadata->nhash_ != nhash.u16[1])
1291 if (strncmp(metadata->name_, name, length) != 0)
1293 if (metadata->name_[length] != '\0')
1300 static void PackageImport(const void *key, const void *value, void *context) {
1301 bool &fail(*reinterpret_cast<bool *>(context));
1304 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1305 NSLog(@"failed to import package %@", key);
1309 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1310 NSDictionary *package((NSDictionary *) value);
1312 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1313 if ([subscribed boolValue] && !metadata->subscribed_)
1314 metadata->subscribed_ = true;
1316 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1317 time_t time([date timeIntervalSince1970]);
1318 if (metadata->first_ > time || metadata->first_ == 0)
1319 metadata->first_ = time;
1322 NSDate *date([package objectForKey:@"LastSeen"]);
1323 NSString *version([package objectForKey:@"LastVersion"]);
1325 if (date != nil && version != nil) {
1326 time_t time([date timeIntervalSince1970]);
1327 if (metadata->last_ < time || metadata->last_ == 0)
1328 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1329 size_t length(strlen(buffer));
1330 uint16_t vhash(hashlittle(buffer, length));
1332 size_t capped(std::min<size_t>(8, length));
1333 char *latest(buffer + length - capped);
1335 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1336 metadata->vhash_ = vhash;
1338 metadata->last_ = time;
1344 static NSDate *GetStatusDate() {
1345 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1348 static void SaveConfig(NSObject *lock) {
1349 @synchronized (lock) {
1355 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1356 Values_, @"CydiaValues",
1357 Sections_, @"CydiaSections",
1358 (id) Sources_, @"CydiaSources",
1359 Version_, @"CydiaVersion",
1360 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1362 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1363 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1365 CydiaWriteSources();
1368 /* Source Class {{{ */
1369 @interface Source : NSObject {
1371 Database *database_;
1374 CYString depiction_;
1375 CYString description_;
1381 CYString distribution_;
1387 _H<NSString> authority_;
1389 CYString defaultIcon_;
1391 _H<NSMutableDictionary> record_;
1394 std::set<std::string> fetches_;
1395 std::set<std::string> files_;
1396 _transient NSObject<SourceDelegate> *delegate_;
1399 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1401 - (NSComparisonResult) compareByName:(Source *)source;
1403 - (NSString *) depictionForPackage:(NSString *)package;
1404 - (NSString *) supportForPackage:(NSString *)package;
1406 - (metaIndex *) metaIndex;
1407 - (NSDictionary *) record;
1410 - (NSString *) rooturi;
1411 - (NSString *) distribution;
1412 - (NSString *) type;
1415 - (NSString *) host;
1417 - (NSString *) name;
1418 - (NSString *) shortDescription;
1419 - (NSString *) label;
1420 - (NSString *) origin;
1421 - (NSString *) version;
1423 - (NSString *) defaultIcon;
1424 - (NSURL *) iconURL;
1426 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1427 - (void) resetFetch;
1431 @implementation Source
1433 + (NSString *) webScriptNameForSelector:(SEL)selector {
1435 else if (selector == @selector(addSection:))
1436 return @"addSection";
1437 else if (selector == @selector(getField:))
1439 else if (selector == @selector(removeSection:))
1440 return @"removeSection";
1441 else if (selector == @selector(remove))
1447 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1448 return [self webScriptNameForSelector:selector] == nil;
1451 + (NSArray *) _attributeKeys {
1452 return [NSArray arrayWithObjects:
1463 @"shortDescription",
1470 - (NSArray *) attributeKeys {
1471 return [[self class] _attributeKeys];
1474 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1475 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1478 - (metaIndex *) metaIndex {
1482 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1483 trusted_ = index->IsTrusted();
1485 uri_.set(pool, index->GetURI());
1486 distribution_.set(pool, index->GetDist());
1487 type_.set(pool, index->GetType());
1489 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1490 if (dindex != NULL) {
1491 std::string file(dindex->MetaIndexURI(""));
1492 base_.set(pool, file);
1495 _profile(Source$setMetaIndex$GetIndexes)
1496 dindex->GetIndexes(&acquire, true);
1498 _profile(Source$setMetaIndex$DescURI)
1499 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1500 std::string file((*item)->DescURI());
1501 auto slash(file.rfind('/'));
1502 if (slash == std::string::npos)
1504 files_.insert(file.substr(0, slash));
1509 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1512 pkgTagFile tags(&fd);
1514 pkgTagSection section;
1521 {"default-icon", &defaultIcon_},
1522 {"depiction", &depiction_},
1523 {"description", &description_},
1525 {"origin", &origin_},
1526 {"support", &support_},
1527 {"version", &version_},
1530 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1531 const char *start, *end;
1533 if (section.Find(names[i].name_, start, end)) {
1534 CYString &value(*names[i].value_);
1535 value.set(pool, start, end - start);
1541 record_ = [Sources_ objectForKey:[self key]];
1543 NSURL *url([NSURL URLWithString:uri_]);
1547 host_ = [host_ lowercaseString];
1552 authority_ = [url path];
1555 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1556 if ((self = [super init]) != nil) {
1557 era_ = [database era];
1558 database_ = database;
1561 _profile(Source$initWithMetaIndex$setMetaIndex)
1562 [self setMetaIndex:index inPool:pool];
1567 - (NSString *) getField:(NSString *)name {
1568 @synchronized (database_) {
1569 if ([database_ era] != era_ || index_ == NULL)
1572 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1577 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1582 pkgTagFile tags(&fd);
1584 pkgTagSection section;
1587 const char *start, *end;
1588 if (!section.Find([name UTF8String], start, end))
1589 return (NSString *) [NSNull null];
1591 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1594 - (NSComparisonResult) compareByName:(Source *)source {
1595 NSString *lhs = [self name];
1596 NSString *rhs = [source name];
1598 if ([lhs length] != 0 && [rhs length] != 0) {
1599 unichar lhc = [lhs characterAtIndex:0];
1600 unichar rhc = [rhs characterAtIndex:0];
1602 if (isalpha(lhc) && !isalpha(rhc))
1603 return NSOrderedAscending;
1604 else if (!isalpha(lhc) && isalpha(rhc))
1605 return NSOrderedDescending;
1608 return [lhs compare:rhs options:LaxCompareOptions_];
1611 - (NSString *) depictionForPackage:(NSString *)package {
1612 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1615 - (NSString *) supportForPackage:(NSString *)package {
1616 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1619 - (NSArray *) sections {
1620 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1623 - (void) _addSection:(NSString *)section {
1626 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1627 if (![sections containsObject:section])
1628 [sections addObject:section];
1630 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1633 - (bool) addSection:(NSString *)section {
1637 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1641 - (void) _removeSection:(NSString *)section {
1645 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1646 if ([sections containsObject:section])
1647 [sections removeObject:section];
1650 - (bool) removeSection:(NSString *)section {
1654 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1659 [Sources_ removeObjectForKey:[self key]];
1663 bool value(record_ != nil);
1664 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1668 - (NSDictionary *) record {
1676 - (NSString *) rooturi {
1680 - (NSString *) distribution {
1681 return distribution_;
1684 - (NSString *) type {
1688 - (NSString *) baseuri {
1689 return base_.empty() ? nil : (id) base_;
1692 - (NSString *) iconuri {
1693 if (NSString *base = [self baseuri])
1694 return [base stringByAppendingString:@"CydiaIcon.png"];
1699 - (NSURL *) iconURL {
1700 if (NSString *uri = [self iconuri])
1701 return [NSURL URLWithString:uri];
1705 - (NSString *) key {
1706 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1709 - (NSString *) host {
1713 - (NSString *) name {
1714 return origin_.empty() ? (id) authority_ : origin_;
1717 - (NSString *) shortDescription {
1718 return description_;
1721 - (NSString *) label {
1722 return label_.empty() ? (id) authority_ : label_;
1725 - (NSString *) origin {
1729 - (NSString *) version {
1733 - (NSString *) defaultIcon {
1734 return defaultIcon_;
1737 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1738 delegate_ = delegate;
1742 return !fetches_.empty();
1745 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1747 if (fetches_.erase(uri) == 0)
1749 } else if (files_.find(uri) == files_.end())
1751 else if (!fetches_.insert(uri).second)
1754 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1757 - (void) resetFetch {
1759 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1764 /* CydiaOperation Class {{{ */
1765 @interface CydiaOperation : NSObject {
1766 _H<NSString> operator_;
1767 _H<NSString> value_;
1770 - (NSString *) operator;
1771 - (NSString *) value;
1775 @implementation CydiaOperation
1777 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1778 if ((self = [super init]) != nil) {
1779 operator_ = [NSString stringWithUTF8String:_operator];
1780 value_ = [NSString stringWithUTF8String:value];
1784 + (NSArray *) _attributeKeys {
1785 return [NSArray arrayWithObjects:
1791 - (NSArray *) attributeKeys {
1792 return [[self class] _attributeKeys];
1795 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1796 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1799 - (NSString *) operator {
1803 - (NSString *) value {
1809 /* CydiaClause Class {{{ */
1810 @interface CydiaClause : NSObject {
1811 _H<NSString> package_;
1812 _H<CydiaOperation> version_;
1815 - (NSString *) package;
1816 - (CydiaOperation *) version;
1820 @implementation CydiaClause
1822 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1823 if ((self = [super init]) != nil) {
1824 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1826 if (const char *version = dep.TargetVer())
1827 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1829 version_ = (id) [NSNull null];
1833 + (NSArray *) _attributeKeys {
1834 return [NSArray arrayWithObjects:
1840 - (NSArray *) attributeKeys {
1841 return [[self class] _attributeKeys];
1844 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1845 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1848 - (NSString *) package {
1852 - (CydiaOperation *) version {
1858 /* CydiaRelation Class {{{ */
1859 @interface CydiaRelation : NSObject {
1860 _H<NSString> relationship_;
1861 _H<NSMutableArray> clauses_;
1864 - (NSString *) relationship;
1865 - (NSArray *) clauses;
1869 @implementation CydiaRelation
1871 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1872 if ((self = [super init]) != nil) {
1873 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1874 clauses_ = [NSMutableArray arrayWithCapacity:8];
1876 pkgCache::DepIterator start;
1877 pkgCache::DepIterator end;
1878 dep.GlobOr(start, end); // ++dep
1881 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1883 // yes, seriously. (wtf?)
1891 + (NSArray *) _attributeKeys {
1892 return [NSArray arrayWithObjects:
1898 - (NSArray *) attributeKeys {
1899 return [[self class] _attributeKeys];
1902 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1903 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1906 - (NSString *) relationship {
1907 return relationship_;
1910 - (NSArray *) clauses {
1914 - (void) addClause:(CydiaClause *)clause {
1915 [clauses_ addObject:clause];
1920 /* Package Class {{{ */
1921 struct ParsedPackage {
1925 CYString architecture_;
1928 CYString depiction_;
1935 @interface Package : NSObject {
1937 @public uint32_t role_ : 3;
1938 uint32_t essential_ : 1;
1939 uint32_t obsolete_ : 1;
1940 uint32_t ignored_ : 1;
1941 uint32_t pooled_ : 1;
1947 _transient Database *database_;
1949 pkgCache::VerIterator version_;
1950 pkgCache::PkgIterator iterator_;
1951 pkgCache::VerFileIterator file_;
1955 CYString transform_;
1958 CYString installed_;
1961 const char *section_;
1962 _transient NSString *section$_;
1966 PackageValue *metadata_;
1967 ParsedPackage *parsed_;
1969 _H<NSMutableArray> tags_;
1972 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1973 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1975 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1977 - (pkgCache::PkgIterator) iterator;
1980 - (NSString *) section;
1981 - (NSString *) simpleSection;
1983 - (NSString *) longSection;
1984 - (NSString *) shortSection;
1988 - (MIMEAddress *) maintainer;
1990 - (NSString *) longDescription;
1991 - (NSString *) shortDescription;
1994 - (PackageValue *) metadata;
1997 - (bool) subscribed;
1998 - (bool) setSubscribed:(bool)subscribed;
2002 - (NSString *) latest;
2003 - (NSString *) installed;
2004 - (BOOL) uninstalled;
2006 - (BOOL) upgradableAndEssential:(BOOL)essential;
2009 - (BOOL) unfiltered;
2013 - (BOOL) halfConfigured;
2014 - (BOOL) halfInstalled;
2016 - (NSString *) mode;
2019 - (NSString *) name;
2021 - (NSString *) homepage;
2022 - (NSString *) depiction;
2023 - (MIMEAddress *) author;
2025 - (NSString *) support;
2027 - (NSArray *) files;
2028 - (NSArray *) warnings;
2029 - (NSArray *) applications;
2031 - (Source *) source;
2034 - (BOOL) matches:(NSArray *)query;
2036 - (BOOL) hasTag:(NSString *)tag;
2037 - (NSString *) primaryPurpose;
2038 - (NSArray *) purposes;
2039 - (bool) isCommercial;
2041 - (void) setIndex:(size_t)index;
2043 - (CYString &) cyname;
2045 - (uint32_t) compareBySection:(NSArray *)sections;
2052 uint32_t PackageChangesRadix(Package *self, void *) {
2057 uint32_t timestamp : 30;
2058 uint32_t ignored : 1;
2059 uint32_t upgradable : 1;
2063 bool upgradable([self upgradableAndEssential:YES]);
2064 value.bits.upgradable = upgradable ? 1 : 0;
2067 value.bits.timestamp = 0;
2068 value.bits.ignored = [self ignored] ? 0 : 1;
2069 value.bits.upgradable = 1;
2071 value.bits.timestamp = [self seen] >> 2;
2072 value.bits.ignored = 0;
2073 value.bits.upgradable = 0;
2076 return _not(uint32_t) - value.key;
2079 CYString &(*PackageName)(Package *self, SEL sel);
2081 uint32_t PackagePrefixRadix(Package *self, void *context) {
2082 size_t offset(reinterpret_cast<size_t>(context));
2083 CYString &name(PackageName(self, @selector(cyname)));
2085 size_t size(name.size());
2088 char *text(name.data());
2091 if (!isdigit(text[0]))
2095 while (size != digits && isdigit(text[digits]))
2103 if (offset == 0 && zeros != 0) {
2104 memset(data, '0', zeros);
2105 memcpy(data + zeros, text, 4 - zeros);
2107 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2108 if (size <= offset - zeros)
2111 text += offset - zeros;
2112 size -= offset - zeros;
2115 memcpy(data, text, 4);
2117 memcpy(data, text, size);
2118 memset(data + size, 0, 4 - size);
2121 for (size_t i(0); i != 4; ++i)
2122 if (isalpha(data[i]))
2130 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2132 /* XXX: ntohl may be more honest */
2133 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2136 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2137 _profile(PackageNameCompare)
2139 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2140 else if (rhn == NULL)
2141 return kCFCompareGreaterThan;
2143 CFIndex length(CFStringGetLength(lhn));
2145 _profile(PackageNameCompare$NumbersLast)
2146 if (length != 0 && CFStringGetLength(rhn) != 0) {
2147 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2148 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2149 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2150 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2151 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2155 _profile(PackageNameCompare$Compare)
2156 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2161 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2162 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2165 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2166 CYString &lhn(PackageName(lhs, @selector(cyname)));
2167 NSString *rhn(PackageName(rhs, @selector(cyname)));
2168 return StringNameCompare(lhn, rhn, lhn.size());
2171 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2172 return PackageNameCompare(*lhs, *rhs, arg);
2175 struct PackageNameOrdering :
2176 std::binary_function<Package *, Package *, bool>
2178 _finline bool operator ()(Package *lhs, Package *rhs) const {
2179 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2183 @implementation Package
2185 - (NSString *) description {
2186 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2192 if (parsed_ != NULL)
2197 + (NSString *) webScriptNameForSelector:(SEL)selector {
2199 else if (selector == @selector(clear))
2201 else if (selector == @selector(getField:))
2203 else if (selector == @selector(getRecord))
2204 return @"getRecord";
2205 else if (selector == @selector(hasTag:))
2207 else if (selector == @selector(install))
2209 else if (selector == @selector(remove))
2215 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2216 return [self webScriptNameForSelector:selector] == nil;
2219 + (NSArray *) _attributeKeys {
2220 return [NSArray arrayWithObjects:
2241 @"shortDescription",
2254 - (NSArray *) attributeKeys {
2255 return [[self class] _attributeKeys];
2258 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2259 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2262 - (NSArray *) relations {
2263 @synchronized (database_) {
2264 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2265 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2266 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2270 - (NSString *) architecture {
2272 @synchronized (database_) {
2273 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2276 - (NSString *) getField:(NSString *)name {
2277 @synchronized (database_) {
2278 if ([database_ era] != era_ || file_.end())
2281 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2283 const char *start, *end;
2284 if (!parser.Find([name UTF8String], start, end))
2285 return (NSString *) [NSNull null];
2287 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2290 - (NSString *) getRecord {
2291 @synchronized (database_) {
2292 if ([database_ era] != era_ || file_.end())
2295 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2297 const char *start, *end;
2298 parser.GetRec(start, end);
2300 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2304 if (parsed_ != NULL)
2306 @synchronized (database_) {
2307 if ([database_ era] != era_ || file_.end())
2310 ParsedPackage *parsed(new ParsedPackage);
2313 _profile(Package$parse)
2314 pkgRecords::Parser *parser;
2316 _profile(Package$parse$Lookup)
2317 parser = &[database_ records]->Lookup(file_);
2323 _profile(Package$parse$Find)
2328 {"architecture", &parsed->architecture_},
2329 {"icon", &parsed->icon_},
2330 {"depiction", &parsed->depiction_},
2331 {"homepage", &parsed->homepage_},
2332 {"website", &website},
2334 {"support", &parsed->support_},
2335 {"author", &parsed->author_},
2336 {"md5sum", &parsed->md5sum_},
2339 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2340 const char *start, *end;
2342 if (parser->Find(names[i].name_, start, end)) {
2343 CYString &value(*names[i].value_);
2344 _profile(Package$parse$Value)
2345 value.set(pool_, start, end - start);
2351 _profile(Package$parse$Tagline)
2352 parsed->tagline_.set(pool_, parser->ShortDesc());
2355 _profile(Package$parse$Retain)
2356 if (parsed->homepage_.empty())
2357 parsed->homepage_ = website;
2358 if (parsed->homepage_ == parsed->depiction_)
2359 parsed->homepage_.clear();
2360 if (parsed->support_.empty())
2361 parsed->support_ = bugs;
2366 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2367 if ((self = [super init]) != nil) {
2368 _profile(Package$initWithVersion)
2370 pool_ = new CYPool();
2376 database_ = database;
2377 era_ = [database era];
2381 pkgCache::PkgIterator iterator(version_.ParentPkg());
2382 iterator_ = iterator;
2384 _profile(Package$initWithVersion$Version)
2385 file_ = version_.FileList();
2388 _profile(Package$initWithVersion$Cache)
2389 name_.set(NULL, version_.Display());
2391 latest_.set(NULL, StripVersion_(version_.VerStr()));
2393 pkgCache::VerIterator current(iterator.CurrentVer());
2395 installed_.set(NULL, StripVersion_(current.VerStr()));
2398 _profile(Package$initWithVersion$Transliterate) do {
2399 if (CollationTransl_ == NULL)
2404 _profile(Package$initWithVersion$Transliterate$utf8)
2405 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2406 for (size_t i(0), e(name_.size()); i != e; ++i)
2407 if (data[i] >= 0x80)
2412 UErrorCode code(U_ZERO_ERROR);
2415 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2416 CollationString_.resize(name_.size());
2417 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2418 if (!U_SUCCESS(code))
2420 CollationString_.resize(length);
2423 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2424 length = CollationString_.size();
2425 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2426 if (!U_SUCCESS(code))
2428 _assert(CollationString_.size() == length);
2431 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2432 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2433 if (code == U_BUFFER_OVERFLOW_ERROR)
2434 code = U_ZERO_ERROR;
2435 else if (!U_SUCCESS(code))
2440 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2441 transform = pool_->malloc<char>(length);
2443 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2444 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2445 if (!U_SUCCESS(code))
2449 transform_.set(NULL, transform, length);
2450 } while (false); _end
2452 _profile(Package$initWithVersion$Tags)
2454 pkgCache::TagIterator tag(version_.TagList());
2456 pkgCache::TagIterator tag(iterator.TagList());
2459 tags_ = [NSMutableArray arrayWithCapacity:8];
2461 goto tag; for (; !tag.end(); ++tag) tag: {
2462 const char *name(tag.Name());
2463 NSString *string((NSString *) CYStringCreate(name));
2467 [tags_ addObject:[string autorelease]];
2469 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2470 if (strcmp(name + 6, "enduser") == 0)
2472 else if (strcmp(name + 6, "hacker") == 0)
2474 else if (strcmp(name + 6, "developer") == 0)
2476 else if (strcmp(name + 6, "cydia") == 0)
2482 if (strncmp(name, "cydia::", 7) == 0) {
2483 if (strcmp(name + 7, "essential") == 0)
2485 else if (strcmp(name + 7, "obsolete") == 0)
2492 _profile(Package$initWithVersion$Metadata)
2493 const char *mixed(iterator.Name());
2494 size_t size(strlen(mixed));
2495 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2496 char lower[prefix + size + 5 + 1];
2498 for (size_t i(0); i != size; ++i)
2499 lower[prefix + i] = mixed[i] | 0x20;
2501 if (!installed_.empty()) {
2502 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2503 memcpy(lower + prefix + size, ".list", 6);
2505 if (stat(lower, &info) != -1)
2506 upgraded_ = info.st_birthtime;
2509 PackageValue *metadata(PackageFind(lower + prefix, size));
2510 metadata_ = metadata;
2512 id_.set(NULL, metadata->name_, size);
2514 const char *latest(version_.VerStr());
2515 size_t length(strlen(latest));
2517 uint16_t vhash(hashlittle(latest, length));
2519 size_t capped(std::min<size_t>(8, length));
2520 latest = latest + length - capped;
2522 if (metadata->first_ == 0)
2523 metadata->first_ = now_;
2525 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2526 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2527 metadata->vhash_ = vhash;
2528 metadata->last_ = now_;
2529 } else if (metadata->last_ == 0)
2530 metadata->last_ = metadata->first_;
2533 _profile(Package$initWithVersion$Section)
2534 section_ = version_.Section();
2537 _profile(Package$initWithVersion$Flags)
2538 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2539 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2544 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2545 pkgCache::VerIterator version;
2547 _profile(Package$packageWithIterator$GetCandidateVer)
2548 version = [database policy]->GetCandidateVer(iterator);
2556 _profile(Package$packageWithIterator$Allocate)
2557 package = [Package allocWithZone:zone];
2560 _profile(Package$packageWithIterator$Initialize)
2562 initWithVersion:version
2572 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2573 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2574 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2577 - (pkgCache::PkgIterator) iterator {
2581 - (NSArray *) downgrades {
2582 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2584 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2585 if (version == version_)
2587 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2588 if ([package source] == nil)
2590 [versions addObject:package];
2596 - (NSString *) section {
2597 if (section$_ == nil) {
2598 if (section_ == NULL)
2601 _profile(Package$section$mappedSectionForPointer)
2602 section$_ = [database_ mappedSectionForPointer:section_];
2607 - (NSString *) simpleSection {
2608 if (NSString *section = [self section])
2609 return Simplify(section);
2614 - (NSString *) longSection {
2615 if (NSString *section = [self section])
2616 return LocalizeSection(section);
2621 - (NSString *) shortSection {
2622 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2625 - (NSString *) uri {
2628 pkgIndexFile *index;
2629 pkgCache::PkgFileIterator file(file_.File());
2630 if (![database_ list].FindIndex(file, index))
2632 return [NSString stringWithUTF8String:iterator_->Path];
2633 //return [NSString stringWithUTF8String:file.Site()];
2634 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2638 - (MIMEAddress *) maintainer {
2639 @synchronized (database_) {
2640 if ([database_ era] != era_ || file_.end())
2643 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2644 const std::string &maintainer(parser->Maintainer());
2645 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2648 - (NSString *) md5sum {
2649 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2653 @synchronized (database_) {
2654 if ([database_ era] != era_ || version_.end())
2657 return version_->InstalledSize;
2660 - (NSString *) longDescription {
2661 @synchronized (database_) {
2662 if ([database_ era] != era_ || file_.end())
2665 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2666 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2668 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2669 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2670 if ([lines count] < 2)
2673 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2674 for (size_t i(1), e([lines count]); i != e; ++i) {
2675 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2676 [trimmed addObject:trim];
2679 return [trimmed componentsJoinedByString:@"\n"];
2682 - (NSString *) shortDescription {
2683 if (parsed_ != NULL)
2684 return static_cast<NSString *>(parsed_->tagline_);
2686 @synchronized (database_) {
2687 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2688 std::string value(parser.ShortDesc());
2691 if (value.size() > 200)
2693 return [(id) CYStringCreate(value) autorelease];
2697 _profile(Package$index)
2698 CFStringRef name((CFStringRef) [self name]);
2699 if (CFStringGetLength(name) == 0)
2701 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2702 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2704 return toupper(character);
2708 - (PackageValue *) metadata {
2713 PackageValue *metadata([self metadata]);
2714 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2717 - (bool) subscribed {
2718 return [self metadata]->subscribed_;
2721 - (bool) setSubscribed:(bool)subscribed {
2722 PackageValue *metadata([self metadata]);
2723 if (metadata->subscribed_ == subscribed)
2725 metadata->subscribed_ = subscribed;
2733 - (NSString *) latest {
2737 - (NSString *) installed {
2741 - (BOOL) uninstalled {
2742 return installed_.empty();
2745 - (BOOL) upgradableAndEssential:(BOOL)essential {
2746 _profile(Package$upgradableAndEssential)
2747 pkgCache::VerIterator current(iterator_.CurrentVer());
2749 return essential && essential_;
2751 return version_ != current;
2755 - (BOOL) essential {
2760 return [database_ cache][iterator_].InstBroken();
2763 - (BOOL) unfiltered {
2764 _profile(Package$unfiltered$obsolete)
2765 if (_unlikely(obsolete_))
2769 _profile(Package$unfiltered$role)
2770 if (_unlikely(role_ > 3))
2778 if (![self unfiltered])
2783 _profile(Package$visible$section)
2784 section = [self section];
2787 _profile(Package$visible$isSectionVisible)
2788 if (!isSectionVisible(section))
2796 unsigned char current(iterator_->CurrentState);
2797 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2800 - (BOOL) halfConfigured {
2801 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2804 - (BOOL) halfInstalled {
2805 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2809 @synchronized (database_) {
2810 if ([database_ era] != era_ || iterator_.end())
2813 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2814 return state.Mode != pkgDepCache::ModeKeep;
2817 - (NSString *) mode {
2818 @synchronized (database_) {
2819 if ([database_ era] != era_ || iterator_.end())
2822 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2824 switch (state.Mode) {
2825 case pkgDepCache::ModeDelete:
2826 if ((state.iFlags & pkgDepCache::Purge) != 0)
2830 case pkgDepCache::ModeKeep:
2831 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2832 return @"REINSTALL";
2833 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2837 case pkgDepCache::ModeInstall:
2838 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2839 return @"REINSTALL";
2840 else*/ switch (state.Status) {
2842 return @"DOWNGRADE";
2848 return @"NEW_INSTALL";
2859 - (NSString *) name {
2860 return name_.empty() ? id_ : name_;
2863 - (UIImage *) icon {
2864 NSString *section = [self simpleSection];
2867 if (parsed_ != NULL)
2868 if (NSString *href = parsed_->icon_)
2869 if ([href hasPrefix:@"file:///"])
2870 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2871 if (icon == nil) if (section != nil)
2872 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2873 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2874 if ([dicon hasPrefix:@"file:///"])
2875 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2877 icon = [UIImage imageNamed:@"unknown.png"];
2881 - (NSString *) homepage {
2882 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2885 - (NSString *) depiction {
2886 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2889 - (MIMEAddress *) author {
2890 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2893 - (NSString *) support {
2894 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2897 - (NSArray *) files {
2898 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2899 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2902 fin.open([path UTF8String]);
2907 while (std::getline(fin, line))
2908 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2913 - (NSString *) state {
2914 @synchronized (database_) {
2915 if ([database_ era] != era_ || file_.end())
2918 switch (iterator_->CurrentState) {
2919 case pkgCache::State::NotInstalled:
2920 return @"NotInstalled";
2921 case pkgCache::State::UnPacked:
2923 case pkgCache::State::HalfConfigured:
2924 return @"HalfConfigured";
2925 case pkgCache::State::HalfInstalled:
2926 return @"HalfInstalled";
2927 case pkgCache::State::ConfigFiles:
2928 return @"ConfigFiles";
2929 case pkgCache::State::Installed:
2930 return @"Installed";
2931 case pkgCache::State::TriggersAwaited:
2932 return @"TriggersAwaited";
2933 case pkgCache::State::TriggersPending:
2934 return @"TriggersPending";
2937 return (NSString *) [NSNull null];
2940 - (NSString *) selection {
2941 @synchronized (database_) {
2942 if ([database_ era] != era_ || file_.end())
2945 switch (iterator_->SelectedState) {
2946 case pkgCache::State::Unknown:
2948 case pkgCache::State::Install:
2950 case pkgCache::State::Hold:
2952 case pkgCache::State::DeInstall:
2953 return @"DeInstall";
2954 case pkgCache::State::Purge:
2958 return (NSString *) [NSNull null];
2961 - (NSArray *) warnings {
2962 @synchronized (database_) {
2963 if ([database_ era] != era_ || file_.end())
2966 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2967 const char *name(iterator_.Name());
2969 size_t length(strlen(name));
2970 if (length < 2) invalid:
2971 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2972 else for (size_t i(0); i != length; ++i)
2974 /* XXX: technically this is not allowed */
2975 (name[i] < 'A' || name[i] > 'Z') &&
2976 (name[i] < 'a' || name[i] > 'z') &&
2977 (name[i] < '0' || name[i] > '9') &&
2978 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2981 if (strcmp(name, "cydia") != 0) {
2984 bool _private = false;
2986 bool dbstash = false;
2987 bool dsstore = false;
2989 bool repository = [[self section] isEqualToString:@"Repositories"];
2991 if (NSArray *files = [self files])
2992 for (NSString *file in files)
2993 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2995 else if (!user && [file isEqualToString:@"/User"])
2997 else if (!_private && [file isEqualToString:@"/private"])
2999 else if (!stash && [file isEqualToString:@"/var/stash"])
3001 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3003 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3006 /* XXX: this is not sensitive enough. only some folders are valid. */
3007 if (cydia && !repository)
3008 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3010 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3012 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3014 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3016 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3018 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3021 return [warnings count] == 0 ? nil : warnings;
3024 - (NSArray *) applications {
3025 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3027 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3029 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3030 if (NSArray *files = [self files])
3031 for (NSString *file in files)
3032 if (application_r(file)) {
3033 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3036 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3037 if (id == nil || [id isEqualToString:me])
3040 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3042 display = application_r[1];
3044 NSString *bundle([file stringByDeletingLastPathComponent]);
3045 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3046 // XXX: maybe this should check if this is really a string, not just for length
3047 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3049 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3051 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3052 [applications addObject:application];
3054 [application addObject:id];
3055 [application addObject:display];
3056 [application addObject:url];
3059 return [applications count] == 0 ? nil : applications;
3062 - (Source *) source {
3063 if (source_ == nil) {
3064 @synchronized (database_) {
3065 if ([database_ era] != era_ || file_.end())
3066 source_ = (Source *) [NSNull null];
3068 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3072 return source_ == (Source *) [NSNull null] ? nil : source_;
3075 - (time_t) upgraded {
3079 - (uint32_t) recent {
3080 return std::numeric_limits<uint32_t>::max() - upgraded_;
3087 - (BOOL) matches:(NSArray *)query {
3088 if (query == nil || [query count] == 0)
3097 string = [self name];
3098 length = [string length];
3101 for (NSString *term in query) {
3102 range = [string rangeOfString:term options:MatchCompareOptions_];
3103 if (range.location != NSNotFound)
3104 rank_ -= 6 * 1000000 / length;
3109 length = [string length];
3112 for (NSString *term in query) {
3113 range = [string rangeOfString:term options:MatchCompareOptions_];
3114 if (range.location != NSNotFound)
3115 rank_ -= 6 * 1000000 / length;
3119 string = [self shortDescription];
3120 length = [string length];
3121 NSUInteger stop(std::min<NSUInteger>(length, 200));
3124 for (NSString *term in query) {
3125 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3126 if (range.location != NSNotFound)
3127 rank_ -= 2 * 100000;
3133 - (NSArray *) tags {
3137 - (BOOL) hasTag:(NSString *)tag {
3138 return tags_ == nil ? NO : [tags_ containsObject:tag];
3141 - (NSString *) primaryPurpose {
3142 for (NSString *tag in (NSArray *) tags_)
3143 if ([tag hasPrefix:@"purpose::"])
3144 return [tag substringFromIndex:9];
3148 - (NSArray *) purposes {
3149 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3150 for (NSString *tag in (NSArray *) tags_)
3151 if ([tag hasPrefix:@"purpose::"])
3152 [purposes addObject:[tag substringFromIndex:9]];
3153 return [purposes count] == 0 ? nil : purposes;
3156 - (bool) isCommercial {
3157 return [self hasTag:@"cydia::commercial"];
3160 - (void) setIndex:(size_t)index {
3161 if (metadata_->index_ != index + 1)
3162 metadata_->index_ = index + 1;
3165 - (CYString &) cyname {
3166 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3169 - (uint32_t) compareBySection:(NSArray *)sections {
3170 NSString *section([self section]);
3171 for (size_t i(0), e([sections count]); i != e; ++i) {
3172 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3176 return _not(uint32_t);
3180 @synchronized (database_) {
3181 if ([database_ era] != era_ || file_.end())
3184 pkgProblemResolver *resolver = [database_ resolver];
3185 resolver->Clear(iterator_);
3187 pkgCacheFile &cache([database_ cache]);
3188 cache->SetReInstall(iterator_, false);
3189 cache->MarkKeep(iterator_, false);
3193 @synchronized (database_) {
3194 if ([database_ era] != era_ || file_.end())
3197 pkgProblemResolver *resolver = [database_ resolver];
3198 resolver->Clear(iterator_);
3199 resolver->Protect(iterator_);
3201 pkgCacheFile &cache([database_ cache]);
3202 cache->SetCandidateVersion(version_);
3203 cache->SetReInstall(iterator_, false);
3204 cache->MarkInstall(iterator_, false);
3206 pkgDepCache::StateCache &state((*cache)[iterator_]);
3207 if (!state.Install())
3208 cache->SetReInstall(iterator_, true);
3212 @synchronized (database_) {
3213 if ([database_ era] != era_ || file_.end())
3216 pkgProblemResolver *resolver = [database_ resolver];
3217 resolver->Clear(iterator_);
3218 resolver->Remove(iterator_);
3219 resolver->Protect(iterator_);
3221 pkgCacheFile &cache([database_ cache]);
3222 cache->SetReInstall(iterator_, false);
3223 cache->MarkDelete(iterator_, true);
3228 /* Section Class {{{ */
3229 @interface Section : NSObject {
3233 _H<NSString> localized_;
3236 - (NSComparisonResult) compareByLocalized:(Section *)section;
3237 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3238 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3239 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3241 - (NSString *) name;
3242 - (void) setName:(NSString *)name;
3248 - (void) addToCount;
3250 - (void) setCount:(size_t)count;
3251 - (NSString *) localized;
3255 @implementation Section
3257 - (NSComparisonResult) compareByLocalized:(Section *)section {
3258 NSString *lhs(localized_);
3259 NSString *rhs([section localized]);
3261 /*if ([lhs length] != 0 && [rhs length] != 0) {
3262 unichar lhc = [lhs characterAtIndex:0];
3263 unichar rhc = [rhs characterAtIndex:0];
3265 if (isalpha(lhc) && !isalpha(rhc))
3266 return NSOrderedAscending;
3267 else if (!isalpha(lhc) && isalpha(rhc))
3268 return NSOrderedDescending;
3271 return [lhs compare:rhs options:LaxCompareOptions_];
3274 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3275 if ((self = [self initWithName:name localize:NO]) != nil) {
3276 if (localized != nil)
3277 localized_ = localized;
3281 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3282 return [self initWithName:name row:0 localize:localize];
3285 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3286 if ((self = [super init]) != nil) {
3290 localized_ = LocalizeSection(name_);
3294 - (NSString *) name {
3298 - (void) setName:(NSString *)name {
3314 - (void) addToCount {
3318 - (void) setCount:(size_t)count {
3322 - (NSString *) localized {
3329 class CydiaLogCleaner :
3330 public pkgArchiveCleaner
3333 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3338 /* Database Implementation {{{ */
3339 @implementation Database
3341 + (Database *) sharedInstance {
3342 static _H<Database> instance;
3343 if (instance == nil)
3344 instance = [[[Database alloc] init] autorelease];
3352 - (void) releasePackages {
3356 - (bool) hasPackages {
3357 return [packages_ count] != 0;
3361 // XXX: actually implement this thing
3363 [self releasePackages];
3364 NSRecycleZone(zone_);
3368 - (void) _readCydia:(NSNumber *)fd {
3369 boost::fdistream is([fd intValue]);
3372 static RegEx finish_r("finish:([^:]*)");
3374 while (std::getline(is, line)) {
3375 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3377 const char *data(line.c_str());
3378 size_t size = line.size();
3379 lprintf("C:%s\n", data);
3381 if (finish_r(data, size)) {
3382 NSString *finish = finish_r[1];
3383 int index = [Finishes_ indexOfObject:finish];
3384 if (index != INT_MAX && index > Finish_)
3394 - (void) _readStatus:(NSNumber *)fd {
3395 boost::fdistream is([fd intValue]);
3398 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3399 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3401 while (std::getline(is, line)) {
3402 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3404 const char *data(line.c_str());
3405 size_t size(line.size());
3406 lprintf("S:%s\n", data);
3408 if (conffile_r(data, size)) {
3409 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3410 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3411 } else if (strncmp(data, "status: ", 8) == 0) {
3412 // status: <package>: {unpacked,half-configured,installed}
3413 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3414 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3415 } else if (strncmp(data, "processing: ", 12) == 0) {
3416 // processing: configure: config-test
3417 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3418 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3419 } else if (pmstatus_r(data, size)) {
3420 std::string type([pmstatus_r[1] UTF8String]);
3422 NSString *package = pmstatus_r[2];
3423 if ([package isEqualToString:@"dpkg-exec"])
3426 float percent([pmstatus_r[3] floatValue]);
3427 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3429 NSString *string = pmstatus_r[4];
3431 if (type == "pmerror") {
3432 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3433 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3434 } else if (type == "pmstatus") {
3435 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3436 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3437 } else if (type == "pmconffile")
3438 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3440 lprintf("E:unknown pmstatus\n");
3442 lprintf("E:unknown status\n");
3450 - (void) _readOutput:(NSNumber *)fd {
3451 boost::fdistream is([fd intValue]);
3454 while (std::getline(is, line)) {
3455 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3457 lprintf("O:%s\n", line.c_str());
3459 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3460 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3472 - (Package *) packageWithName:(NSString *)name {
3475 @synchronized (self) {
3476 if (static_cast<pkgDepCache *>(cache_) == NULL)
3478 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3483 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3487 if ((self = [super init]) != nil) {
3494 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3496 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3500 _assert(pipe(fds) != -1);
3503 _config->Set("APT::Keep-Fds::", cydiafd_);
3504 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3507 detachNewThreadSelector:@selector(_readCydia:)
3509 withObject:[NSNumber numberWithInt:fds[0]]
3512 _assert(pipe(fds) != -1);
3516 detachNewThreadSelector:@selector(_readStatus:)
3518 withObject:[NSNumber numberWithInt:fds[0]]
3521 _assert(pipe(fds) != -1);
3522 _assert(dup2(fds[0], 0) != -1);
3523 _assert(close(fds[0]) != -1);
3525 input_ = fdopen(fds[1], "a");
3527 _assert(pipe(fds) != -1);
3528 _assert(dup2(fds[1], 1) != -1);
3529 _assert(close(fds[1]) != -1);
3532 detachNewThreadSelector:@selector(_readOutput:)
3534 withObject:[NSNumber numberWithInt:fds[0]]
3539 - (pkgCacheFile &) cache {
3543 - (pkgDepCache::Policy *) policy {
3547 - (pkgRecords *) records {
3551 - (pkgProblemResolver *) resolver {
3555 - (pkgAcquire &) fetcher {
3559 - (pkgSourceList &) list {
3563 - (NSArray *) packages {
3567 - (NSArray *) sources {
3571 - (Source *) sourceWithKey:(NSString *)key {
3572 for (Source *source in [self sources]) {
3573 if ([[source key] isEqualToString:key])
3578 - (bool) popErrorWithTitle:(NSString *)title {
3581 while (!_error->empty()) {
3583 bool warning(!_error->PopMessage(error));
3588 size_t size(error.size());
3589 if (size == 0 || error[size - 1] != '\n')
3591 error.resize(size - 1);
3594 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3596 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3597 if (warning && no_pubkey(error.c_str()))
3600 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3606 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3607 return [self popErrorWithTitle:title] || !success;
3610 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3611 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3619 if (access("/etc/apt/sources.list", F_OK) == 0)
3620 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3622 std::string base("/etc/apt/sources.list.d");
3623 if (DIR *sources = opendir(base.c_str())) {
3624 while (dirent *source = readdir(sources))
3625 if (source->d_name[0] != '.' && source->d_namlen > 5 && strcmp(source->d_name + source->d_namlen - 5, ".list") == 0 && strcmp(source->d_name, "cydia.list") != 0)
3626 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3630 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend([SOURCES_LIST UTF8String])];
3635 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3636 @synchronized (self) {
3639 [self releasePackages];
3642 [sourceList_ removeAllObjects];
3663 new (&pool_) CYPool();
3665 NSRecycleZone(zone_);
3666 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3668 int chk(creat("/tmp/cydia.chk", 0644));
3672 if (invocation != nil)
3673 [invocation invoke];
3675 NSString *title(UCLocalize("DATABASE"));
3677 list_ = new pkgSourceList();
3678 _profile(reloadDataWithInvocation$ReadMainList)
3679 if ([self popErrorWithTitle:title forReadList:*list_])
3683 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3684 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3685 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3686 [sourceList_ addObject:object];
3691 OpProgress progress;
3694 delock_ = GetStatusDate();
3695 _profile(reloadDataWithInvocation$pkgCacheFile)
3696 opened = cache_.Open(progress, false);
3699 // XXX: this block should probably be merged with popError: in some way
3700 while (!_error->empty()) {
3702 bool warning(!_error->PopMessage(error));
3704 lprintf("cache_.Open():[%s]\n", error.c_str());
3706 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3710 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3711 repair = @selector(configure);
3712 //else if (error == "The package lists or status file could not be parsed or opened.")
3713 // repair = @selector(update);
3714 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3715 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3716 // else if (error == "Malformed Status line")
3717 // else if (error == "The list of sources could not be read.")
3719 if (repair != NULL) {
3721 [delegate_ repairWithSelector:repair];
3727 } else if ([self popErrorWithTitle:title forOperation:true])
3731 unlink("/tmp/cydia.chk");
3733 now_ = [[NSDate date] timeIntervalSince1970];
3735 policy_ = new pkgDepCache::Policy();
3736 records_ = new pkgRecords(cache_);
3737 resolver_ = new pkgProblemResolver(cache_);
3738 fetcher_ = new pkgAcquire(&status_);
3741 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3742 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3746 _profile(reloadDataWithInvocation$pkgApplyStatus)
3747 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3751 if (cache_->BrokenCount() != 0) {
3752 _profile(pkgApplyStatus$pkgFixBroken)
3753 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3757 if (cache_->BrokenCount() != 0) {
3758 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3762 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3763 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3768 for (Source *object in (id) sourceList_) {
3769 metaIndex *source([object metaIndex]);
3770 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3771 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3772 // XXX: this could be more intelligent
3773 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3774 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3776 sourceMap_[cached->ID] = object;
3781 size_t capacity(MetaFile_->active_);
3783 capacity = 128*1024;
3787 std::vector<Package *> packages;
3788 packages.reserve(capacity);
3792 _profile(reloadDataWithInvocation$packageWithIterator)
3793 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3794 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3795 if (unsigned index = package.metadata->index_) {
3797 if (packages.size() == index) {
3798 packages.push_back(package);
3799 } else if (packages.size() <= index) {
3800 packages.resize(index + 1, nil);
3801 packages[index] = package;
3804 std::swap(package, packages[index]);
3805 if (package != nil) {
3806 if (package.metadata->index_ == index + 1)
3815 lost: if (last == packages.size())
3816 packages.push_back(package);
3818 packages[last] = package;
3822 for (; last != packages.size(); ++last)
3823 if (packages[last] == nil)
3828 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3830 if (next == packages.size())
3832 if (packages[next] != nil)
3837 std::swap(packages[last], packages[next]);
3840 packages.resize(last);
3843 NSLog(@"lost = %zu", lost);
3845 _profile(reloadDataWithInvocation$radix$8)
3846 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3849 _profile(reloadDataWithInvocation$radix$4)
3850 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3853 _profile(reloadDataWithInvocation$radix$0)
3854 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3858 _profile(reloadDataWithInvocation$insertion)
3859 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3862 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3864 /*_profile(reloadDataWithInvocation$CFQSortArray)
3865 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3868 /*_profile(reloadDataWithInvocation$stdsort)
3869 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3872 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3873 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3876 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3877 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3880 MetaFile_->active_ = packages.size();
3881 for (size_t index(0), count(packages.size()); index != count; ++index) {
3882 auto package(packages[index]);
3883 [package setIndex:index];
3890 @synchronized (self) {
3892 resolver_ = new pkgProblemResolver(cache_);
3894 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3895 if (!cache_[iterator].Keep())
3896 cache_->MarkKeep(iterator, false);
3897 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3898 cache_->SetReInstall(iterator, false);
3901 - (void) configure {
3902 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3904 system([dpkg UTF8String]);
3909 @synchronized (self) {
3910 // XXX: I don't remember this condition
3915 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3917 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3919 if ([self popErrorWithTitle:title])
3923 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3925 CydiaLogCleaner cleaner;
3926 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3933 fetcher_->Shutdown();
3935 pkgRecords records(cache_);
3937 lock_ = new FileFd();
3938 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3940 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3942 if ([self popErrorWithTitle:title])
3946 if ([self popErrorWithTitle:title forReadList:list])
3949 manager_ = (_system->CreatePM(cache_));
3950 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3957 bool substrate(RestartSubstrate_);
3958 RestartSubstrate_ = false;
3960 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3962 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3964 if ([self popErrorWithTitle:title forReadList:list])
3966 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3967 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3970 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3972 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3974 [self popErrorWithTitle:title];
3978 bool failed = false;
3979 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3980 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3982 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3985 std::string uri = (*item)->DescURI();
3986 std::string error = (*item)->ErrorText;
3988 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3991 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3992 [delegate_ addProgressEventOnMainThread:event forTask:title];
3995 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4003 RestartSubstrate_ = true;
4005 if (![delock_ isEqual:GetStatusDate()]) {
4006 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4012 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4014 NSString *oextended(@"/var/lib/apt/extended_states");
4015 NSString *nextended(Cache("extended_states"));
4018 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4019 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4021 unlink([nextended UTF8String]);
4022 symlink([oextended UTF8String], [nextended UTF8String]);
4024 if ([self popErrorWithTitle:title])
4027 if (result == pkgPackageManager::Failed) {
4032 if (result != pkgPackageManager::Completed) {
4037 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4039 if ([self popErrorWithTitle:title forReadList:list])
4041 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4042 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4045 if (![before isEqualToArray:after])
4050 return ![delock_ isEqual:GetStatusDate()];
4054 NSString *title(UCLocalize("UPGRADE"));
4055 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4061 [self updateWithStatus:status_];
4064 - (void) updateWithStatus:(CancelStatus &)status {
4065 NSString *title(UCLocalize("REFRESHING_DATA"));
4068 if ([self popErrorWithTitle:title forReadList:list])
4072 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4073 if ([self popErrorWithTitle:title])
4076 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4078 bool success(ListUpdate(status, list, PulseInterval_));
4079 if (status.WasCancelled())
4082 [self popErrorWithTitle:title forOperation:success];
4084 [[NSDictionary dictionaryWithObjectsAndKeys:
4085 [NSDate date], @"LastUpdate",
4086 nil] writeToFile:CacheState_ atomically:YES];
4089 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4092 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4093 delegate_ = delegate;
4096 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4097 progress_ = delegate;
4098 status_.setDelegate(delegate);
4101 - (NSObject<ProgressDelegate> *) progressDelegate {
4105 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4106 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4107 return i == sourceMap_.end() ? nil : i->second;
4110 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4111 for (Source *source in (id) sourceList_)
4112 [source setFetch:fetch forURI:uri];
4115 - (void) resetFetch {
4116 for (Source *source in (id) sourceList_)
4117 [source resetFetch];
4120 - (NSString *) mappedSectionForPointer:(const char *)section {
4121 _H<NSString> *mapped;
4123 _profile(Database$mappedSectionForPointer$Cache)
4124 mapped = §ions_[section];
4127 if (*mapped == NULL) {
4128 size_t length(strlen(section));
4129 char spaced[length + 1];
4131 _profile(Database$mappedSectionForPointer$Replace)
4132 for (size_t index(0); index != length; ++index)
4133 spaced[index] = section[index] == '_' ? ' ' : section[index];
4134 spaced[length] = '\0';
4139 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4140 string = [NSString stringWithUTF8String:spaced];
4143 _profile(Database$mappedSectionForPointer$Map)
4144 string = [SectionMap_ objectForKey:string] ?: string;
4154 @interface CydiaObject : CyteObject {
4155 _transient id delegate_;
4160 @interface CydiaWebViewController : CyteWebViewController {
4161 _H<CydiaObject> cydia_;
4164 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4165 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4166 - (void) setDelegate:(id)delegate;
4170 /* Web Scripting {{{ */
4171 @implementation CydiaObject
4173 - (void) setDelegate:(id)delegate {
4174 delegate_ = delegate;
4177 - (NSArray *) attributeKeys {
4178 return [[NSArray arrayWithObjects:
4186 nil] arrayByAddingObjectsFromArray:[super attributeKeys]];
4189 - (NSString *) version {
4193 - (NSString *) device {
4194 return UniqueIdentifier();
4197 - (NSArray *) cells {
4198 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4199 if ($_CTServerConnectionCreate == NULL)
4202 struct CTResult { int flag; int error; };
4203 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4204 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4207 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4208 if (connection == nil)
4212 CFArrayRef cells(NULL);
4213 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4214 if (result.flag != 0)
4217 return [(NSArray *) cells autorelease];
4220 - (NSString *) mcc {
4221 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4222 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4226 - (NSString *) mnc {
4227 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4228 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4232 - (NSString *) operator {
4233 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4234 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4238 - (NSString *) role {
4239 return (id) [NSNull null];
4242 + (NSString *) webScriptNameForSelector:(SEL)selector {
4244 else if (selector == @selector(addBridgedHost:))
4245 return @"addBridgedHost";
4246 else if (selector == @selector(addInsecureHost:))
4247 return @"addInsecureHost";
4248 else if (selector == @selector(addSource:::))
4249 return @"addSource";
4250 else if (selector == @selector(addTrivialSource:))
4251 return @"addTrivialSource";
4252 else if (selector == @selector(du:))
4254 else if (selector == @selector(getAllSources))
4255 return @"getAllSources";
4256 else if (selector == @selector(getApplicationInfo:value:))
4257 return @"getApplicationInfoValue";
4258 else if (selector == @selector(getDisplayIdentifiers))
4259 return @"getDisplayIdentifiers";
4260 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4261 return @"getLocalizedNameForDisplayIdentifier";
4262 else if (selector == @selector(getInstalledPackages))
4263 return @"getInstalledPackages";
4264 else if (selector == @selector(getPackageById:))
4265 return @"getPackageById";
4266 else if (selector == @selector(getMetadataKeys))
4267 return @"getMetadataKeys";
4268 else if (selector == @selector(getMetadataValue:))
4269 return @"getMetadataValue";
4270 else if (selector == @selector(getSessionValue:))
4271 return @"getSessionValue";
4272 else if (selector == @selector(installPackages:))
4273 return @"installPackages";
4274 else if (selector == @selector(refreshSources))
4275 return @"refreshSources";
4276 else if (selector == @selector(saveConfig))
4277 return @"saveConfig";
4278 else if (selector == @selector(setMetadataValue::))
4279 return @"setMetadataValue";
4280 else if (selector == @selector(setSessionValue::))
4281 return @"setSessionValue";
4282 else if (selector == @selector(substitutePackageNames:))
4283 return @"substitutePackageNames";
4284 else if (selector == @selector(setToken:))
4290 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4291 return [self webScriptNameForSelector:selector] == nil;
4294 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4296 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4297 return (id) [NSNull null];
4298 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4300 return (id) [NSNull null];
4301 return [info objectForKey:key];
4304 - (NSArray *) getDisplayIdentifiers {
4305 return SBSCopyApplicationDisplayIdentifiers(false, false);
4308 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4309 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4312 - (NSNumber *) getKernelNumber:(NSString *)name {
4313 const char *string([name UTF8String]);
4316 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4317 return (id) [NSNull null];
4319 if (size != sizeof(int))
4320 return (id) [NSNull null];
4323 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4324 return (id) [NSNull null];
4326 return [NSNumber numberWithInt:value];
4329 - (NSArray *) getMetadataKeys {
4330 @synchronized (Values_) {
4331 return [Values_ allKeys];
4334 - (id) getMetadataValue:(NSString *)key {
4335 @synchronized (Values_) {
4336 return [Values_ objectForKey:key];
4339 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4340 @synchronized (Values_) {
4341 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4342 [Values_ removeObjectForKey:key];
4344 [Values_ setObject:value forKey:key];
4347 - (id) getSessionValue:(NSString *)key {
4348 @synchronized (SessionData_) {
4349 return [SessionData_ objectForKey:key];
4352 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4353 @synchronized (SessionData_) {
4354 if (value == (id) [WebUndefined undefined])
4355 [SessionData_ removeObjectForKey:key];
4357 [SessionData_ setObject:value forKey:key];
4360 - (void) addBridgedHost:(NSString *)host {
4361 @synchronized (BridgedHosts_) {
4362 [BridgedHosts_ addObject:host];
4365 - (void) addInsecureHost:(NSString *)host {
4366 @synchronized (InsecureHosts_) {
4367 [InsecureHosts_ addObject:host];
4370 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4371 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4373 for (NSString *section in sections)
4374 [array addObject:section];
4376 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4379 distribution, @"Distribution",
4381 nil] waitUntilDone:NO];
4384 - (BOOL) addTrivialSource:(NSString *)href {
4385 href = VerifySource(href);
4388 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4392 - (void) refreshSources {
4393 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4396 - (void) saveConfig {
4397 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4400 - (NSArray *) getAllSources {
4401 return [[Database sharedInstance] sources];
4404 - (NSArray *) getInstalledPackages {
4405 Database *database([Database sharedInstance]);
4406 @synchronized (database) {
4407 NSArray *packages([database packages]);
4408 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4409 for (Package *package in packages)
4410 if (![package uninstalled])
4411 [installed addObject:package];
4415 - (Package *) getPackageById:(NSString *)id {
4416 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4420 return (Package *) [NSNull null];
4423 - (NSNumber *) du:(NSString *)path {
4424 NSNumber *value(nil);
4426 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4429 while (fgets(line, sizeof(line), du) != NULL) {
4430 size_t length(strlen(line));
4431 while (length != 0 && line[length - 1] == '\n')
4432 line[--length] = '\0';
4433 if (char *tab = strchr(line, '\t')) {
4435 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4444 - (void) installPackages:(NSArray *)packages {
4445 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4448 - (NSString *) substitutePackageNames:(NSString *)message {
4449 auto database([Database sharedInstance]);
4451 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4452 if (![database hasPackages])
4455 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4456 for (size_t i(0), e([words count]); i != e; ++i) {
4457 NSString *word([words objectAtIndex:i]);
4458 if (Package *package = [database packageWithName:word])
4459 [words replaceObjectAtIndex:i withObject:[package name]];
4462 return [words componentsJoinedByString:@" "];
4465 - (void) setToken:(NSString *)token {
4466 // XXX: the website expects this :/
4472 @interface NSURL (CydiaSecure)
4475 @implementation NSURL (CydiaSecure)
4477 - (bool) isCydiaSecure {
4478 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4481 @synchronized (InsecureHosts_) {
4482 if ([InsecureHosts_ containsObject:[self host]])
4491 /* Cydia Browser Controller {{{ */
4492 @implementation CydiaWebViewController
4494 - (NSURL *) navigationURL {
4495 if (NSURLRequest *request = self.request)
4496 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4501 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4502 [super webView:view didClearWindowObject:window forFrame:frame];
4503 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4506 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4507 WebDataSource *source([frame dataSource]);
4508 NSURLResponse *response([source response]);
4509 NSURL *url([response URL]);
4510 NSString *scheme([[url scheme] lowercaseString]);
4512 bool bridged(false);
4514 @synchronized (BridgedHosts_) {
4515 if ([scheme isEqualToString:@"file"])
4517 else if ([scheme isEqualToString:@"https"])
4518 if ([BridgedHosts_ containsObject:[url host]])
4523 [window setValue:cydia forKey:@"cydia"];
4526 - (void) _setupMail:(MFMailComposeViewController *)controller {
4527 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4529 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4530 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4533 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4534 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4537 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4538 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4541 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4542 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4544 NSURL *url([copy URL]);
4545 NSString *href([url absoluteString]);
4546 NSString *host([url host]);
4548 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4549 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4550 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4551 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4554 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4555 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4557 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4561 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4562 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4563 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4564 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4566 bool bridged; @synchronized (BridgedHosts_) {
4567 bridged = [BridgedHosts_ containsObject:host];
4570 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4571 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4576 - (void) setDelegate:(id)delegate {
4577 [super setDelegate:delegate];
4578 [cydia_ setDelegate:delegate];
4582 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4583 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
4589 @interface AppCacheController : CydiaWebViewController {
4594 @implementation AppCacheController
4596 - (void) didReceiveMemoryWarning {
4597 // XXX: this doesn't work
4600 - (bool) retainsNetworkActivityIndicator {
4607 /* Confirmation Controller {{{ */
4608 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4609 if (!iterator.end())
4610 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4611 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4613 pkgCache::PkgIterator package(dep.TargetPkg());
4616 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4623 @protocol ConfirmationControllerDelegate
4624 - (void) cancelAndClear:(bool)clear;
4625 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4629 @interface ConfirmationController : CydiaWebViewController {
4630 _transient Database *database_;
4632 _H<UIAlertView> essential_;
4634 _H<NSDictionary> changes_;
4635 _H<NSMutableArray> issues_;
4636 _H<NSDictionary> sizes_;
4641 - (id) initWithDatabase:(Database *)database;
4645 @implementation ConfirmationController
4649 RestartSubstrate_ = true;
4650 [self.delegate confirmWithNavigationController:[self navigationController]];
4653 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4654 NSString *context([alert context]);
4656 if ([context isEqualToString:@"remove"]) {
4657 if (button == [alert cancelButtonIndex])
4659 else if (button == [alert firstOtherButtonIndex]) {
4660 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4663 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4664 } else if ([context isEqualToString:@"unable"]) {
4665 [self dismissModalViewControllerAnimated:YES];
4666 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4668 [super alertView:alert clickedButtonAtIndex:button];
4672 - (void) _doContinue {
4673 [self.delegate cancelAndClear:NO];
4674 [self dismissModalViewControllerAnimated:YES];
4677 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4678 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4682 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4683 [super webView:view didClearWindowObject:window forFrame:frame];
4685 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4686 (id) changes_, @"changes",
4687 (id) issues_, @"issues",
4688 (id) sizes_, @"sizes",
4690 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4693 - (id) initWithDatabase:(Database *)database {
4694 if ((self = [super init]) != nil) {
4695 database_ = database;
4697 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4698 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4699 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4700 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4701 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4705 pkgCacheFile &cache([database_ cache]);
4706 NSArray *packages([database_ packages]);
4707 pkgDepCache::Policy *policy([database_ policy]);
4709 issues_ = [NSMutableArray arrayWithCapacity:4];
4711 for (Package *package in packages) {
4712 pkgCache::PkgIterator iterator([package iterator]);
4713 NSString *name([package id]);
4715 if ([package broken]) {
4716 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4718 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4720 reasons, @"reasons",
4723 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4727 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4728 pkgCache::DepIterator start;
4729 pkgCache::DepIterator end;
4730 dep.GlobOr(start, end); // ++dep
4732 if (!cache->IsImportantDep(end))
4734 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4737 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4739 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4740 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4741 clauses, @"clauses",
4745 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4747 pkgCache::PkgIterator target(start.TargetPkg());
4748 if (target->ProvidesList != 0)
4749 reason = @"missing";
4751 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4753 reason = @"installed";
4754 installed = [NSString stringWithUTF8String:ver.VerStr()];
4755 } else if (!cache[target].CandidateVerIter(cache).end())
4756 reason = @"uninstalled";
4757 else if (target->ProvidesList == 0)
4758 reason = @"uninstallable";
4760 reason = @"virtual";
4763 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4764 [NSString stringWithUTF8String:start.CompType()], @"operator",
4765 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4768 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4769 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4770 version, @"version",
4772 installed, @"installed",
4775 // yes, seriously. (wtf?)
4783 pkgDepCache::StateCache &state(cache[iterator]);
4785 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
4787 if (state.NewInstall())
4788 [installs addObject:name];
4789 // XXX: else if (state.Install())
4790 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4791 [reinstalls addObject:name];
4792 // XXX: move before previous if
4793 else if (state.Upgrade())
4794 [upgrades addObject:name];
4795 else if (state.Downgrade())
4796 [downgrades addObject:name];
4797 else if (!state.Delete())
4798 // XXX: _assert(state.Keep());
4800 else if (special_r(name))
4801 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4802 [NSNull null], @"package",
4803 [NSArray arrayWithObjects:
4804 [NSDictionary dictionaryWithObjectsAndKeys:
4805 @"Conflicts", @"relationship",
4806 [NSArray arrayWithObjects:
4807 [NSDictionary dictionaryWithObjectsAndKeys:
4809 [NSNull null], @"version",
4810 @"installed", @"reason",
4817 if ([package essential])
4819 [removes addObject:name];
4822 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4823 substrate_ |= DepSubstrate(iterator.CurrentVer());
4828 else if (Advanced_) {
4829 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4831 essential_ = [[[UIAlertView alloc]
4832 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4833 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4835 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4837 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4841 [essential_ setContext:@"remove"];
4842 [essential_ setNumberOfRows:2];
4844 essential_ = [[[UIAlertView alloc]
4845 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4846 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4848 cancelButtonTitle:UCLocalize("OKAY")
4849 otherButtonTitles:nil
4852 [essential_ setContext:@"unable"];
4855 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4856 installs, @"installs",
4857 reinstalls, @"reinstalls",
4858 upgrades, @"upgrades",
4859 downgrades, @"downgrades",
4860 removes, @"removes",
4863 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4864 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4865 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4868 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4872 - (UIBarButtonItem *) leftButton {
4873 return [[[UIBarButtonItem alloc]
4874 initWithTitle:UCLocalize("CANCEL")
4875 style:UIBarButtonItemStylePlain
4877 action:@selector(cancelButtonClicked)
4882 - (void) applyRightButton {
4883 if ([issues_ count] == 0 && ![self isLoading])
4884 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4885 initWithTitle:UCLocalize("CONFIRM")
4886 style:UIBarButtonItemStyleDone
4888 action:@selector(confirmButtonClicked)
4891 [[self navigationItem] setRightBarButtonItem:nil];
4895 - (void) cancelButtonClicked {
4896 [self.delegate cancelAndClear:YES];
4897 [self dismissModalViewControllerAnimated:YES];
4901 - (void) confirmButtonClicked {
4902 if (essential_ != nil)
4912 /* Progress Data {{{ */
4913 @interface CydiaProgressData : NSObject {
4914 _transient id delegate_;
4923 _H<NSMutableArray> events_;
4924 _H<NSString> title_;
4926 _H<NSString> status_;
4927 _H<NSString> finish_;
4932 @implementation CydiaProgressData
4934 + (NSArray *) _attributeKeys {
4935 return [NSArray arrayWithObjects:
4947 - (NSArray *) attributeKeys {
4948 return [[self class] _attributeKeys];
4951 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4952 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4956 if ((self = [super init]) != nil) {
4957 events_ = [NSMutableArray arrayWithCapacity:32];
4965 - (void) setDelegate:(id)delegate {
4966 delegate_ = delegate;
4969 - (void) setPercent:(float)value {
4973 - (NSNumber *) percent {
4974 return [NSNumber numberWithFloat:percent_];
4977 - (void) setCurrent:(float)value {
4981 - (NSNumber *) current {
4982 return [NSNumber numberWithFloat:current_];
4985 - (void) setTotal:(float)value {
4989 - (NSNumber *) total {
4990 return [NSNumber numberWithFloat:total_];
4993 - (void) setSpeed:(float)value {
4997 - (NSNumber *) speed {
4998 return [NSNumber numberWithFloat:speed_];
5001 - (NSArray *) events {
5005 - (void) removeAllEvents {
5006 [events_ removeAllObjects];
5009 - (void) addEvent:(CydiaProgressEvent *)event {
5010 [events_ addObject:event];
5013 - (void) setTitle:(NSString *)text {
5017 - (NSString *) title {
5021 - (void) setFinish:(NSString *)text {
5025 - (NSString *) finish {
5026 return (id) finish_ ?: [NSNull null];
5029 - (void) setRunning:(bool)running {
5033 - (NSNumber *) running {
5034 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5039 /* Progress Controller {{{ */
5040 @interface ProgressController : CydiaWebViewController <
5043 _transient Database *database_;
5044 _H<CydiaProgressData, 1> progress_;
5048 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5050 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5052 - (void) setTitle:(NSString *)title;
5053 - (void) setCancellable:(bool)cancellable;
5057 @implementation ProgressController
5060 [database_ setProgressDelegate:nil];
5064 - (UIBarButtonItem *) leftButton {
5065 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5066 initWithTitle:UCLocalize("CANCEL")
5067 style:UIBarButtonItemStylePlain
5069 action:@selector(cancel)
5070 ] autorelease] : nil;
5073 - (void) updateCancel {
5074 [super applyLeftButton];
5077 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5078 if ((self = [super init]) != nil) {
5079 database_ = database;
5080 self.delegate = delegate;
5082 [database_ setProgressDelegate:self];
5084 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5085 [progress_ setDelegate:self];
5087 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5089 [self setPageColor:[UIColor blackColor]];
5091 [[self navigationItem] setHidesBackButton:YES];
5093 [self updateCancel];
5097 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5098 [super webView:view didClearWindowObject:window forFrame:frame];
5099 [window setValue:progress_ forKey:@"cydiaProgress"];
5102 - (void) updateProgress {
5103 [self dispatchEvent:@"CydiaProgressUpdate"];
5106 - (void) viewWillAppear:(BOOL)animated {
5107 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5108 [super viewWillAppear:animated];
5112 UpdateExternalStatus(0);
5115 [self.delegate saveState];
5119 [self.delegate returnToCydia];
5123 [self.delegate terminateWithSuccess];
5124 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5125 [self.delegate suspendWithAnimation:YES];
5127 [self.delegate suspend];*/
5139 UIProgressHUD *hud([self.delegate addProgressHUD]);
5140 [hud setText:UCLocalize("LOADING")];
5141 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5147 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5148 SBReboot(SBSSpringBoardServerPort());
5150 reboot2(RB_AUTOBOOT);
5157 - (void) setTitle:(NSString *)title {
5158 [progress_ setTitle:title];
5159 [self updateProgress];
5162 - (UIBarButtonItem *) rightButton {
5163 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5164 initWithTitle:UCLocalize("CLOSE")
5165 style:UIBarButtonItemStylePlain
5167 action:@selector(close)
5171 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5172 UpdateExternalStatus(1);
5174 [progress_ setRunning:true];
5175 [self setTitle:title];
5176 // implicit updateProgress
5178 SHA1SumValue notifyconf; {
5180 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5183 MMap mmap(file, MMap::ReadOnly);
5185 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5186 notifyconf = sha1.Result();
5190 SHA1SumValue springlist; {
5192 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5195 MMap mmap(file, MMap::ReadOnly);
5197 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5198 springlist = sha1.Result();
5202 if (invocation != nil) {
5203 [invocation yieldToSelector:@selector(invoke)];
5204 [self setTitle:@"COMPLETE"];
5209 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5212 MMap mmap(file, MMap::ReadOnly);
5214 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5215 if (!(notifyconf == sha1.Result()))
5222 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5225 MMap mmap(file, MMap::ReadOnly);
5227 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5228 if (!(springlist == sha1.Result()))
5234 if (RestartSubstrate_)
5238 RestartSubstrate_ = false;
5241 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5242 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5243 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5244 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5245 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5248 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5250 [progress_ setRunning:false];
5251 [self updateProgress];
5253 [self applyRightButton];
5256 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5257 [progress_ addEvent:event];
5258 [self updateProgress];
5261 - (bool) isProgressCancelled {
5262 return cancel_ == 2;
5267 [self updateCancel];
5270 - (void) setCancellable:(bool)cancellable {
5271 unsigned cancel(cancel_);
5275 else if (cancel_ == 0)
5278 if (cancel != cancel_)
5279 [self updateCancel];
5282 - (void) setProgressCancellable:(NSNumber *)cancellable {
5283 [self setCancellable:[cancellable boolValue]];
5286 - (void) setProgressPercent:(NSNumber *)percent {
5287 [progress_ setPercent:[percent floatValue]];
5288 [self updateProgress];
5291 - (void) setProgressStatus:(NSDictionary *)status {
5292 if (status == nil) {
5293 [progress_ setCurrent:0];
5294 [progress_ setTotal:0];
5295 [progress_ setSpeed:0];
5297 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5299 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5300 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5301 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5304 [self updateProgress];
5310 /* Package Cell {{{ */
5311 @interface PackageCell : CyteTableViewCell <
5312 CyteTableViewCellDelegate
5316 _H<NSString> description_;
5318 _H<NSString> source_;
5320 _H<UIImage> placard_;
5324 - (PackageCell *) init;
5325 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5327 - (void) drawContentRect:(CGRect)rect;
5331 @implementation PackageCell
5333 - (PackageCell *) init {
5334 CGRect frame(CGRectMake(0, 0, 320, 74));
5335 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5336 [self.content setOpaque:YES];
5340 - (NSString *) accessibilityLabel {
5344 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5345 summarized_ = summary;
5355 [self.content setBackgroundColor:[UIColor whiteColor]];
5359 Source *source = [package source];
5361 icon_ = [package icon];
5363 if (NSString *name = [package name])
5364 name_ = [NSString stringWithString:name];
5366 if (NSString *description = [package shortDescription])
5367 description_ = [NSString stringWithString:description];
5369 commercial_ = [package isCommercial];
5371 NSString *label = nil;
5372 bool trusted = false;
5374 if (source != nil) {
5375 label = [source label];
5376 trusted = [source trusted];
5377 } else if ([[package id] isEqualToString:@"firmware"])
5378 label = UCLocalize("APPLE");
5380 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5382 NSString *from(label);
5384 NSString *section = [package simpleSection];
5385 if (section != nil && ![section isEqualToString:label]) {
5386 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5387 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5390 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5392 if (NSString *purpose = [package primaryPurpose])
5393 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5398 if (NSString *mode = [package mode]) {
5399 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5400 color = RemovingColor_;
5401 placard = @"removing";
5403 color = InstallingColor_;
5404 placard = @"installing";
5407 color = [UIColor whiteColor];
5409 if ([package installed] != nil)
5410 placard = @"installed";
5415 [self.content setBackgroundColor:color];
5418 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5421 [self setNeedsDisplay];
5422 [self.content setNeedsDisplay];
5425 - (void) drawSummaryContentRect:(CGRect)rect {
5426 bool highlighted(self.highlighted);
5427 float width([self bounds].size.width);
5431 rect.size = [(UIImage *) icon_ size];
5433 while (rect.size.width > 16 || rect.size.height > 16) {
5434 rect.size.width /= 2;
5435 rect.size.height /= 2;
5438 rect.origin.x = 19 - rect.size.width / 2;
5439 rect.origin.y = 19 - rect.size.height / 2;
5441 [icon_ drawInRect:Retina(rect)];
5444 if (badge_ != nil) {
5446 rect.size = [(UIImage *) badge_ size];
5448 rect.size.width /= 4;
5449 rect.size.height /= 4;
5451 rect.origin.x = 25 - rect.size.width / 2;
5452 rect.origin.y = 25 - rect.size.height / 2;
5454 [badge_ drawInRect:Retina(rect)];
5457 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5461 UISetColor(commercial_ ? Purple_ : Black_);
5462 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5464 if (placard_ != nil)
5465 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5468 - (void) drawNormalContentRect:(CGRect)rect {
5469 bool highlighted(self.highlighted);
5470 float width([self bounds].size.width);
5474 rect.size = [(UIImage *) icon_ size];
5476 while (rect.size.width > 32 || rect.size.height > 32) {
5477 rect.size.width /= 2;
5478 rect.size.height /= 2;
5481 rect.origin.x = 25 - rect.size.width / 2;
5482 rect.origin.y = 25 - rect.size.height / 2;
5484 [icon_ drawInRect:Retina(rect)];
5487 if (badge_ != nil) {
5489 rect.size = [(UIImage *) badge_ size];
5491 rect.size.width /= 2;
5492 rect.size.height /= 2;
5494 rect.origin.x = 36 - rect.size.width / 2;
5495 rect.origin.y = 36 - rect.size.height / 2;
5497 [badge_ drawInRect:Retina(rect)];
5500 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5504 UISetColor(commercial_ ? Purple_ : Black_);
5505 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5506 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5509 UISetColor(commercial_ ? Purplish_ : Gray_);
5510 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5512 if (placard_ != nil)
5513 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5516 - (void) drawContentRect:(CGRect)rect {
5518 [self drawSummaryContentRect:rect];
5520 [self drawNormalContentRect:rect];
5525 /* Section Cell {{{ */
5526 @interface SectionCell : CyteTableViewCell <
5527 CyteTableViewCellDelegate
5529 _H<NSString> basic_;
5530 _H<NSString> section_;
5532 _H<NSString> count_;
5534 _H<UISwitch> switch_;
5538 - (void) setSection:(Section *)section editing:(BOOL)editing;
5542 @implementation SectionCell
5544 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5545 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5546 icon_ = [UIImage imageNamed:@"folder.png"];
5547 // XXX: this initial frame is wrong, but is fixed later
5548 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5549 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5551 [self.content setBackgroundColor:[UIColor whiteColor]];
5555 - (void) onSwitch:(id)sender {
5556 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5557 if (metadata == nil) {
5558 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5559 [Sections_ setObject:metadata forKey:basic_];
5562 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5565 - (void) setSection:(Section *)section editing:(BOOL)editing {
5566 if (editing != editing_) {
5568 [switch_ removeFromSuperview];
5570 [self addSubview:switch_];
5579 if (section == nil) {
5580 name_ = UCLocalize("ALL_PACKAGES");
5583 basic_ = [section name];
5584 section_ = [section localized];
5586 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5587 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5590 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5593 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5594 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5596 [self.content setNeedsDisplay];
5599 - (void) setFrame:(CGRect)frame {
5600 [super setFrame:frame];
5602 CGRect rect([switch_ frame]);
5603 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5606 - (NSString *) accessibilityLabel {
5610 - (void) drawContentRect:(CGRect)rect {
5611 bool highlighted(self.highlighted && !editing_);
5613 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5615 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5618 float width(rect.size.width);
5620 width -= 9 + [switch_ frame].size.width;
5624 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
5626 CGSize size = [count_ sizeWithFont:Font14_];
5628 UISetColor(Folder_);
5630 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
5636 /* File Table {{{ */
5637 @interface FileTable : CyteListController <
5638 UITableViewDataSource,
5641 _transient Database *database_;
5642 _H<Package> package_;
5644 _H<NSMutableArray> files_;
5647 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5651 @implementation FileTable
5653 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5654 return files_ == nil ? 0 : [files_ count];
5657 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5661 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5662 static NSString *reuseIdentifier = @"Cell";
5664 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5666 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5667 [cell setFont:[UIFont systemFontOfSize:16]];
5669 [cell setText:[files_ objectAtIndex:indexPath.row]];
5670 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5675 - (NSURL *) navigationURL {
5676 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5679 - (CGFloat) rowHeight {
5683 - (void) releaseSubviews {
5687 [super releaseSubviews];
5690 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5691 if ((self = [super initWithTitle:UCLocalize("INSTALLED_FILES")]) != nil) {
5692 database_ = database;
5697 - (bool) shouldYield {
5701 - (void) _reloadData {
5704 package_ = [database_ packageWithName:name_];
5705 if (package_ != nil) {
5706 files_ = [NSMutableArray arrayWithCapacity:32];
5708 if (NSArray *files = [package_ files])
5709 [files_ addObjectsFromArray:files];
5711 if ([files_ count] != 0) {
5712 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5713 [files_ removeObjectAtIndex:0];
5714 [files_ sortUsingSelector:@selector(compareByPath:)];
5716 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5717 [stack addObject:@"/"];
5719 for (int i(0), e([files_ count]); i != e; ++i) {
5720 NSString *file = [files_ objectAtIndex:i];
5721 while (![file hasPrefix:[stack lastObject]])
5722 [stack removeLastObject];
5723 NSString *directory = [stack lastObject];
5724 [stack addObject:[file stringByAppendingString:@"/"]];
5725 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5726 int(([stack count] - 2) * 3), "",
5727 [file substringFromIndex:[directory length]]
5733 [super _reloadData];
5738 /* Package Controller {{{ */
5739 @interface CYPackageController : CydiaWebViewController <
5740 UIActionSheetDelegate
5742 _transient Database *database_;
5743 _H<Package> package_;
5746 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
5747 _H<UIActionSheet> sheet_;
5748 _H<UIBarButtonItem> button_;
5749 _H<NSArray> versions_;
5752 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5756 @implementation CYPackageController
5758 - (NSURL *) navigationURL {
5759 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5762 - (void) _clickButtonWithPackage:(Package *)package {
5763 [self.delegate installPackage:package];
5766 - (void) _clickButtonWithName:(NSString *)name {
5767 if ([name isEqualToString:@"CLEAR"])
5768 return [self.delegate clearPackage:package_];
5769 else if ([name isEqualToString:@"REMOVE"])
5770 return [self.delegate removePackage:package_];
5771 else if ([name isEqualToString:@"DOWNGRADE"]) {
5772 sheet_ = [[[UIActionSheet alloc]
5775 cancelButtonTitle:nil
5776 destructiveButtonTitle:nil
5777 otherButtonTitles:nil
5780 for (Package *version in (id) versions_)
5781 [sheet_ addButtonWithTitle:[version latest]];
5782 [sheet_ setContext:@"version"];
5784 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5788 else if ([name isEqualToString:@"INSTALL"]);
5789 else if ([name isEqualToString:@"REINSTALL"]);
5790 else if ([name isEqualToString:@"UPGRADE"]);
5791 else _assert(false);
5793 [self.delegate installPackage:package_];
5796 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5797 NSString *context([sheet context]);
5798 if (sheet_ == sheet)
5801 if ([context isEqualToString:@"modify"]) {
5802 if (button != [sheet cancelButtonIndex]) {
5804 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
5806 [self _clickButtonWithName:buttons_[button].first];
5809 [sheet dismissWithClickedButtonIndex:button animated:YES];
5810 } else if ([context isEqualToString:@"version"]) {
5811 if (button != [sheet cancelButtonIndex]) {
5812 Package *version([versions_ objectAtIndex:button]);
5814 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
5816 [self _clickButtonWithPackage:version];
5819 [sheet dismissWithClickedButtonIndex:button animated:YES];
5823 - (bool) _allowJavaScriptPanel {
5828 - (void) _customButtonClicked {
5829 if (commercial_ && self.isLoading && [package_ uninstalled])
5830 return [self reloadURLWithCache:NO];
5832 size_t count(buttons_.size());
5837 [self _clickButtonWithName:buttons_[0].first];
5839 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5840 for (const auto &button : buttons_)
5841 [buttons addObject:button.second];
5843 sheet_ = [[[UIActionSheet alloc]
5846 cancelButtonTitle:nil
5847 destructiveButtonTitle:nil
5848 otherButtonTitles:nil
5851 for (NSString *button in buttons)
5852 [sheet_ addButtonWithTitle:button];
5853 [sheet_ setContext:@"modify"];
5855 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5859 - (void) applyLoadingTitle {
5860 // Don't show "Loading" as the title. Ever.
5863 - (UIBarButtonItem *) rightButton {
5868 - (void) setPageColor:(UIColor *)color {
5869 return [super setPageColor:nil];
5872 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
5873 if ((self = [super init]) != nil) {
5874 database_ = database;
5875 name_ = name == nil ? @"" : [NSString stringWithString:name];
5876 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
5880 - (void) reloadData {
5883 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
5886 package_ = [database_ packageWithName:name_];
5887 versions_ = [package_ downgrades];
5891 if (package_ != nil) {
5892 [(Package *) package_ parse];
5894 commercial_ = [package_ isCommercial];
5896 if ([package_ mode] != nil)
5897 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
5898 if ([package_ source] == nil);
5899 else if ([package_ upgradableAndEssential:NO])
5900 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
5901 else if ([package_ uninstalled])
5902 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
5904 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
5905 if (![package_ uninstalled])
5906 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
5907 if ([versions_ count] != 0)
5908 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
5912 switch (buttons_.size()) {
5913 case 0: title = nil; break;
5914 case 1: title = buttons_[0].second; break;
5915 default: title = UCLocalize("MODIFY"); break;
5918 button_ = [[[UIBarButtonItem alloc]
5920 style:UIBarButtonItemStylePlain
5922 action:@selector(customButtonClicked)
5926 - (bool) isLoading {
5927 return commercial_ ? [super isLoading] : false;
5933 /* Package List Controller {{{ */
5934 @interface PackageListController : CyteListController <
5935 UITableViewDataSource,
5938 _transient Database *database_;
5940 _H<NSArray> packages_;
5941 _H<NSArray> sections_;
5943 _H<NSArray> thumbs_;
5944 std::vector<NSInteger> offset_;
5946 unsigned reloading_;
5949 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5951 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
5955 @implementation PackageListController
5957 - (NSURL *) referrerURL {
5958 return [self navigationURL];
5961 - (bool) isSummarized {
5965 - (bool) showsSections {
5969 - (void) didSelectPackage:(Package *)package {
5970 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
5971 [view setDelegate:self.delegate];
5972 [[self navigationController] pushViewController:view animated:YES];
5975 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5976 NSInteger count([sections_ count]);
5977 return count == 0 ? 1 : count;
5980 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5981 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5983 return [[sections_ objectAtIndex:section] name];
5986 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5987 if ([sections_ count] == 0)
5989 return [[sections_ objectAtIndex:section] count];
5992 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5993 @synchronized (database_) {
5994 if ([database_ era] != era_)
5997 Section *section([sections_ objectAtIndex:[path section]]);
5998 NSInteger row([path row]);
5999 Package *package([packages_ objectAtIndex:([section row] + row)]);
6000 return [[package retain] autorelease];
6003 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6004 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6006 cell = [[[PackageCell alloc] init] autorelease];
6008 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6009 [cell setPackage:package asSummary:[self isSummarized]];
6013 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6014 Package *package([self packageAtIndexPath:path]);
6015 package = [database_ packageWithName:[package id]];
6016 [self didSelectPackage:package];
6019 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6023 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6024 return offset_[index];
6027 - (CGFloat) rowHeight {
6028 return [self isSummarized] ? 38 : 73;
6031 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6032 if ((self = [super initWithTitle:title]) != nil) {
6033 database_ = database;
6037 - (void) releaseSubviews {
6044 [super releaseSubviews];
6047 - (bool) shouldBlock {
6051 - (NSMutableArray *) _reloadPackages {
6052 @synchronized (database_) {
6053 era_ = [database_ era];
6054 NSArray *packages([database_ packages]);
6056 return [NSMutableArray arrayWithArray:packages];
6059 - (void) _reloadData {
6060 if (reloading_ != 0) {
6065 NSMutableArray *packages;
6068 if ([self shouldYield]) {
6072 if (![self shouldBlock])
6075 hud = [self.delegate addProgressHUD];
6076 [hud setText:UCLocalize("LOADING")];
6080 packages = [self yieldToSelector:@selector(_reloadPackages)];
6083 [self.delegate removeProgressHUD:hud];
6084 } while (reloading_ == 2);
6086 packages = [self _reloadPackages];
6089 @synchronized (database_) {
6090 if (era_ != [database_ era])
6097 packages_ = packages;
6099 if ([self showsSections])
6100 sections_ = [self sectionsForPackages:packages];
6102 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6103 [section setCount:[packages_ count]];
6104 sections_ = [NSArray arrayWithObject:section];
6107 [super _reloadData];
6113 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6114 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6115 size_t end([packages count]);
6117 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6118 Section *section(prefix);
6120 thumbs_ = CollationThumbs_;
6121 offset_ = CollationOffset_;
6124 size_t offsets([CollationStarts_ count]);
6126 NSString *start([CollationStarts_ objectAtIndex:offset]);
6127 size_t length([start length]);
6129 for (size_t index(0); index != end; ++index) {
6131 Package *package([packages objectAtIndex:index]);
6132 NSString *name(PackageName(package, @selector(cyname)));
6134 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6135 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6136 NSString *title([CollationTitles_ objectAtIndex:offset]);
6137 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6138 [sections addObject:section];
6140 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6143 length = [start length];
6147 [section addToCount];
6150 for (; offset != offsets; ++offset) {
6151 NSString *title([CollationTitles_ objectAtIndex:offset]);
6152 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6153 [sections addObject:section];
6156 if ([prefix count] != 0) {
6157 Section *suffix([sections lastObject]);
6158 [prefix setName:[suffix name]];
6159 [suffix setName:nil];
6160 [sections insertObject:prefix atIndex:(offsets - 1)];
6168 /* Filtered Package List Controller {{{ */
6169 typedef Function<bool, Package *> PackageFilter;
6170 typedef Function<void, NSMutableArray *> PackageSorter;
6171 @interface FilteredPackageListController : PackageListController {
6172 PackageFilter filter_;
6173 PackageSorter sorter_;
6176 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6178 - (void) setFilter:(PackageFilter)filter;
6179 - (void) setSorter:(PackageSorter)sorter;
6183 @implementation FilteredPackageListController
6185 - (void) setFilter:(PackageFilter)filter {
6186 @synchronized (self) {
6190 - (void) setSorter:(PackageSorter)sorter {
6191 @synchronized (self) {
6195 - (NSMutableArray *) _reloadPackages {
6196 @synchronized (database_) {
6197 era_ = [database_ era];
6199 NSArray *packages([database_ packages]);
6200 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6202 PackageFilter filter;
6203 PackageSorter sorter;
6205 @synchronized (self) {
6210 _profile(PackageTable$reloadData$Filter)
6211 for (Package *package in packages)
6212 if (filter(package))
6213 [filtered addObject:package];
6221 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6222 if ((self = [super initWithDatabase:database title:title]) != nil) {
6223 [self setFilter:filter];
6230 /* Home Controller {{{ */
6231 @interface HomeController : CydiaWebViewController {
6232 CFRunLoopRef runloop_;
6233 SCNetworkReachabilityRef reachability_;
6238 @implementation HomeController
6240 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6241 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6245 if ((self = [super init]) != nil) {
6246 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6249 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6250 if (reachability_ != NULL) {
6251 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6252 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6254 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6255 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6262 if (reachability_ != NULL && runloop_ != NULL)
6263 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6267 - (NSURL *) navigationURL {
6268 return [NSURL URLWithString:@"cydia://home"];
6271 - (void) aboutButtonClicked {
6272 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6274 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6275 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6276 [alert setCancelButtonIndex:0];
6279 @"Copyright \u00a9 2008-2015\n"
6282 "Jay Freeman (saurik)\n"
6283 "saurik@saurik.com\n"
6284 "http://www.saurik.com/"
6290 - (UIBarButtonItem *) leftButton {
6291 return [[[UIBarButtonItem alloc]
6292 initWithTitle:UCLocalize("ABOUT")
6293 style:UIBarButtonItemStylePlain
6295 action:@selector(aboutButtonClicked)
6302 /* Cydia Tab Bar Controller {{{ */
6303 @interface CydiaTabBarController : CyteTabBarController <
6304 UITabBarControllerDelegate,
6307 _transient Database *database_;
6309 _H<UIActivityIndicatorView> indicator_;
6312 // XXX: ok, "updatedelegate_"?...
6313 _transient NSObject<CydiaDelegate> *updatedelegate_;
6316 - (void) beginUpdate;
6321 @implementation CydiaTabBarController
6323 - (id) initWithDatabase:(Database *)database {
6324 if ((self = [super init]) != nil) {
6325 database_ = database;
6326 [self setDelegate:self];
6328 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6329 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6331 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6335 - (void) beginUpdate {
6339 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6340 UITabBarItem *item([controller tabBarItem]);
6342 [item setBadgeValue:@""];
6343 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6345 [indicator_ startAnimating];
6346 [badge addSubview:indicator_];
6348 [updatedelegate_ retainNetworkActivityIndicator];
6352 detachNewThreadSelector:@selector(performUpdate)
6358 - (void) performUpdate {
6359 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6361 SourceStatus status(self, database_);
6362 [database_ updateWithStatus:status];
6365 performSelectorOnMainThread:@selector(completeUpdate)
6373 - (void) stopUpdateWithSelector:(SEL)selector {
6375 [updatedelegate_ releaseNetworkActivityIndicator];
6377 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6378 [[controller tabBarItem] setBadgeValue:nil];
6380 [indicator_ removeFromSuperview];
6381 [indicator_ stopAnimating];
6383 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6386 - (void) completeUpdate {
6389 [self stopUpdateWithSelector:@selector(reloadData)];
6392 - (void) cancelUpdate {
6393 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6396 - (void) cancelPressed {
6397 [self cancelUpdate];
6404 - (bool) isSourceCancelled {
6408 - (void) startSourceFetch:(NSString *)uri {
6411 - (void) stopSourceFetch:(NSString *)uri {
6414 - (void) setUpdateDelegate:(id)delegate {
6415 updatedelegate_ = delegate;
6421 /* Cydia:// Protocol {{{ */
6422 @interface CydiaURLProtocol : CyteURLProtocol {
6427 @implementation CydiaURLProtocol
6429 + (NSString *) scheme {
6433 - (bool) loadForPath:(NSString *)path ofRequest:(NSURLRequest *)request {
6434 NSRange slash([path rangeOfString:@"/"]);
6437 if (slash.location == NSNotFound) {
6441 command = [path substringToIndex:slash.location];
6442 path = [path substringFromIndex:(slash.location + 1)];
6445 Database *database([Database sharedInstance]);
6448 else if ([command isEqualToString:@"application-icon"]) {
6451 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6455 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
6456 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
6457 icon = [UIImage imageWithData:data];
6461 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
6462 icon = [UIImage imageAtPath:file];
6465 icon = [UIImage imageNamed:@"unknown.png"];
6467 [self _returnPNGWithImage:icon forRequest:request];
6468 } else if ([command isEqualToString:@"package-icon"]) {
6471 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6472 Package *package([database packageWithName:path]);
6476 UIImage *icon([package icon]);
6477 [self _returnPNGWithImage:icon forRequest:request];
6478 } else if ([command isEqualToString:@"uikit-image"]) {
6481 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6482 UIImage *icon(_UIImageWithName(path));
6483 [self _returnPNGWithImage:icon forRequest:request];
6484 } else if ([command isEqualToString:@"section-icon"]) {
6487 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6488 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6490 icon = [UIImage imageNamed:@"unknown.png"];
6491 [self _returnPNGWithImage:icon forRequest:request];
6493 return [super loadForPath:path ofRequest:request];
6502 /* Section Controller {{{ */
6503 @interface SectionController : FilteredPackageListController {
6505 _H<NSString> section_;
6508 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
6512 @implementation SectionController
6514 - (NSURL *) referrerURL {
6515 NSString *name(section_);
6516 name = name ?: @"*";
6517 NSString *key(key_);
6519 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6522 - (NSURL *) navigationURL {
6523 NSString *name(section_);
6524 name = name ?: @"*";
6525 NSString *key(key_);
6527 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6530 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
6533 title = UCLocalize("ALL_PACKAGES");
6534 else if (![section isEqual:@""])
6535 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
6537 title = UCLocalize("NO_SECTION");
6539 if ((self = [super initWithDatabase:database title:title]) != nil) {
6540 key_ = [source key];
6545 - (void) reloadData {
6546 Source *source([database_ sourceWithKey:key_]);
6547 _H<NSString> name(section_);
6549 [self setFilter:[=](Package *package) {
6550 NSString *section([package section]);
6554 section == nil && [name length] == 0 ||
6555 [name isEqualToString:section]
6558 [package source] == source
6559 ) && [package visible];
6567 /* Sections Controller {{{ */
6568 @interface SectionsController : CyteViewController <
6569 UITableViewDataSource,
6572 _transient Database *database_;
6574 _H<NSMutableArray> sections_;
6575 _H<NSMutableArray> filtered_;
6576 _H<UITableView, 2> list_;
6579 - (id) initWithDatabase:(Database *)database source:(Source *)source;
6580 - (void) editButtonClicked;
6584 @implementation SectionsController
6586 - (NSURL *) navigationURL {
6587 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
6590 - (Source *) source {
6593 return [database_ sourceWithKey:key_];
6596 - (void) updateNavigationItem {
6597 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6598 if ([sections_ count] == 0) {
6599 [[self navigationItem] setRightBarButtonItem:nil];
6601 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6602 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6604 action:@selector(editButtonClicked)
6605 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6609 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6610 [super setEditing:editing animated:animated];
6615 [self.delegate updateData];
6617 [self updateNavigationItem];
6620 - (void) viewDidAppear:(BOOL)animated {
6621 [super viewDidAppear:animated];
6622 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6625 - (void) viewWillDisappear:(BOOL)animated {
6626 [super viewWillDisappear:animated];
6627 [self setEditing:NO];
6630 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6631 Section *section = nil;
6632 int index = [indexPath row];
6633 if (![self isEditing]) {
6636 section = [filtered_ objectAtIndex:index];
6638 section = [sections_ objectAtIndex:index];
6643 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6644 if ([self isEditing])
6645 return [sections_ count];
6647 return [filtered_ count] + 1;
6650 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6654 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6655 static NSString *reuseIdentifier = @"SectionCell";
6657 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6659 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6661 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6666 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6667 if ([self isEditing])
6670 Section *section = [self sectionAtIndexPath:indexPath];
6672 SectionController *controller = [[[SectionController alloc]
6673 initWithDatabase:database_
6674 source:[self source]
6675 section:[section name]
6677 [controller setDelegate:self.delegate];
6679 [[self navigationController] pushViewController:controller animated:YES];
6683 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6684 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6685 [list_ setRowHeight:46];
6686 [(UITableView *) list_ setDataSource:self];
6687 [list_ setDelegate:self];
6688 [self setView:list_];
6691 - (void) viewDidLoad {
6692 [super viewDidLoad];
6694 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6697 - (void) releaseSubviews {
6703 [super releaseSubviews];
6706 - (id) initWithDatabase:(Database *)database source:(Source *)source {
6707 if ((self = [super init]) != nil) {
6708 database_ = database;
6709 key_ = [source key];
6713 - (void) reloadData {
6716 NSArray *packages = [database_ packages];
6718 sections_ = [NSMutableArray arrayWithCapacity:16];
6719 filtered_ = [NSMutableArray arrayWithCapacity:16];
6721 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6723 Source *source([self source]);
6726 for (Package *package in packages) {
6727 if (source != nil && [package source] != source)
6730 NSString *name([package section]);
6731 NSString *key(name == nil ? @"" : name);
6735 _profile(SectionsView$reloadData$Section)
6736 section = [sections objectForKey:key];
6737 if (section == nil) {
6738 _profile(SectionsView$reloadData$Section$Allocate)
6739 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6740 [sections setObject:section forKey:key];
6745 [section addToCount];
6747 _profile(SectionsView$reloadData$Filter)
6748 if (![package visible])
6756 [sections_ addObjectsFromArray:[sections allValues]];
6758 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6760 for (Section *section in (id) sections_) {
6761 size_t count([section row]);
6765 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6766 [section setCount:count];
6767 [filtered_ addObject:section];
6770 [self updateNavigationItem];
6775 - (void) editButtonClicked {
6776 [self setEditing:![self isEditing] animated:YES];
6782 /* Changes Controller {{{ */
6783 @interface ChangesController : FilteredPackageListController {
6787 - (id) initWithDatabase:(Database *)database;
6791 @implementation ChangesController
6793 - (NSURL *) referrerURL {
6794 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
6797 - (NSURL *) navigationURL {
6798 return [NSURL URLWithString:@"cydia://changes"];
6801 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6802 @synchronized (database_) {
6803 if ([database_ era] != era_)
6806 NSUInteger sectionIndex([path section]);
6807 if (sectionIndex >= [sections_ count])
6809 Section *section([sections_ objectAtIndex:sectionIndex]);
6810 NSInteger row([path row]);
6811 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
6814 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6815 NSString *context([alert context]);
6817 if ([context isEqualToString:@"norefresh"])
6818 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6821 - (void) setLeftBarButtonItem {
6822 if ([self.delegate updating])
6823 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6824 initWithTitle:UCLocalize("CANCEL")
6825 style:UIBarButtonItemStyleDone
6827 action:@selector(cancelButtonClicked)
6828 ] autorelease] animated:YES];
6830 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6831 initWithTitle:UCLocalize("REFRESH")
6832 style:UIBarButtonItemStylePlain
6834 action:@selector(refreshButtonClicked)
6835 ] autorelease] animated:YES];
6838 - (void) refreshButtonClicked {
6839 if ([self.delegate requestUpdate])
6840 [self setLeftBarButtonItem];
6843 - (void) cancelButtonClicked {
6844 [self.delegate cancelUpdate];
6847 - (void) upgradeButtonClicked {
6848 [self.delegate distUpgrade];
6849 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
6852 - (bool) shouldYield {
6856 - (bool) shouldBlock {
6860 - (void) useFilter {
6861 @synchronized (self) {
6862 [self setFilter:[](Package *package) {
6863 return [package upgradableAndEssential:YES] || [package visible];
6866 [self setSorter:[](NSMutableArray *packages) {
6867 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
6871 - (id) initWithDatabase:(Database *)database {
6872 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
6877 - (void) viewDidLoad {
6878 [super viewDidLoad];
6879 [self setLeftBarButtonItem];
6882 - (void) viewWillAppear:(BOOL)animated {
6883 [super viewWillAppear:animated];
6884 [self setLeftBarButtonItem];
6887 - (void) reloadData {
6888 [self setLeftBarButtonItem];
6892 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6893 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6895 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6896 Section *ignored = nil;
6897 Section *section = nil;
6901 bool unseens = false;
6903 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6905 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
6906 Package *package = [packages objectAtIndex:offset];
6908 BOOL uae = [package upgradableAndEssential:YES];
6912 time_t seen([package seen]);
6914 if (section == nil || last != seen) {
6918 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
6921 _profile(ChangesController$reloadData$Allocate)
6922 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6923 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6924 [sections addObject:section];
6928 [section addToCount];
6929 } else if ([package ignored]) {
6930 if (ignored == nil) {
6931 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
6933 [ignored addToCount];
6936 [upgradable addToCount];
6941 CFRelease(formatter);
6944 Section *last = [sections lastObject];
6945 size_t count = [last count];
6946 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
6947 [sections removeLastObject];
6950 if ([ignored count] != 0)
6951 [sections insertObject:ignored atIndex:0];
6953 [sections insertObject:upgradable atIndex:0];
6955 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
6956 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
6957 style:UIBarButtonItemStylePlain
6959 action:@selector(upgradeButtonClicked)
6960 ] autorelease]) animated:YES];
6967 /* Search Controller {{{ */
6968 @interface SearchController : FilteredPackageListController <
6971 _H<UISearchBar, 1> search_;
6976 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
6977 - (void) reloadData;
6981 @implementation SearchController
6983 - (NSURL *) referrerURL {
6984 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
6987 - (NSURL *) navigationURL {
6988 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
6989 return [NSURL URLWithString:@"cydia://search"];
6991 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
6994 - (NSArray *) termsForQuery:(NSString *)query {
6995 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
6996 for (NSString *component in [query componentsSeparatedByString:@" "])
6997 if ([component length] != 0)
6998 [terms addObject:component];
7003 - (void) useSearch {
7004 _H<NSArray> query([self termsForQuery:[search_ text]]);
7007 @synchronized (self) {
7008 [self setFilter:[=](Package *package) {
7009 if (![package unfiltered])
7011 if (![package matches:query])
7016 [self setSorter:[](NSMutableArray *packages) {
7017 [packages radixSortUsingSelector:@selector(rank)];
7025 - (void) usePrefix:(NSString *)prefix {
7026 _H<NSString> query(prefix);
7029 @synchronized (self) {
7030 [self setFilter:[=](Package *package) {
7031 if ([query length] == 0)
7033 if (![package unfiltered])
7035 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7040 [self setSorter:nullptr];
7046 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7048 [self usePrefix:[search_ text]];
7051 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7052 [search_ resignFirstResponder];
7056 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7057 [search_ setText:@""];
7058 [self searchBarButtonClicked:searchBar];
7061 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7062 [self searchBarButtonClicked:searchBar];
7065 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7066 [self usePrefix:text];
7069 - (bool) shouldYield {
7073 - (bool) shouldBlock {
7077 - (bool) isSummarized {
7081 - (bool) showsSections {
7085 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7086 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7087 search_ = [[[UISearchBar alloc] init] autorelease];
7088 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7089 [search_ setDelegate:self];
7091 UITextField *textField;
7092 if ([search_ respondsToSelector:@selector(searchField)])
7093 textField = [search_ searchField];
7095 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7097 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7098 [textField setEnablesReturnKeyAutomatically:NO];
7099 [[self navigationItem] setTitleView:textField];
7102 [search_ setText:query];
7107 - (void) viewDidAppear:(BOOL)animated {
7108 [super viewDidAppear:animated];
7110 if (!searchloaded_) {
7111 searchloaded_ = YES;
7112 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7113 [search_ layoutSubviews];
7116 if ([self isSummarized])
7117 [search_ becomeFirstResponder];
7120 - (void) reloadData {
7125 - (void) didSelectPackage:(Package *)package {
7126 [search_ resignFirstResponder];
7127 [super didSelectPackage:package];
7132 /* Package Settings Controller {{{ */
7133 @interface PackageSettingsController : CyteViewController <
7134 UITableViewDataSource,
7137 _transient Database *database_;
7139 _H<Package> package_;
7140 _H<UITableView, 2> table_;
7141 _H<UISwitch> subscribedSwitch_;
7142 _H<UISwitch> ignoredSwitch_;
7143 _H<UITableViewCell> subscribedCell_;
7144 _H<UITableViewCell> ignoredCell_;
7147 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7151 @implementation PackageSettingsController
7153 - (NSURL *) navigationURL {
7154 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7157 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7158 if (package_ == nil)
7161 if ([package_ installed] == nil)
7167 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7168 if (package_ == nil)
7171 // both sections contain just one item right now.
7175 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7179 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7181 return UCLocalize("SHOW_ALL_CHANGES_EX");
7183 return UCLocalize("IGNORE_UPGRADES_EX");
7186 - (void) onSubscribed:(id)control {
7187 bool value([control isOn]);
7188 if (package_ == nil)
7190 if ([package_ setSubscribed:value])
7191 [self.delegate updateData];
7194 - (void) _updateIgnored {
7195 const char *package([name_ UTF8String]);
7196 bool on([ignoredSwitch_ isOn]);
7198 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7199 fwrite(package, strlen(package), 1, dpkg);
7202 fwrite(" hold\n", 6, 1, dpkg);
7204 fwrite(" install\n", 9, 1, dpkg);
7209 - (void) onIgnored:(id)control {
7210 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7211 [invocation setTarget:self];
7212 [invocation setSelector:@selector(_updateIgnored)];
7214 [self.delegate reloadDataWithInvocation:invocation];
7217 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7218 if (package_ == nil)
7221 switch ([indexPath section]) {
7222 case 0: return subscribedCell_;
7223 case 1: return ignoredCell_;
7232 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7233 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7234 [self setView:view];
7236 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7237 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7238 [(UITableView *) table_ setDataSource:self];
7239 [table_ setDelegate:self];
7240 [view addSubview:table_];
7242 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7243 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7244 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7246 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7247 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7248 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7250 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7251 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7252 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7253 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7255 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7256 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7257 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7258 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7261 - (void) viewDidLoad {
7262 [super viewDidLoad];
7264 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7267 - (void) releaseSubviews {
7269 subscribedCell_ = nil;
7271 ignoredSwitch_ = nil;
7272 subscribedSwitch_ = nil;
7274 [super releaseSubviews];
7277 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7278 if ((self = [super init]) != nil) {
7279 database_ = database;
7284 - (void) reloadData {
7287 package_ = [database_ packageWithName:name_];
7289 if (package_ != nil) {
7290 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7291 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7292 } // XXX: what now, G?
7294 [table_ reloadData];
7300 /* Installed Controller {{{ */
7301 @interface InstalledController : FilteredPackageListController {
7305 - (id) initWithDatabase:(Database *)database;
7306 - (void) queueStatusDidChange;
7310 @implementation InstalledController
7312 - (NSURL *) referrerURL {
7313 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7316 - (NSURL *) navigationURL {
7317 return [NSURL URLWithString:@"cydia://installed"];
7320 - (void) useRecent {
7323 @synchronized (self) {
7324 [self setFilter:[](Package *package) {
7325 return ![package uninstalled] && package->role_ < 7;
7328 [self setSorter:[](NSMutableArray *packages) {
7329 [packages radixSortUsingSelector:@selector(recent)];
7333 - (void) useFilter:(UISegmentedControl *)segmented {
7334 NSInteger selected([segmented selectedSegmentIndex]);
7336 return [self useRecent];
7337 bool simple(selected == 0);
7340 @synchronized (self) {
7341 [self setFilter:[=](Package *package) {
7342 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7345 [self setSorter:nullptr];
7348 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7350 return [super sectionsForPackages:packages];
7352 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
7354 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7355 Section *section(nil);
7358 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
7359 Package *package([packages objectAtIndex:offset]);
7361 time_t upgraded([package upgraded]);
7362 if (upgraded < 1168364520)
7365 upgraded -= upgraded % (60 * 60 * 24);
7367 if (section == nil || upgraded != last) {
7372 continue; // XXX: name = UCLocalize("...");
7374 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
7378 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7379 [sections addObject:section];
7382 [section addToCount];
7385 CFRelease(formatter);
7389 - (id) initWithDatabase:(Database *)database {
7390 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7391 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7392 [segmented setSelectedSegmentIndex:0];
7393 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7394 [[self navigationItem] setTitleView:segmented];
7396 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7397 [self useFilter:segmented];
7399 [self queueStatusDidChange];
7404 - (void) queueButtonClicked {
7405 [self.delegate queue];
7409 - (void) queueStatusDidChange {
7412 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7413 initWithTitle:UCLocalize("QUEUE")
7414 style:UIBarButtonItemStyleDone
7416 action:@selector(queueButtonClicked)
7419 [[self navigationItem] setRightBarButtonItem:nil];
7424 - (void) modeChanged:(UISegmentedControl *)segmented {
7425 [self useFilter:segmented];
7432 /* Source Cell {{{ */
7433 @interface SourceCell : CyteTableViewCell <
7434 CyteTableViewCellDelegate,
7437 _H<Source, 1> source_;
7440 _H<NSString> origin_;
7441 _H<NSString> label_;
7442 _H<UIActivityIndicatorView> indicator_;
7445 - (void) setSource:(Source *)source;
7446 - (void) setFetch:(NSNumber *)fetch;
7450 @implementation SourceCell
7452 - (void) _setImage:(NSArray *)data {
7453 if ([url_ isEqual:[data objectAtIndex:0]]) {
7454 icon_ = [data objectAtIndex:1];
7455 [self.content setNeedsDisplay];
7459 - (void) _setSource:(NSURL *) url {
7460 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7462 if (NSData *data = [NSURLConnection
7463 sendSynchronousRequest:[NSURLRequest
7465 cachePolicy:NSURLRequestUseProtocolCachePolicy
7469 returningResponse:NULL
7472 if (UIImage *image = [UIImage imageWithData:data])
7473 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
7478 - (void) setSource:(Source *)source {
7480 [source_ setDelegate:self];
7482 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
7484 icon_ = [UIImage imageNamed:@"unknown.png"];
7486 origin_ = [source name];
7487 label_ = [source rooturi];
7489 [self.content setNeedsDisplay];
7491 url_ = [source iconURL];
7492 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
7495 - (void) setAllSource {
7497 [indicator_ stopAnimating];
7499 icon_ = [UIImage imageNamed:@"folder.png"];
7500 origin_ = UCLocalize("ALL_SOURCES");
7501 label_ = UCLocalize("ALL_SOURCES_EX");
7502 [self.content setNeedsDisplay];
7505 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7506 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7507 [self.content setBackgroundColor:[UIColor whiteColor]];
7508 [self.content setOpaque:YES];
7510 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
7511 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
7512 [[self contentView] addSubview:indicator_];
7514 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
7518 - (void) layoutSubviews {
7519 [super layoutSubviews];
7521 UIView *content([self contentView]);
7522 CGRect bounds([content bounds]);
7524 CGRect frame([indicator_ frame]);
7525 frame.origin.x = bounds.size.width - frame.size.width;
7526 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
7528 if (kCFCoreFoundationVersionNumber < 800)
7529 frame.origin.x -= 8;
7530 [indicator_ setFrame:frame];
7533 - (NSString *) accessibilityLabel {
7537 - (void) drawContentRect:(CGRect)rect {
7538 bool highlighted(self.highlighted);
7539 float width(rect.size.width);
7543 rect.size = [(UIImage *) icon_ size];
7545 while (rect.size.width > 32 || rect.size.height > 32) {
7546 rect.size.width /= 2;
7547 rect.size.height /= 2;
7550 rect.origin.x = 26 - rect.size.width / 2;
7551 rect.origin.y = 26 - rect.size.height / 2;
7553 [icon_ drawInRect:Retina(rect)];
7556 if (highlighted && kCFCoreFoundationVersionNumber < 800)
7561 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
7565 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
7568 - (void) setFetch:(NSNumber *)fetch {
7569 if ([fetch boolValue])
7570 [indicator_ startAnimating];
7572 [indicator_ stopAnimating];
7577 /* Sources Controller {{{ */
7578 @interface SourcesController : CyteViewController <
7579 UITableViewDataSource,
7582 _transient Database *database_;
7585 _H<UITableView, 2> list_;
7586 _H<NSMutableArray> sources_;
7590 _H<UIProgressHUD> hud_;
7593 NSURLConnection *trivial_bz2_;
7594 NSURLConnection *trivial_gz_;
7599 - (id) initWithDatabase:(Database *)database;
7600 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
7604 @implementation SourcesController
7606 - (void) _releaseConnection:(NSURLConnection *)connection {
7607 if (connection != nil) {
7608 [connection cancel];
7609 //[connection setDelegate:nil];
7610 [connection release];
7615 [self _releaseConnection:trivial_gz_];
7616 [self _releaseConnection:trivial_bz2_];
7621 - (NSURL *) navigationURL {
7622 return [NSURL URLWithString:@"cydia://sources"];
7625 - (void) viewDidAppear:(BOOL)animated {
7626 [super viewDidAppear:animated];
7627 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7630 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7634 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7636 return UCLocalize("INDIVIDUAL_SOURCES");
7640 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7643 case 1: return [sources_ count];
7648 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7649 @synchronized (database_) {
7650 if ([database_ era] != era_)
7652 if ([indexPath section] != 1)
7654 NSUInteger index([indexPath row]);
7655 if (index >= [sources_ count])
7657 return [sources_ objectAtIndex:index];
7660 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7661 static NSString *cellIdentifier = @"SourceCell";
7663 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7664 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7665 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7667 Source *source([self sourceAtIndexPath:indexPath]);
7669 [cell setAllSource];
7671 [cell setSource:source];
7676 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7677 SectionsController *controller([[[SectionsController alloc]
7678 initWithDatabase:database_
7679 source:[self sourceAtIndexPath:indexPath]
7682 [controller setDelegate:self.delegate];
7683 [[self navigationController] pushViewController:controller animated:YES];
7686 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7687 if ([indexPath section] != 1)
7689 Source *source = [self sourceAtIndexPath:indexPath];
7690 return [source record] != nil;
7693 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7694 _assert([indexPath section] == 1);
7695 if (editingStyle == UITableViewCellEditingStyleDelete) {
7696 Source *source = [self sourceAtIndexPath:indexPath];
7697 if (source == nil) return;
7699 [Sources_ removeObjectForKey:[source key]];
7701 [self.delegate syncData];
7705 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
7706 [self updateButtonsForEditingStatusAnimated:YES];
7710 [self.delegate addTrivialSource:href_];
7713 [self.delegate syncData];
7716 - (NSString *) getWarning {
7717 NSString *href(href_);
7718 NSRange colon([href rangeOfString:@"://"]);
7719 if (colon.location != NSNotFound)
7720 href = [href substringFromIndex:(colon.location + 3)];
7721 href = [href stringByAddingPercentEscapes];
7722 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7724 NSURL *url([NSURL URLWithString:href]);
7726 NSStringEncoding encoding;
7727 NSError *error(nil);
7729 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7730 return [warning length] == 0 ? nil : warning;
7734 - (void) _endConnection:(NSURLConnection *)connection {
7735 // XXX: the memory management in this method is horribly awkward
7737 NSURLConnection **field = NULL;
7738 if (connection == trivial_bz2_)
7739 field = &trivial_bz2_;
7740 else if (connection == trivial_gz_)
7741 field = &trivial_gz_;
7742 _assert(field != NULL);
7743 [connection release];
7747 trivial_bz2_ == nil &&
7750 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
7752 [self.delegate releaseNetworkActivityIndicator];
7754 [self.delegate removeProgressHUD:hud_];
7758 if (warning != nil) {
7759 UIAlertView *alert = [[[UIAlertView alloc]
7760 initWithTitle:UCLocalize("SOURCE_WARNING")
7763 cancelButtonTitle:UCLocalize("CANCEL")
7765 UCLocalize("ADD_ANYWAY"),
7769 [alert setContext:@"warning"];
7770 [alert setNumberOfRows:1];
7773 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
7779 } else if (error_ != nil) {
7780 UIAlertView *alert = [[[UIAlertView alloc]
7781 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7782 message:[error_ localizedDescription]
7784 cancelButtonTitle:UCLocalize("OK")
7785 otherButtonTitles:nil
7788 [alert setContext:@"urlerror"];
7793 UIAlertView *alert = [[[UIAlertView alloc]
7794 initWithTitle:UCLocalize("NOT_REPOSITORY")
7795 message:UCLocalize("NOT_REPOSITORY_EX")
7797 cancelButtonTitle:UCLocalize("OK")
7798 otherButtonTitles:nil
7801 [alert setContext:@"trivial"];
7811 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7812 switch ([response statusCode]) {
7818 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7819 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7821 [self _endConnection:connection];
7824 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7825 [self _endConnection:connection];
7828 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7829 NSURL *url([NSURL URLWithString:href]);
7831 NSMutableURLRequest *request = [NSMutableURLRequest
7833 cachePolicy:NSURLRequestUseProtocolCachePolicy
7837 [request setHTTPMethod:method];
7839 if (Machine_ != NULL)
7840 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7842 if (UniqueID_ != nil)
7843 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7845 if ([url isCydiaSecure]) {
7846 if (UniqueID_ != nil)
7847 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
7850 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7853 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7854 NSString *context([alert context]);
7856 if ([context isEqualToString:@"source"]) {
7859 NSString *href = [[alert textField] text];
7860 href = VerifySource(href);
7865 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7866 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7870 // XXX: this is stupid
7871 hud_ = [self.delegate addProgressHUD];
7872 [hud_ setText:UCLocalize("VERIFYING_URL")];
7873 [self.delegate retainNetworkActivityIndicator];
7882 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7883 } else if ([context isEqualToString:@"trivial"])
7884 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7885 else if ([context isEqualToString:@"urlerror"])
7886 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7887 else if ([context isEqualToString:@"warning"]) {
7890 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
7899 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7903 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
7904 BOOL editing([list_ isEditing]);
7907 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7908 initWithTitle:UCLocalize("ADD")
7909 style:UIBarButtonItemStylePlain
7911 action:@selector(addButtonClicked)
7912 ] autorelease] animated:animated];
7913 else if ([self.delegate updating])
7914 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7915 initWithTitle:UCLocalize("CANCEL")
7916 style:UIBarButtonItemStyleDone
7918 action:@selector(cancelButtonClicked)
7919 ] autorelease] animated:animated];
7921 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7922 initWithTitle:UCLocalize("REFRESH")
7923 style:UIBarButtonItemStylePlain
7925 action:@selector(refreshButtonClicked)
7926 ] autorelease] animated:animated];
7928 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7929 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
7930 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7932 action:@selector(editButtonClicked)
7933 ] autorelease] animated:animated];
7937 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
7938 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7939 [list_ setRowHeight:53];
7940 [(UITableView *) list_ setDataSource:self];
7941 [list_ setDelegate:self];
7942 [self setView:list_];
7945 - (void) viewDidLoad {
7946 [super viewDidLoad];
7948 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7949 [self updateButtonsForEditingStatusAnimated:NO];
7952 - (void) viewWillAppear:(BOOL)animated {
7953 [super viewWillAppear:animated];
7955 [list_ setEditing:NO];
7956 [self updateButtonsForEditingStatusAnimated:NO];
7959 - (void) releaseSubviews {
7964 [super releaseSubviews];
7967 - (id) initWithDatabase:(Database *)database {
7968 if ((self = [super init]) != nil) {
7969 database_ = database;
7973 - (void) reloadData {
7975 [self updateButtonsForEditingStatusAnimated:YES];
7977 @synchronized (database_) {
7978 era_ = [database_ era];
7980 sources_ = [NSMutableArray arrayWithCapacity:16];
7981 [sources_ addObjectsFromArray:[database_ sources]];
7983 [sources_ sortUsingSelector:@selector(compareByName:)];
7986 int count([sources_ count]);
7988 for (int i = 0; i != count; i++) {
7989 if ([[sources_ objectAtIndex:i] record] == nil)
7997 - (void) showAddSourcePrompt {
7998 UIAlertView *alert = [[[UIAlertView alloc]
7999 initWithTitle:UCLocalize("ENTER_APT_URL")
8002 cancelButtonTitle:UCLocalize("CANCEL")
8004 UCLocalize("ADD_SOURCE"),
8008 [alert setContext:@"source"];
8010 [alert setNumberOfRows:1];
8011 [alert addTextFieldWithValue:@"http://" label:@""];
8013 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8014 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8015 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8016 [traits setKeyboardType:UIKeyboardTypeURL];
8017 // XXX: UIReturnKeyDone
8018 [traits setReturnKeyType:UIReturnKeyNext];
8023 - (void) addButtonClicked {
8024 [self showAddSourcePrompt];
8027 - (void) refreshButtonClicked {
8028 if ([self.delegate requestUpdate])
8029 [self updateButtonsForEditingStatusAnimated:YES];
8032 - (void) cancelButtonClicked {
8033 [self.delegate cancelUpdate];
8036 - (void) editButtonClicked {
8037 [list_ setEditing:![list_ isEditing] animated:YES];
8038 [self updateButtonsForEditingStatusAnimated:YES];
8044 /* Stash Controller {{{ */
8045 @interface StashController : CyteViewController {
8046 _H<UIActivityIndicatorView> spinner_;
8047 _H<UILabel> status_;
8048 _H<UILabel> caption_;
8053 @implementation StashController
8056 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8057 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8058 [self setView:view];
8060 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8062 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8063 CGRect spinrect = [spinner_ frame];
8064 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8065 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8066 [spinner_ setFrame:spinrect];
8067 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8068 [view addSubview:spinner_];
8069 [spinner_ startAnimating];
8072 captrect.size.width = [[self view] frame].size.width;
8073 captrect.size.height = 40.0f;
8074 captrect.origin.x = 0;
8075 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8076 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8077 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8078 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8079 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8080 [caption_ setTextColor:[UIColor whiteColor]];
8081 [caption_ setBackgroundColor:[UIColor clearColor]];
8082 [caption_ setShadowColor:[UIColor blackColor]];
8083 [caption_ setTextAlignment:NSTextAlignmentCenter];
8084 [view addSubview:caption_];
8087 statusrect.size.width = [[self view] frame].size.width;
8088 statusrect.size.height = 30.0f;
8089 statusrect.origin.x = 0;
8090 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8091 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8092 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8093 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8094 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8095 [status_ setTextColor:[UIColor whiteColor]];
8096 [status_ setBackgroundColor:[UIColor clearColor]];
8097 [status_ setShadowColor:[UIColor blackColor]];
8098 [status_ setTextAlignment:NSTextAlignmentCenter];
8099 [view addSubview:status_];
8102 - (void) releaseSubviews {
8107 [super releaseSubviews];
8113 @interface Cydia : CyteApplication <
8114 ConfirmationControllerDelegate,
8118 _H<CyteWindow> window_;
8119 _H<CydiaTabBarController> tabbar_;
8120 _H<CyteTabBarController> emulated_;
8121 _H<AppCacheController> appcache_;
8123 _H<NSMutableArray> essential_;
8124 _H<NSMutableArray> broken_;
8126 Database *database_;
8128 _H<NSURL> starturl_;
8132 _H<StashController> stash_;
8141 @implementation Cydia
8143 - (void) lockSuspend {
8144 if (locked_++ == 0) {
8145 if ($SBSSetInterceptsMenuButtonForever != NULL)
8146 (*$SBSSetInterceptsMenuButtonForever)(true);
8148 [self setIdleTimerDisabled:YES];
8152 - (void) unlockSuspend {
8153 if (--locked_ == 0) {
8154 [self setIdleTimerDisabled:NO];
8156 if ($SBSSetInterceptsMenuButtonForever != NULL)
8157 (*$SBSSetInterceptsMenuButtonForever)(false);
8161 - (void) beginUpdate {
8162 [tabbar_ beginUpdate];
8165 - (void) cancelUpdate {
8166 [tabbar_ cancelUpdate];
8169 - (bool) requestUpdate {
8170 if (CyteIsReachable("cydia.saurik.com")) {
8174 UIAlertView *alert = [[[UIAlertView alloc]
8175 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8176 message:@"Host Unreachable" // XXX: Localize
8178 cancelButtonTitle:UCLocalize("OK")
8179 otherButtonTitles:nil
8182 [alert setContext:@"norefresh"];
8190 return [tabbar_ updating];
8194 if ([broken_ count] != 0) {
8195 int count = [broken_ count];
8197 UIAlertView *alert = [[[UIAlertView alloc]
8198 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8199 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8201 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8203 UCLocalize("TEMPORARY_IGNORE"),
8207 [alert setContext:@"fixhalf"];
8208 [alert setNumberOfRows:2];
8210 } else if (!Ignored_ && [essential_ count] != 0) {
8211 int count = [essential_ count];
8213 UIAlertView *alert = [[[UIAlertView alloc]
8214 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8215 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8217 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8219 UCLocalize("UPGRADE_ESSENTIAL"),
8220 UCLocalize("COMPLETE_UPGRADE"),
8224 [alert setContext:@"upgrade"];
8229 - (void) returnToCydia {
8233 - (void) reloadSpringBoard {
8234 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8235 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8237 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8239 system("/usr/bin/killall backboardd SpringBoard");
8242 - (void) _saveConfig {
8243 SaveConfig(database_);
8246 // Navigation controller for the queuing badge.
8247 - (UINavigationController *) queueNavigationController {
8248 NSArray *controllers = [tabbar_ viewControllers];
8249 return [controllers objectAtIndex:3];
8252 - (void) _updateData {
8254 [window_ unloadData];
8256 UINavigationController *navigation = [self queueNavigationController];
8258 id queuedelegate = nil;
8259 if ([[navigation viewControllers] count] > 0)
8260 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8262 [queuedelegate queueStatusDidChange];
8263 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8266 - (void) _refreshIfPossible {
8267 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8269 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:CacheState_] objectForKey:@"LastUpdate"]);
8271 bool recently = false;
8272 if (update != nil) {
8273 NSTimeInterval interval([update timeIntervalSinceNow]);
8274 if (interval > -(15*60))
8278 // Don't automatic refresh if:
8279 // - We already refreshed recently.
8280 // - We already auto-refreshed this launch.
8281 // - Auto-refresh is disabled.
8282 // - Cydia's server is not reachable
8283 if (recently || loaded_ || ManualRefresh || !CyteIsReachable("cydia.saurik.com")) {
8284 // If we are cancelling, we need to make sure it knows it's already loaded.
8287 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8289 // We are going to load, so remember that.
8292 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
8298 - (void) refreshIfPossible {
8299 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8302 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8303 _profile(reloadDataWithInvocation)
8304 @synchronized (self) {
8305 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8307 [hud setText:UCLocalize("RELOADING_DATA")];
8309 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8313 [essential_ removeAllObjects];
8314 [broken_ removeAllObjects];
8316 _profile(reloadDataWithInvocation$Essential)
8317 NSArray *packages([database_ packages]);
8318 for (Package *package in packages) {
8320 [broken_ addObject:package];
8321 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8322 if ([package essential] && [package installed] != nil)
8323 [essential_ addObject:package];
8329 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8332 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8333 [changesItem setBadgeValue:badge];
8334 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8335 [self setApplicationIconBadgeNumber:changes];
8338 [changesItem setBadgeValue:nil];
8339 [changesItem setAnimatedBadge:NO];
8340 [self setApplicationIconBadgeNumber:0];
8347 [self removeProgressHUD:hud];
8354 - (void) updateData {
8358 - (void) updateDataAndLoad {
8360 if ([database_ progressDelegate] == nil)
8366 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8369 - (void) disemulate {
8370 if (emulated_ == nil)
8373 [window_ setRootViewController:tabbar_];
8376 [window_ setUserInteractionEnabled:YES];
8379 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8380 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8382 UIViewController *parent;
8383 if (emulated_ == nil)
8393 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8394 [parent presentModalViewController:navigation animated:YES];
8397 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8398 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8400 if (navigation != nil)
8401 [navigation pushViewController:progress animated:YES];
8403 [self presentModalViewController:progress force:YES];
8405 [progress invoke:invocation withTitle:title];
8409 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8410 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8413 - (void) repairWithInvocation:(NSInvocation *)invocation {
8415 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8419 - (void) repairWithSelector:(SEL)selector {
8420 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8423 - (void) reloadData {
8424 [self reloadDataWithInvocation:nil];
8425 if ([database_ progressDelegate] == nil)
8431 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8434 - (void) addSource:(NSDictionary *) source {
8435 CydiaAddSource(source);
8438 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
8439 CydiaAddSource(href, distribution, sections);
8442 // XXX: this method should not return anything
8443 - (BOOL) addTrivialSource:(NSString *)href {
8444 CydiaAddSource(href, @"./");
8449 pkgProblemResolver *resolver = [database_ resolver];
8451 resolver->InstallProtect();
8452 if (!resolver->Resolve(true))
8457 // XXX: this is a really crappy way of doing this.
8458 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8459 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8460 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8461 if ([tabbar_ updating])
8462 [tabbar_ cancelUpdate];
8464 if (![database_ prepare])
8467 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8468 [page setDelegate:self];
8469 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8472 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8473 [tabbar_ presentModalViewController:confirm_ animated:YES];
8479 @synchronized (self) {
8484 - (void) clearPackage:(Package *)package {
8485 @synchronized (self) {
8492 - (void) installPackages:(NSArray *)packages {
8493 @synchronized (self) {
8494 for (Package *package in packages)
8501 - (void) installPackage:(Package *)package {
8502 @synchronized (self) {
8509 - (void) removePackage:(Package *)package {
8510 @synchronized (self) {
8517 - (void) distUpgrade {
8518 @synchronized (self) {
8519 if (![database_ upgrade])
8527 system("/usr/bin/uicache");
8532 UIProgressHUD *hud([self addProgressHUD]);
8533 [hud setText:UCLocalize("LOADING")];
8534 [self yieldToSelector:@selector(_uicache)];
8535 [self removeProgressHUD:hud];
8539 [database_ perform];
8540 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8541 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
8544 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8547 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8548 [self unlockSuspend];
8551 - (void) cancelAndClear:(bool)clear {
8552 @synchronized (self) {
8564 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8565 NSString *context([alert context]);
8567 if ([context isEqualToString:@"conffile"]) {
8568 FILE *input = [database_ input];
8569 if (button == [alert cancelButtonIndex])
8570 fprintf(input, "N\n");
8571 else if (button == [alert firstOtherButtonIndex])
8572 fprintf(input, "Y\n");
8575 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8576 } else if ([context isEqualToString:@"fixhalf"]) {
8577 if (button == [alert cancelButtonIndex]) {
8578 @synchronized (self) {
8579 for (Package *broken in (id) broken_) {
8581 NSString *id(ShellEscape([broken id]));
8582 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
8583 " /var/lib/dpkg/info/%@.prerm"
8584 " /var/lib/dpkg/info/%@.postrm"
8585 " /var/lib/dpkg/info/%@.preinst"
8586 " /var/lib/dpkg/info/%@.postinst"
8587 " /var/lib/dpkg/info/%@.extrainst_"
8588 "", id, id, id, id, id] UTF8String]);
8594 } else if (button == [alert firstOtherButtonIndex]) {
8595 [broken_ removeAllObjects];
8599 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8600 } else if ([context isEqualToString:@"upgrade"]) {
8601 if (button == [alert firstOtherButtonIndex]) {
8602 @synchronized (self) {
8603 for (Package *essential in (id) essential_)
8604 [essential install];
8609 } else if (button == [alert firstOtherButtonIndex] + 1) {
8611 } else if (button == [alert cancelButtonIndex]) {
8615 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8619 - (void) system:(NSString *)command {
8620 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8623 system([command UTF8String]);
8629 - (void) applicationWillSuspend {
8631 [super applicationWillSuspend];
8634 - (BOOL) isSafeToSuspend {
8637 NSLog(@"isSafeToSuspend: locked_ != 0");
8642 if ([tabbar_ modalViewController] != nil)
8645 // Use external process status API internally.
8646 // This is probably a really bad idea.
8647 // XXX: what is the point of this? does this solve anything at all?
8648 uint64_t status = 0;
8650 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8651 notify_get_state(notify_token, &status);
8652 notify_cancel(notify_token);
8657 NSLog(@"isSafeToSuspend: status != 0");
8663 NSLog(@"isSafeToSuspend: -> true");
8668 - (void) suspendReturningToLastApp:(BOOL)returning {
8669 if ([self isSafeToSuspend])
8670 [super suspendReturningToLastApp:returning];
8674 if ([self isSafeToSuspend])
8678 - (void) applicationSuspend {
8679 if ([self isSafeToSuspend])
8680 [super applicationSuspend];
8683 - (void) applicationSuspend:(GSEventRef)event {
8684 if ([self isSafeToSuspend])
8685 [super applicationSuspend:event];
8688 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8689 if ([self isSafeToSuspend])
8690 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8693 - (void) _setSuspended:(BOOL)value {
8694 if ([self isSafeToSuspend])
8695 [super _setSuspended:value];
8698 - (UIProgressHUD *) addProgressHUD {
8699 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
8700 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8702 [window_ setUserInteractionEnabled:NO];
8704 UIViewController *target(tabbar_);
8705 if (UIViewController *modal = [target modalViewController])
8708 [hud showInView:[target view]];
8714 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8715 [self unlockSuspend];
8717 [hud removeFromSuperview];
8718 [window_ setUserInteractionEnabled:YES];
8721 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
8722 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
8725 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
8726 NSString *scheme([[url scheme] lowercaseString]);
8727 if ([[url absoluteString] length] <= [scheme length] + 3)
8729 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8730 NSArray *components([path componentsSeparatedByString:@"/"]);
8732 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
8733 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
8734 if (controller != nil)
8735 [controller setDelegate:self];
8739 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8742 NSString *base([components objectAtIndex:0]);
8744 CyteViewController *controller = nil;
8746 if ([base isEqualToString:@"url"]) {
8747 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8748 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8749 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
8750 } else if (!external && [components count] == 1) {
8751 if ([base isEqualToString:@"sources"]) {
8752 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8755 if ([base isEqualToString:@"home"]) {
8756 controller = [[[HomeController alloc] init] autorelease];
8759 if ([base isEqualToString:@"sections"]) {
8760 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
8763 if ([base isEqualToString:@"search"]) {
8764 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
8767 if ([base isEqualToString:@"changes"]) {
8768 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8771 if ([base isEqualToString:@"installed"]) {
8772 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8774 } else if ([components count] == 2) {
8775 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8777 if ([base isEqualToString:@"package"]) {
8778 controller = [self pageForPackage:argument withReferrer:referrer];
8781 if (!external && [base isEqualToString:@"search"]) {
8782 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
8785 if (!external && [base isEqualToString:@"sections"]) {
8786 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
8788 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
8791 if ([base isEqualToString:@"sources"]) {
8792 if ([argument isEqualToString:@"add"]) {
8793 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8794 [(SourcesController *)controller showAddSourcePrompt];
8796 Source *source([database_ sourceWithKey:argument]);
8797 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
8801 if (!external && [base isEqualToString:@"launch"]) {
8802 [self launchApplicationWithIdentifier:argument suspended:NO];
8805 } else if (!external && [components count] == 3) {
8806 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8807 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8809 if ([base isEqualToString:@"package"]) {
8810 if ([arg2 isEqualToString:@"settings"]) {
8811 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8812 } else if ([arg2 isEqualToString:@"files"]) {
8813 controller = [[[FileTable alloc] initWithDatabase:database_ forPackage:arg1] autorelease];
8817 if ([base isEqualToString:@"sections"]) {
8818 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
8819 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
8820 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
8824 [controller setDelegate:self];
8828 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
8829 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
8832 [tabbar_ setUnselectedViewController:page];
8837 - (void) applicationOpenURL:(NSURL *)url {
8838 [super applicationOpenURL:url];
8843 [self openCydiaURL:url forExternal:YES];
8846 - (void) applicationWillResignActive:(UIApplication *)application {
8847 // Stop refreshing if you get a phone call or lock the device.
8848 if ([tabbar_ updating])
8849 [tabbar_ cancelUpdate];
8851 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8852 [super applicationWillResignActive:application];
8855 - (void) saveState {
8856 [[NSDictionary dictionaryWithObjectsAndKeys:
8857 @"InterfaceState", [tabbar_ navigationURLCollection],
8858 @"LastClosed", [NSDate date],
8859 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
8860 nil] writeToFile:SavedState_ atomically:YES];
8865 - (void) applicationWillTerminate:(UIApplication *)application {
8869 - (void) applicationDidEnterBackground:(UIApplication *)application {
8870 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
8871 return [self terminateWithSuccess];
8872 Backgrounded_ = [NSDate date];
8876 - (void) applicationWillEnterForeground:(UIApplication *)application {
8877 if (Backgrounded_ == nil)
8880 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
8882 if (interval <= -(30*60)) {
8883 [tabbar_ setSelectedIndex:0];
8884 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
8887 if (interval <= -(15*60)) {
8888 if (CyteIsReachable("cydia.saurik.com")) {
8889 [tabbar_ beginUpdate];
8890 [appcache_ reloadURLWithCache:YES];
8894 if ([database_ delocked])
8898 - (void) setConfigurationData:(NSString *)data {
8899 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
8901 if (!conffile_r(data)) {
8902 lprintf("E:invalid conffile\n");
8906 NSString *ofile = conffile_r[1];
8907 //NSString *nfile = conffile_r[2];
8909 UIAlertView *alert = [[[UIAlertView alloc]
8910 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
8911 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
8913 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
8915 UCLocalize("ACCEPT_NEW_COPY"),
8916 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
8920 [alert setContext:@"conffile"];
8921 [alert setNumberOfRows:2];
8925 - (void) addStashController {
8927 stash_ = [[[StashController alloc] init] autorelease];
8928 [window_ addSubview:[stash_ view]];
8931 - (void) removeStashController {
8932 [[stash_ view] removeFromSuperview];
8934 [self unlockSuspend];
8938 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8939 UpdateExternalStatus(1);
8940 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
8941 UpdateExternalStatus(0);
8943 [self removeStashController];
8944 [self reloadSpringBoard];
8947 - (void) applicationDidFinishLaunching:(id)unused {
8948 [super applicationDidFinishLaunching:unused];
8949 [CyteWebViewController _initialize];
8951 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
8953 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8955 // this would disallow http{,s} URLs from accessing this data
8956 //[WebView registerURLSchemeAsLocal:@"cydia"];
8958 Font12_ = [UIFont systemFontOfSize:12];
8959 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
8960 Font14_ = [UIFont systemFontOfSize:14];
8961 Font18_ = [UIFont systemFontOfSize:18];
8962 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
8963 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
8965 essential_ = [NSMutableArray arrayWithCapacity:4];
8966 broken_ = [NSMutableArray arrayWithCapacity:4];
8968 // XXX: I really need this thing... like, seriously... I'm sorry
8969 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
8970 [appcache_ reloadData];
8972 window_ = [[[CyteWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
8973 [window_ orderFront:self];
8974 [window_ makeKey:self];
8975 [window_ setHidden:NO];
8977 if (access("/.cydia_no_stash", F_OK) == 0);
8981 [self addStashController];
8982 // XXX: this would be much cleaner as a yieldToSelector:
8983 // that way the removeStashController could happen right here inline
8984 // we also could no longer require the useless stash_ field anymore
8985 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8990 int error(stat("/", &root));
8991 _assert(error != -1);
8993 #define Stash_(path) do { \
8994 struct stat folder; \
8995 int error(lstat((path), &folder)); \
8996 if (error != -1 && ( \
8997 folder.st_dev == root.st_dev && \
8998 S_ISDIR(folder.st_mode) \
8999 ) || error == -1 && ( \
9000 errno == ENOENT || \
9005 Stash_("/Applications");
9006 Stash_("/Library/Ringtones");
9007 Stash_("/Library/Wallpaper");
9008 //Stash_("/usr/bin");
9009 Stash_("/usr/include");
9010 Stash_("/usr/share");
9011 //Stash_("/var/lib");
9015 database_ = [Database sharedInstance];
9016 [database_ setDelegate:self];
9018 [window_ setUserInteractionEnabled:NO];
9020 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9022 [tabbar_ addViewControllers:nil,
9023 @"Cydia", @"home.png", @"home7.png", @"home7s.png",
9024 UCLocalize("SOURCES"), @"install.png", @"install7.png", @"install7s.png",
9025 UCLocalize("CHANGES"), @"changes.png", @"changes7.png", @"changes7s.png",
9026 UCLocalize("INSTALLED"), @"manage.png", @"manage7.png", @"manage7s.png",
9027 UCLocalize("SEARCH"), @"search.png", @"search7.png", @"search7s.png",
9030 [tabbar_ setUpdateDelegate:self];
9032 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9033 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9034 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9036 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9037 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9038 [emulated_ setSelectedIndex:0];
9040 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9041 [emulated_ concealTabBarSelection];
9043 [window_ setRootViewController:emulated_];
9045 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9049 - (NSArray *) defaultStartPages {
9050 NSMutableArray *standard = [NSMutableArray array];
9051 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9052 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9053 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9054 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9055 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9061 if ([emulated_ modalViewController] != nil)
9062 [emulated_ dismissModalViewControllerAnimated:YES];
9063 [window_ setUserInteractionEnabled:NO];
9065 [self reloadDataWithInvocation:nil];
9066 [self refreshIfPossible];
9069 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:SavedState_]);
9071 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9072 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9073 int standardIndex = 0;
9074 NSArray *standard = [self defaultStartPages];
9081 NSDate *closed = [state objectForKey:@"LastClosed"];
9082 if (valid && closed != nil) {
9083 NSTimeInterval interval([closed timeIntervalSinceNow]);
9084 if (interval <= -(30*60))
9088 if (valid && [saved count] != [standard count])
9092 for (unsigned int i = 0; i < [standard count]; i++) {
9093 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9094 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9095 // but it's good enough for now.
9096 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9103 NSArray *items = nil;
9105 [tabbar_ setSelectedIndex:savedIndex];
9108 [tabbar_ setSelectedIndex:standardIndex];
9112 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9113 NSArray *stack = [items objectAtIndex:tab];
9114 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9115 NSMutableArray *current = [NSMutableArray array];
9117 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9118 NSString *addr = [stack objectAtIndex:nav];
9119 NSURL *url = [NSURL URLWithString:addr];
9120 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9122 [current addObject:page];
9125 [navigation setViewControllers:current];
9128 // (Try to) show the startup URL.
9129 if (starturl_ != nil) {
9130 [self openCydiaURL:starturl_ forExternal:YES];
9135 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9137 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9138 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9141 if (item != nil && IsWildcat_) {
9142 [sheet showFromBarButtonItem:item animated:YES];
9144 [sheet showInView:window_];
9148 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9149 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9150 [progress setTitle:task];
9151 [progress addProgressEvent:event];
9154 - (void) addProgressEventForTask:(NSArray *)data {
9155 CydiaProgressEvent *event([data objectAtIndex:0]);
9156 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9157 [self addProgressEvent:event forTask:task];
9160 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9161 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9167 id Alloc_(id self, SEL selector) {
9168 id object = alloc_(self, selector);
9169 lprintf("[%s]A-%p\n", self->isa->name, object);
9174 id Dealloc_(id self, SEL selector) {
9175 id object = dealloc_(self, selector);
9176 lprintf("[%s]D-%p\n", self->isa->name, object);
9180 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9183 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9185 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9187 return [(NSMutableDictionary *) copy autorelease];
9193 int main_rred(int, char *argv[]);
9195 int main_gzip(int, char *argv[]);
9197 int main_store(int, char *argv[]);
9201 int main(int argc, char *argv[]) {
9202 const char *argv0(argv[0]);
9203 if (const char *slash = strrchr(argv0, '/'))
9206 else if (!strcmp(argv0, "copy"))
9208 else if (!strcmp(argv0, "file"))
9210 else if (!strcmp(argv0, "gpgv"))
9212 else if (!strcmp(argv0, "rred"))
9213 return main_rred(argc, argv);
9215 else if (!strcmp(argv0, "bzip2"))
9216 return main_gzip(argc, argv);
9217 else if (!strcmp(argv0, "gzip"))
9218 return main_gzip(argc, argv);
9219 else if (!strcmp(argv0, "lzma"))
9220 return main_gzip(argc, argv);
9223 else if (!strcmp(argv0, "store"))
9224 return main_store(argc, argv);
9226 else if (!strcmp(argv0, "http"))
9228 else if (!strcmp(argv0, "https"))
9232 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9236 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9240 CyteInitialize([NSString stringWithFormat:@"Cydia/%@", Cydia_]);
9241 UpdateExternalStatus(0);
9243 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9244 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9245 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9247 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@/1.1", IsWildcat_ ? @"ipad" : @"iphone"]);
9248 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9250 /* Set Locale {{{ */
9251 Locale_ = CFLocaleCopyCurrent();
9252 Languages_ = [NSLocale preferredLanguages];
9254 std::string languages;
9255 const char *translation(NULL);
9257 // XXX: this isn't really a language, but this is compatible with older Cydia builds
9258 if (Locale_ != NULL)
9259 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
9260 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
9261 if (pattern(language)) {
9262 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
9263 languages += translation;
9268 if (Languages_ != nil)
9269 for (NSString *locale : Languages_) {
9270 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
9271 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
9272 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
9273 language = [NSString stringWithFormat:@"%@-%@", language, script];
9274 languages += [language UTF8String];
9279 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
9281 /* Index Collation {{{ */
9282 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
9283 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
9284 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
9285 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
9286 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
9287 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
9289 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
9291 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
9292 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
9293 for (NSInteger offset : (NSInteger[]) {0,1,3,4,6,7,9,10,12,13,15,16,18,25,26,29,30,33,34,37,38,42,43,46,47,50,51})
9294 CollationOffset_.push_back(offset);
9295 CollationTitles_ = [NSArray arrayWithObjects:@"1 畫",@"2 畫",@"3 畫",@"4 畫",@"5 畫",@"6 畫",@"7 畫",@"8 畫",@"9 畫",@"10 畫",@"11 畫",@"12 畫",@"13 畫",@"14 畫",@"15 畫",@"16 畫",@"17 畫",@"18 畫",@"19 畫",@"20 畫",@"21 畫",@"22 畫",@"23 畫",@"24 畫",@"25 畫以上",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
9296 CollationStarts_ = [NSArray arrayWithObjects:@"一",@"丁",@"丈",@"不",@"且",@"丞",@"串",@"並",@"亭",@"乘",@"乾",@"傀",@"亂",@"僎",@"僵",@"儐",@"償",@"叢",@"儳",@"嚴",@"儷",@"儻",@"囌",@"囑",@"廳",@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil];
9299 CollationThumbs_ = [collation sectionIndexTitles];
9300 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
9301 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
9303 CollationTitles_ = [collation sectionTitles];
9304 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
9306 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
9307 if (&transform != NULL && transform != nil) {
9308 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
9309 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
9310 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
9311 UErrorCode code(U_ZERO_ERROR);
9312 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
9313 if (!U_SUCCESS(code))
9314 NSLog(@"%s", u_errorName(code));
9318 } @catch (NSException *e) {
9322 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
9324 CollationThumbs_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
9325 for (NSInteger offset(0); offset != 28; ++offset)
9326 CollationOffset_.push_back(offset);
9328 CollationTitles_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
9329 CollationStarts_ = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil];
9333 App_ = [[NSBundle mainBundle] bundlePath];
9336 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
9337 mkdir([Cache_ UTF8String], 0755);
9339 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9340 alloc_ = alloc->method_imp;
9341 alloc->method_imp = (IMP) &Alloc_;*/
9343 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9344 dealloc_ = dealloc->method_imp;
9345 dealloc->method_imp = (IMP) &Dealloc_;*/
9347 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
9348 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
9349 UniqueID_ = UniqueIdentifier([UIDevice currentDevice]);
9351 /* System Information {{{ */
9355 size = sizeof(maxproc);
9356 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9357 perror("sysctlbyname(\"kern.maxproc\", ?)");
9358 else if (maxproc < 64) {
9360 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9361 perror("sysctlbyname(\"kern.maxproc\", #)");
9364 /* Load Database {{{ */
9365 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9368 mkdir("/var/mobile/Library/Cydia", 0755);
9369 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
9372 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
9373 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
9374 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
9375 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
9378 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
9381 Values_ = [metadata objectForKey:@"Values"];
9383 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
9385 if (Sections_ == nil)
9386 Sections_ = [metadata objectForKey:@"Sections"];
9387 if (Sections_ == nil)
9388 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9390 if (Sources_ == nil)
9391 Sources_ = [metadata objectForKey:@"Sources"];
9392 if (Sources_ == nil)
9393 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9395 // XXX: this wrong, but in a way that doesn't matter :/
9396 if (Version_ == nil)
9397 Version_ = [metadata objectForKey:@"Version"];
9398 if (Version_ == nil)
9399 Version_ = [NSNumber numberWithUnsignedInt:0];
9401 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
9403 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
9406 NSLog(@"unable to import package preferences... from 2010? oh well :/");
9409 if ([Version_ unsignedIntValue] == 0) {
9410 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9411 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9412 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9414 Version_ = [NSNumber numberWithUnsignedInt:1];
9416 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:CacheState_]) {
9417 [cache removeObjectForKey:@"LastUpdate"];
9418 [cache writeToFile:CacheState_ atomically:YES];
9422 _H<NSMutableArray> broken([NSMutableArray array]);
9423 for (NSString *key in (id) Sources_)
9424 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
9425 [broken addObject:key];
9426 if ([broken count] != 0)
9427 for (NSString *key in (id) broken)
9428 [Sources_ removeObjectForKey:key];
9432 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
9435 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9437 if (kCFCoreFoundationVersionNumber > 1000)
9438 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
9440 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9442 if (access("/User", F_OK) != 0 || version != 6) {
9444 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
9448 if (access("/tmp/cydia.chk", F_OK) == 0) {
9449 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
9450 _assert(errno == ENOENT);
9451 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
9452 _assert(errno == ENOENT);
9455 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/ln -sf %@ /etc/apt/sources.list.d/cydia.list", Cache("sources.list")] UTF8String]);
9457 /* APT Initialization {{{ */
9458 _assert(pkgInitConfig(*_config));
9459 _assert(pkgInitSystem(*_config, _system));
9461 _config->Set("Acquire::AllowInsecureRepositories", true);
9462 _config->Set("Acquire::Check-Valid-Until", false);
9464 _config->Set("Dir::Bin::Methods", "/Applications/Cydia.app");
9466 _config->Set("pkgCacheGen::ForceEssential", "");
9468 if (translation != NULL)
9469 _config->Set("APT::Acquire::Translation", translation);
9470 _config->Set("Acquire::Languages", languages);
9472 // XXX: this timeout might be important :(
9473 //_config->Set("Acquire::http::Timeout", 15);
9476 size = sizeof(usermem);
9477 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
9479 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
9481 mkdir([Cache("archives") UTF8String], 0755);
9482 mkdir([Cache("archives/partial") UTF8String], 0755);
9483 _config->Set("Dir::Cache", [Cache_ UTF8String]);
9485 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
9486 _config->Set("Dir::State", [Cache_ UTF8String]);
9488 mkdir([Cache("lists") UTF8String], 0755);
9489 mkdir([Cache("lists/partial") UTF8String], 0755);
9490 mkdir([Cache("periodic") UTF8String], 0755);
9491 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
9493 std::string logs("/var/mobile/Library/Logs/Cydia");
9494 mkdir(logs.c_str(), 0755);
9495 _config->Set("Dir::Log", logs);
9497 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
9499 /* Color Choices {{{ */
9500 space_ = CGColorSpaceCreateDeviceRGB();
9502 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9503 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9504 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9505 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
9506 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9507 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9508 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9509 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9510 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9511 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9513 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9514 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9516 /* UIKit Configuration {{{ */
9517 // XXX: I have a feeling this was important
9518 //UIKeyboardDisableAutomaticAppearance();
9521 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
9522 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
9524 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
9525 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
9526 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
9528 PulseInterval_ = fast ? 50000 : 500000;
9530 Colon_ = UCLocalize("COLON_DELIMITED");
9531 Elision_ = UCLocalize("ELISION");
9532 Error_ = UCLocalize("ERROR");
9533 Warning_ = UCLocalize("WARNING");
9536 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9538 CGColorSpaceRelease(space_);