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 NSString *Cache_;
234 #define Cache(file) \
235 [NSString stringWithFormat:@"%@/%s", Cache_, file]
237 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
238 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
240 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
242 static NSString *UniqueIdentifier(UIDevice *device = nil) {
243 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
244 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
246 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
249 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
251 static _finline NSString *CydiaURL(NSString *path) {
253 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
254 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
255 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
256 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
257 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
259 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
262 static NSString *ShellEscape(NSString *value) {
263 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
266 static _finline void UpdateExternalStatus(uint64_t newStatus) {
268 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
269 notify_set_state(notify_token, newStatus);
270 notify_cancel(notify_token);
272 notify_post("com.saurik.Cydia.status");
275 /* NSForcedOrderingSearch doesn't work on the iPhone */
276 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
277 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
278 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
280 /* Insertion Sort {{{ */
282 template <typename Type_>
283 size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
284 const char *ptr = (const char *)list;
286 size_t half = count / 2;
287 const char *probe = ptr + sizeof(Type_) * half;
288 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
289 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
290 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
291 count = (cr < 0) ? half : (half + (count & 1) - 1);
293 return (ptr - (const char *)list) / sizeof(Type_);
296 template <typename Type_>
297 void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
301 #if HistogramInsertionSort > 0
302 uint32_t total(0), *offsets(new uint32_t[length]);
305 for (size_t index(1); index != length; ++index) {
306 Type_ value(values[index]);
308 size_t correct(CFBSearch_(value, values, index, comparator, context));
310 size_t correct(index);
311 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
312 #if HistogramInsertionSort > 1
313 NSLog(@"%@ < %@", value, values[correct - 1]);
317 if (index - correct >= 8) {
318 correct = CFBSearch_(value, values, correct, comparator, context);
323 if (correct != index) {
324 size_t offset(index - correct);
325 #if HistogramInsertionSort
329 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
331 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
332 values[correct] = value;
336 #if HistogramInsertionSort > 0
337 for (size_t index(0); index != range.length; ++index)
338 if (offsets[index] != 0)
339 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
340 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
347 /* Cydia NSString Additions {{{ */
348 @interface NSString (Cydia)
349 - (NSComparisonResult) compareByPath:(NSString *)other;
350 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
353 @implementation NSString (Cydia)
355 - (NSComparisonResult) compareByPath:(NSString *)other {
356 NSString *prefix = [self commonPrefixWithString:other options:0];
357 size_t length = [prefix length];
359 NSRange lrange = NSMakeRange(length, [self length] - length);
360 NSRange rrange = NSMakeRange(length, [other length] - length);
362 lrange = [self rangeOfString:@"/" options:0 range:lrange];
363 rrange = [other rangeOfString:@"/" options:0 range:rrange];
365 NSComparisonResult value;
367 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
368 value = NSOrderedSame;
369 else if (lrange.location == NSNotFound)
370 value = NSOrderedAscending;
371 else if (rrange.location == NSNotFound)
372 value = NSOrderedDescending;
374 value = NSOrderedSame;
376 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
377 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
378 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
379 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
381 NSComparisonResult result = [lpath compare:rpath];
382 return result == NSOrderedSame ? value : result;
385 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
386 return [(id)CFURLCreateStringByAddingPercentEscapes(
391 kCFStringEncodingUTF8
398 /* C++ NSString Wrapper Cache {{{ */
399 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
400 return size == 0 ? NULL :
401 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
402 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
405 static _finline CFStringRef CYStringCreate(const std::string &data) {
406 return CYStringCreate(data.data(), data.size());
409 static _finline CFStringRef CYStringCreate(const char *data) {
410 return CYStringCreate(data, strlen(data));
419 _finline void clear_() {
420 if (cache_ != NULL) {
427 _finline bool empty() const {
431 _finline size_t size() const {
435 _finline char *data() const {
439 _finline void clear() {
444 _finline CYString() :
451 _finline ~CYString() {
455 void operator =(const CYString &rhs) {
459 if (rhs.cache_ == nil)
462 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
465 void copy(CYPool *pool) {
466 char *temp(pool->malloc<char>(size_ + 1));
467 memcpy(temp, data_, size_);
472 void set(CYPool *pool, const char *data, size_t size) {
478 data_ = const_cast<char *>(data);
486 _finline void set(CYPool *pool, const char *data) {
487 set(pool, data, data == NULL ? 0 : strlen(data));
490 _finline void set(CYPool *pool, const std::string &rhs) {
491 set(pool, rhs.data(), rhs.size());
494 bool operator ==(const CYString &rhs) const {
495 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
498 _finline operator CFStringRef() {
500 cache_ = CYStringCreate(data_, size_);
504 _finline operator id() {
505 return (NSString *) static_cast<CFStringRef>(*this);
508 _finline operator const char *() {
509 return reinterpret_cast<const char *>(data_);
513 /* C++ NSString Algorithm Adapters {{{ */
515 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
518 struct NSStringMapHash :
519 std::unary_function<NSString *, size_t>
521 _finline size_t operator ()(NSString *value) const {
522 return CFStringHashNSString((CFStringRef) value);
526 struct NSStringMapLess :
527 std::binary_function<NSString *, NSString *, bool>
529 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
530 return [lhs compare:rhs] == NSOrderedAscending;
534 struct NSStringMapEqual :
535 std::binary_function<NSString *, NSString *, bool>
537 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
538 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
539 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
540 //[lhs isEqualToString:rhs];
545 /* CoreGraphics Primitives {{{ */
550 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
551 CGFloat color[] = {red, green, blue, alpha};
552 return CGColorCreate(space, color);
561 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
562 color_(Create_(space, red, green, blue, alpha))
564 Set(space, red, green, blue, alpha);
569 CGColorRelease(color_);
576 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
578 color_ = Create_(space, red, green, blue, alpha);
581 operator CGColorRef() {
587 /* Random Global Variables {{{ */
588 static int PulseInterval_ = 500000;
590 static const NSString *UI_;
593 static bool RestartSubstrate_;
594 static NSArray *Finishes_;
596 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
597 #define NotifyConfig_ "/etc/notify.conf"
599 static bool Queuing_;
601 static CYColor Blue_;
602 static CYColor Blueish_;
603 static CYColor Black_;
604 static CYColor Folder_;
606 static CYColor White_;
607 static CYColor Gray_;
608 static CYColor Green_;
609 static CYColor Purple_;
610 static CYColor Purplish_;
612 static UIColor *InstallingColor_;
613 static UIColor *RemovingColor_;
615 static NSString *App_;
617 static BOOL Advanced_;
618 static BOOL Ignored_;
620 static _H<UIFont> Font12_;
621 static _H<UIFont> Font12Bold_;
622 static _H<UIFont> Font14_;
623 static _H<UIFont> Font18_;
624 static _H<UIFont> Font18Bold_;
625 static _H<UIFont> Font22Bold_;
627 static _H<NSString> UniqueID_;
629 static _H<NSLocale> CollationLocale_;
630 static _H<NSArray> CollationThumbs_;
631 static std::vector<NSInteger> CollationOffset_;
632 static _H<NSArray> CollationTitles_;
633 static _H<NSArray> CollationStarts_;
634 static UTransliterator *CollationTransl_;
635 //static Function<NSString *, NSString *> CollationModify_;
637 typedef std::basic_string<UChar> ustring;
638 static ustring CollationString_;
640 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
641 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
642 static struct UReplaceableCallbacks CollationUCalls_ = {
643 .length = [](const UReplaceable *rep) -> int32_t { CUC;
647 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
648 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
649 if (offset >= str.size())
654 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
655 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
656 if (offset >= str.size())
659 U16_GET(str.data(), 0, offset, str.size(), c);
663 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
664 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
665 str.replace(start, limit - start, text, length);
668 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
669 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
670 str.copy(dst, limit - start, start);
673 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
674 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
675 str.replace(dest, 0, str, start, limit - start);
679 static CFLocaleRef Locale_;
680 static NSArray *Languages_;
681 static CGColorSpaceRef space_;
683 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
684 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
686 static NSDictionary *SectionMap_;
687 static _H<NSDate> Backgrounded_;
688 static _transient NSMutableDictionary *Values_;
689 static _transient NSMutableDictionary *Sections_;
690 _H<NSMutableDictionary> Sources_;
691 static _transient NSNumber *Version_;
694 static _H<NSMutableDictionary> SessionData_;
695 static _H<NSMutableSet> BridgedHosts_;
696 static _H<NSMutableSet> InsecureHosts_;
698 static NSString *kCydiaProgressEventTypeError = @"Error";
699 static NSString *kCydiaProgressEventTypeInformation = @"Information";
700 static NSString *kCydiaProgressEventTypeStatus = @"Status";
701 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
704 /* Display Helpers {{{ */
705 static _finline const char *StripVersion_(const char *version) {
706 const char *colon(strchr(version, ':'));
707 return colon == NULL ? version : colon + 1;
710 NSString *LocalizeSection(NSString *section) {
711 static RegEx title_r("(.*?) \\((.*)\\)");
712 if (title_r(section)) {
713 NSString *parent(title_r[1]);
714 NSString *child(title_r[2]);
716 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
717 LocalizeSection(parent),
718 LocalizeSection(child)
722 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
725 NSString *Simplify(NSString *title) {
726 const char *data = [title UTF8String];
727 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
729 static RegEx square_r("\\[(.*)\\]");
730 if (square_r(data, size))
731 return Simplify(square_r[1]);
733 static RegEx paren_r("\\((.*)\\)");
734 if (paren_r(data, size))
735 return Simplify(paren_r[1]);
737 static RegEx title_r("(.*?) \\((.*)\\)");
738 if (title_r(data, size))
739 return Simplify(title_r[1]);
745 bool isSectionVisible(NSString *section) {
746 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
747 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
748 return hidden == nil || ![hidden boolValue];
751 static NSString *VerifySource(NSString *href) {
752 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
754 [[[[UIAlertView alloc]
755 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
756 message:UCLocalize("INVALID_URL_EX")
758 cancelButtonTitle:UCLocalize("OK")
759 otherButtonTitles:nil
760 ] autorelease] show];
765 if (![href hasSuffix:@"/"])
766 href = [href stringByAppendingString:@"/"];
772 /* Delegate Prototypes {{{ */
775 @class CydiaProgressEvent;
777 @protocol DatabaseDelegate
778 - (void) repairWithSelector:(SEL)selector;
779 - (void) setConfigurationData:(NSString *)data;
780 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
783 @class CYPackageController;
785 @protocol SourceDelegate
786 - (void) setFetch:(NSNumber *)fetch;
789 @protocol FetchDelegate
790 - (bool) isSourceCancelled;
791 - (void) startSourceFetch:(NSString *)uri;
792 - (void) stopSourceFetch:(NSString *)uri;
795 @protocol CydiaDelegate
796 - (void) returnToCydia;
798 - (void) retainNetworkActivityIndicator;
799 - (void) releaseNetworkActivityIndicator;
800 - (void) clearPackage:(Package *)package;
801 - (void) installPackage:(Package *)package;
802 - (void) installPackages:(NSArray *)packages;
803 - (void) removePackage:(Package *)package;
804 - (void) beginUpdate;
806 - (bool) requestUpdate;
807 - (void) distUpgrade;
810 - (void) _saveConfig;
812 - (void) addSource:(NSDictionary *)source;
813 - (BOOL) addTrivialSource:(NSString *)href;
814 - (UIProgressHUD *) addProgressHUD;
815 - (void) removeProgressHUD:(UIProgressHUD *)hud;
816 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
817 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
821 /* CancelStatus {{{ */
823 public pkgAcquireStatus
834 virtual bool MediaChange(std::string media, std::string drive) {
838 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
842 virtual bool Pulse_(pkgAcquire *Owner) = 0;
844 virtual bool Pulse(pkgAcquire *Owner) {
845 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
853 _finline bool WasCancelled() const {
858 /* DelegateStatus {{{ */
863 _transient NSObject<ProgressDelegate> *delegate_;
871 void setDelegate(NSObject<ProgressDelegate> *delegate) {
872 delegate_ = delegate;
875 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
876 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
877 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
878 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
881 virtual void Done(pkgAcquire::ItemDesc &desc) {
882 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
883 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
884 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
887 virtual void Fail(pkgAcquire::ItemDesc &desc) {
889 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
890 desc.Owner->Status == pkgAcquire::Item::StatDone
894 std::string &error(desc.Owner->ErrorText);
898 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
899 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
902 virtual bool Pulse_(pkgAcquire *Owner) {
904 double(CurrentBytes + CurrentItems) /
905 double(TotalBytes + TotalItems)
908 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
909 [NSNumber numberWithDouble:percent], @"Percent",
911 [NSNumber numberWithDouble:CurrentBytes], @"Current",
912 [NSNumber numberWithDouble:TotalBytes], @"Total",
913 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
914 nil] waitUntilDone:YES];
916 return ![delegate_ isProgressCancelled];
919 virtual void Start() {
920 pkgAcquireStatus::Start();
921 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
924 virtual void Stop() {
925 pkgAcquireStatus::Stop();
926 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
927 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
931 /* Database Interface {{{ */
932 typedef std::map< unsigned long, _H<Source> > SourceMap;
934 @interface Database : NSObject {
942 pkgDepCache::Policy *policy_;
943 pkgRecords *records_;
944 pkgProblemResolver *resolver_;
945 pkgAcquire *fetcher_;
947 SPtr<pkgPackageManager> manager_;
948 pkgSourceList *list_;
950 SourceMap sourceMap_;
951 _H<NSMutableArray> sourceList_;
953 _H<NSArray> packages_;
955 _transient NSObject<DatabaseDelegate> *delegate_;
956 _transient NSObject<ProgressDelegate> *progress_;
964 std::map<const char *, _H<NSString> > sections_;
967 + (Database *) sharedInstance;
969 - (bool) hasPackages;
971 - (void) _readCydia:(NSNumber *)fd;
972 - (void) _readStatus:(NSNumber *)fd;
973 - (void) _readOutput:(NSNumber *)fd;
977 - (Package *) packageWithName:(NSString *)name;
979 - (pkgCacheFile &) cache;
980 - (pkgDepCache::Policy *) policy;
981 - (pkgRecords *) records;
982 - (pkgProblemResolver *) resolver;
983 - (pkgAcquire &) fetcher;
984 - (pkgSourceList &) list;
985 - (NSArray *) packages;
986 - (NSArray *) sources;
987 - (Source *) sourceWithKey:(NSString *)key;
988 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
996 - (void) updateWithStatus:(CancelStatus &)status;
998 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1000 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1001 - (NSObject<ProgressDelegate> *) progressDelegate;
1003 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1004 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1005 - (void) resetFetch;
1007 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1011 /* SourceStatus {{{ */
1012 class SourceStatus :
1016 _transient NSObject<FetchDelegate> *delegate_;
1017 _transient Database *database_;
1018 std::set<std::string> fetches_;
1021 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1022 delegate_(delegate),
1027 void Set(bool fetch, const std::string &uri) {
1029 if (!fetches_.insert(uri).second)
1032 if (fetches_.erase(uri) == 0)
1036 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1038 auto slash(uri.rfind('/'));
1039 if (slash != std::string::npos)
1040 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1043 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1044 /*unsigned long ID(fetch ? 1 : 0);
1048 Set(fetch, item->DescURI());
1051 void Log(const char *tag, pkgAcquire::Item *item) {
1052 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1055 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1056 Log("Fetch", desc.Owner);
1057 Set(true, desc.Owner);
1060 virtual void Done(pkgAcquire::ItemDesc &desc) {
1061 Log("Done", desc.Owner);
1062 Set(false, desc.Owner);
1065 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1066 Log("Fail", desc.Owner);
1067 Set(false, desc.Owner);
1070 virtual bool Pulse_(pkgAcquire *Owner) {
1071 std::set<std::string> fetches;
1072 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1074 if ((*item)->QueueCounter == 0)
1076 else switch ((*item)->Status) {
1077 case pkgAcquire::Item::StatFetching:
1078 fetches.insert((*item)->DescURI());
1087 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1091 std::vector<std::string> stops;
1092 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1093 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1094 //printf("Stop(%s)\n", stop->c_str());
1098 return ![delegate_ isSourceCancelled];
1101 virtual void Stop() {
1102 pkgAcquireStatus::Stop();
1103 [database_ resetFetch];
1107 /* ProgressEvent Implementation {{{ */
1108 @implementation CydiaProgressEvent
1110 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1111 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1114 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1115 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1116 [event setPackage:package];
1120 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1121 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1123 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1124 NSArray *fields([description componentsSeparatedByString:@" "]);
1125 [event setItem:fields];
1127 if ([fields count] > 3) {
1128 [event setPackage:[fields objectAtIndex:2]];
1129 [event setVersion:[fields objectAtIndex:3]];
1132 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1137 + (NSArray *) _attributeKeys {
1138 return [NSArray arrayWithObjects:
1148 - (NSArray *) attributeKeys {
1149 return [[self class] _attributeKeys];
1152 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1153 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1156 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1157 if ((self = [super init]) != nil) {
1163 - (NSString *) message {
1167 - (NSString *) type {
1171 - (NSArray *) item {
1172 return (id) item_ ?: [NSNull null];
1175 - (void) setItem:(NSArray *)item {
1179 - (NSString *) package {
1180 return (id) package_ ?: [NSNull null];
1183 - (void) setPackage:(NSString *)package {
1187 - (NSString *) url {
1188 return (id) url_ ?: [NSNull null];
1191 - (void) setURL:(NSString *)url {
1195 - (void) setVersion:(NSString *)version {
1199 - (NSString *) version {
1200 return (id) version_ ?: [NSNull null];
1203 - (NSString *) compound:(NSString *)value {
1205 NSString *mode(nil); {
1206 NSString *type([self type]);
1207 if ([type isEqualToString:kCydiaProgressEventTypeError])
1208 mode = UCLocalize("ERROR");
1209 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1210 mode = UCLocalize("WARNING");
1214 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1220 - (NSString *) compoundMessage {
1221 return [self compound:[self message]];
1224 - (NSString *) compoundTitle {
1227 if (package_ == nil)
1229 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1230 title = [package name];
1234 return [self compound:title];
1240 // Cytore Definitions {{{
1241 struct PackageValue :
1244 Cytore::Offset<PackageValue> next_;
1246 uint32_t index_ : 23;
1247 uint32_t subscribed_ : 1;
1264 Cytore::Offset<PackageValue> packages_[1 << 16];
1267 static Cytore::File<MetaValue> MetaFile_;
1269 // Cytore Helper Functions {{{
1270 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1271 SplitHash nhash = { hashlittle(name, length) };
1273 PackageValue *metadata;
1275 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1276 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1277 *offset = MetaFile_.New<PackageValue>(length + 1);
1278 metadata = &MetaFile_.Get(*offset);
1280 if (metadata == NULL) {
1284 metadata = new PackageValue();
1285 memset(metadata, 0, sizeof(*metadata));
1288 memcpy(metadata->name_, name, length);
1289 metadata->name_[length] = '\0';
1290 metadata->nhash_ = nhash.u16[1];
1292 metadata = &MetaFile_.Get(*offset);
1293 if (metadata->nhash_ != nhash.u16[1])
1295 if (strncmp(metadata->name_, name, length) != 0)
1297 if (metadata->name_[length] != '\0')
1304 static void PackageImport(const void *key, const void *value, void *context) {
1305 bool &fail(*reinterpret_cast<bool *>(context));
1308 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1309 NSLog(@"failed to import package %@", key);
1313 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1314 NSDictionary *package((NSDictionary *) value);
1316 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1317 if ([subscribed boolValue] && !metadata->subscribed_)
1318 metadata->subscribed_ = true;
1320 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1321 time_t time([date timeIntervalSince1970]);
1322 if (metadata->first_ > time || metadata->first_ == 0)
1323 metadata->first_ = time;
1326 NSDate *date([package objectForKey:@"LastSeen"]);
1327 NSString *version([package objectForKey:@"LastVersion"]);
1329 if (date != nil && version != nil) {
1330 time_t time([date timeIntervalSince1970]);
1331 if (metadata->last_ < time || metadata->last_ == 0)
1332 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1333 size_t length(strlen(buffer));
1334 uint16_t vhash(hashlittle(buffer, length));
1336 size_t capped(std::min<size_t>(8, length));
1337 char *latest(buffer + length - capped);
1339 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1340 metadata->vhash_ = vhash;
1342 metadata->last_ = time;
1348 static NSDate *GetStatusDate() {
1349 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1352 static void SaveConfig(NSObject *lock) {
1353 @synchronized (lock) {
1359 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1360 Values_, @"CydiaValues",
1361 Sections_, @"CydiaSections",
1362 (id) Sources_, @"CydiaSources",
1363 Version_, @"CydiaVersion",
1364 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1366 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1367 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1369 CydiaWriteSources();
1372 /* Source Class {{{ */
1373 @interface Source : NSObject {
1375 Database *database_;
1378 CYString depiction_;
1379 CYString description_;
1385 CYString distribution_;
1391 _H<NSString> authority_;
1393 CYString defaultIcon_;
1395 _H<NSMutableDictionary> record_;
1398 std::set<std::string> fetches_;
1399 std::set<std::string> files_;
1400 _transient NSObject<SourceDelegate> *delegate_;
1403 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1405 - (NSComparisonResult) compareByName:(Source *)source;
1407 - (NSString *) depictionForPackage:(NSString *)package;
1408 - (NSString *) supportForPackage:(NSString *)package;
1410 - (metaIndex *) metaIndex;
1411 - (NSDictionary *) record;
1414 - (NSString *) rooturi;
1415 - (NSString *) distribution;
1416 - (NSString *) type;
1419 - (NSString *) host;
1421 - (NSString *) name;
1422 - (NSString *) shortDescription;
1423 - (NSString *) label;
1424 - (NSString *) origin;
1425 - (NSString *) version;
1427 - (NSString *) defaultIcon;
1428 - (NSURL *) iconURL;
1430 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1431 - (void) resetFetch;
1435 @implementation Source
1437 + (NSString *) webScriptNameForSelector:(SEL)selector {
1439 else if (selector == @selector(addSection:))
1440 return @"addSection";
1441 else if (selector == @selector(getField:))
1443 else if (selector == @selector(removeSection:))
1444 return @"removeSection";
1445 else if (selector == @selector(remove))
1451 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1452 return [self webScriptNameForSelector:selector] == nil;
1455 + (NSArray *) _attributeKeys {
1456 return [NSArray arrayWithObjects:
1467 @"shortDescription",
1474 - (NSArray *) attributeKeys {
1475 return [[self class] _attributeKeys];
1478 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1479 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1482 - (metaIndex *) metaIndex {
1486 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1487 trusted_ = index->IsTrusted();
1489 uri_.set(pool, index->GetURI());
1490 distribution_.set(pool, index->GetDist());
1491 type_.set(pool, index->GetType());
1493 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1494 if (dindex != NULL) {
1495 std::string file(dindex->MetaIndexURI(""));
1496 base_.set(pool, file);
1499 _profile(Source$setMetaIndex$GetIndexes)
1500 dindex->GetIndexes(&acquire, true);
1502 _profile(Source$setMetaIndex$DescURI)
1503 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1504 std::string file((*item)->DescURI());
1505 auto slash(file.rfind('/'));
1506 if (slash == std::string::npos)
1508 files_.insert(file.substr(0, slash));
1513 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1516 pkgTagFile tags(&fd);
1518 pkgTagSection section;
1525 {"default-icon", &defaultIcon_},
1526 {"depiction", &depiction_},
1527 {"description", &description_},
1529 {"origin", &origin_},
1530 {"support", &support_},
1531 {"version", &version_},
1534 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1535 const char *start, *end;
1537 if (section.Find(names[i].name_, start, end)) {
1538 CYString &value(*names[i].value_);
1539 value.set(pool, start, end - start);
1545 record_ = [Sources_ objectForKey:[self key]];
1547 NSURL *url([NSURL URLWithString:uri_]);
1551 host_ = [host_ lowercaseString];
1556 authority_ = [url path];
1559 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1560 if ((self = [super init]) != nil) {
1561 era_ = [database era];
1562 database_ = database;
1565 _profile(Source$initWithMetaIndex$setMetaIndex)
1566 [self setMetaIndex:index inPool:pool];
1571 - (NSString *) getField:(NSString *)name {
1572 @synchronized (database_) {
1573 if ([database_ era] != era_ || index_ == NULL)
1576 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1581 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1586 pkgTagFile tags(&fd);
1588 pkgTagSection section;
1591 const char *start, *end;
1592 if (!section.Find([name UTF8String], start, end))
1593 return (NSString *) [NSNull null];
1595 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1598 - (NSComparisonResult) compareByName:(Source *)source {
1599 NSString *lhs = [self name];
1600 NSString *rhs = [source name];
1602 if ([lhs length] != 0 && [rhs length] != 0) {
1603 unichar lhc = [lhs characterAtIndex:0];
1604 unichar rhc = [rhs characterAtIndex:0];
1606 if (isalpha(lhc) && !isalpha(rhc))
1607 return NSOrderedAscending;
1608 else if (!isalpha(lhc) && isalpha(rhc))
1609 return NSOrderedDescending;
1612 return [lhs compare:rhs options:LaxCompareOptions_];
1615 - (NSString *) depictionForPackage:(NSString *)package {
1616 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1619 - (NSString *) supportForPackage:(NSString *)package {
1620 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1623 - (NSArray *) sections {
1624 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1627 - (void) _addSection:(NSString *)section {
1630 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1631 if (![sections containsObject:section])
1632 [sections addObject:section];
1634 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1637 - (bool) addSection:(NSString *)section {
1641 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1645 - (void) _removeSection:(NSString *)section {
1649 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1650 if ([sections containsObject:section])
1651 [sections removeObject:section];
1654 - (bool) removeSection:(NSString *)section {
1658 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1663 [Sources_ removeObjectForKey:[self key]];
1667 bool value(record_ != nil);
1668 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1672 - (NSDictionary *) record {
1680 - (NSString *) rooturi {
1684 - (NSString *) distribution {
1685 return distribution_;
1688 - (NSString *) type {
1692 - (NSString *) baseuri {
1693 return base_.empty() ? nil : (id) base_;
1696 - (NSString *) iconuri {
1697 if (NSString *base = [self baseuri])
1698 return [base stringByAppendingString:@"CydiaIcon.png"];
1703 - (NSURL *) iconURL {
1704 if (NSString *uri = [self iconuri])
1705 return [NSURL URLWithString:uri];
1709 - (NSString *) key {
1710 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1713 - (NSString *) host {
1717 - (NSString *) name {
1718 return origin_.empty() ? (id) authority_ : origin_;
1721 - (NSString *) shortDescription {
1722 return description_;
1725 - (NSString *) label {
1726 return label_.empty() ? (id) authority_ : label_;
1729 - (NSString *) origin {
1733 - (NSString *) version {
1737 - (NSString *) defaultIcon {
1738 return defaultIcon_;
1741 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1742 delegate_ = delegate;
1746 return !fetches_.empty();
1749 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1751 if (fetches_.erase(uri) == 0)
1753 } else if (files_.find(uri) == files_.end())
1755 else if (!fetches_.insert(uri).second)
1758 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1761 - (void) resetFetch {
1763 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1768 /* CydiaOperation Class {{{ */
1769 @interface CydiaOperation : NSObject {
1770 _H<NSString> operator_;
1771 _H<NSString> value_;
1774 - (NSString *) operator;
1775 - (NSString *) value;
1779 @implementation CydiaOperation
1781 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1782 if ((self = [super init]) != nil) {
1783 operator_ = [NSString stringWithUTF8String:_operator];
1784 value_ = [NSString stringWithUTF8String:value];
1788 + (NSArray *) _attributeKeys {
1789 return [NSArray arrayWithObjects:
1795 - (NSArray *) attributeKeys {
1796 return [[self class] _attributeKeys];
1799 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1800 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1803 - (NSString *) operator {
1807 - (NSString *) value {
1813 /* CydiaClause Class {{{ */
1814 @interface CydiaClause : NSObject {
1815 _H<NSString> package_;
1816 _H<CydiaOperation> version_;
1819 - (NSString *) package;
1820 - (CydiaOperation *) version;
1824 @implementation CydiaClause
1826 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1827 if ((self = [super init]) != nil) {
1828 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1830 if (const char *version = dep.TargetVer())
1831 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1833 version_ = (id) [NSNull null];
1837 + (NSArray *) _attributeKeys {
1838 return [NSArray arrayWithObjects:
1844 - (NSArray *) attributeKeys {
1845 return [[self class] _attributeKeys];
1848 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1849 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1852 - (NSString *) package {
1856 - (CydiaOperation *) version {
1862 /* CydiaRelation Class {{{ */
1863 @interface CydiaRelation : NSObject {
1864 _H<NSString> relationship_;
1865 _H<NSMutableArray> clauses_;
1868 - (NSString *) relationship;
1869 - (NSArray *) clauses;
1873 @implementation CydiaRelation
1875 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1876 if ((self = [super init]) != nil) {
1877 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1878 clauses_ = [NSMutableArray arrayWithCapacity:8];
1880 pkgCache::DepIterator start;
1881 pkgCache::DepIterator end;
1882 dep.GlobOr(start, end); // ++dep
1885 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1887 // yes, seriously. (wtf?)
1895 + (NSArray *) _attributeKeys {
1896 return [NSArray arrayWithObjects:
1902 - (NSArray *) attributeKeys {
1903 return [[self class] _attributeKeys];
1906 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1907 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1910 - (NSString *) relationship {
1911 return relationship_;
1914 - (NSArray *) clauses {
1918 - (void) addClause:(CydiaClause *)clause {
1919 [clauses_ addObject:clause];
1924 /* Package Class {{{ */
1925 struct ParsedPackage {
1929 CYString architecture_;
1932 CYString depiction_;
1939 @interface Package : NSObject {
1941 @public uint32_t role_ : 3;
1942 uint32_t essential_ : 1;
1943 uint32_t obsolete_ : 1;
1944 uint32_t ignored_ : 1;
1945 uint32_t pooled_ : 1;
1951 _transient Database *database_;
1953 pkgCache::VerIterator version_;
1954 pkgCache::PkgIterator iterator_;
1955 pkgCache::VerFileIterator file_;
1959 CYString transform_;
1962 CYString installed_;
1965 const char *section_;
1966 _transient NSString *section$_;
1970 PackageValue *metadata_;
1971 ParsedPackage *parsed_;
1973 _H<NSMutableArray> tags_;
1976 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1977 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1979 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
1981 - (pkgCache::PkgIterator) iterator;
1984 - (NSString *) section;
1985 - (NSString *) simpleSection;
1987 - (NSString *) longSection;
1988 - (NSString *) shortSection;
1992 - (MIMEAddress *) maintainer;
1994 - (NSString *) longDescription;
1995 - (NSString *) shortDescription;
1998 - (PackageValue *) metadata;
2001 - (bool) subscribed;
2002 - (bool) setSubscribed:(bool)subscribed;
2006 - (NSString *) latest;
2007 - (NSString *) installed;
2008 - (BOOL) uninstalled;
2010 - (BOOL) upgradableAndEssential:(BOOL)essential;
2013 - (BOOL) unfiltered;
2017 - (BOOL) halfConfigured;
2018 - (BOOL) halfInstalled;
2020 - (NSString *) mode;
2023 - (NSString *) name;
2025 - (NSString *) homepage;
2026 - (NSString *) depiction;
2027 - (MIMEAddress *) author;
2029 - (NSString *) support;
2031 - (NSArray *) files;
2032 - (NSArray *) warnings;
2033 - (NSArray *) applications;
2035 - (Source *) source;
2038 - (BOOL) matches:(NSArray *)query;
2040 - (BOOL) hasTag:(NSString *)tag;
2041 - (NSString *) primaryPurpose;
2042 - (NSArray *) purposes;
2043 - (bool) isCommercial;
2045 - (void) setIndex:(size_t)index;
2047 - (CYString &) cyname;
2049 - (uint32_t) compareBySection:(NSArray *)sections;
2056 uint32_t PackageChangesRadix(Package *self, void *) {
2061 uint32_t timestamp : 30;
2062 uint32_t ignored : 1;
2063 uint32_t upgradable : 1;
2067 bool upgradable([self upgradableAndEssential:YES]);
2068 value.bits.upgradable = upgradable ? 1 : 0;
2071 value.bits.timestamp = 0;
2072 value.bits.ignored = [self ignored] ? 0 : 1;
2073 value.bits.upgradable = 1;
2075 value.bits.timestamp = [self seen] >> 2;
2076 value.bits.ignored = 0;
2077 value.bits.upgradable = 0;
2080 return _not(uint32_t) - value.key;
2083 CYString &(*PackageName)(Package *self, SEL sel);
2085 uint32_t PackagePrefixRadix(Package *self, void *context) {
2086 size_t offset(reinterpret_cast<size_t>(context));
2087 CYString &name(PackageName(self, @selector(cyname)));
2089 size_t size(name.size());
2092 char *text(name.data());
2095 if (!isdigit(text[0]))
2099 while (size != digits && isdigit(text[digits]))
2107 if (offset == 0 && zeros != 0) {
2108 memset(data, '0', zeros);
2109 memcpy(data + zeros, text, 4 - zeros);
2111 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2112 if (size <= offset - zeros)
2115 text += offset - zeros;
2116 size -= offset - zeros;
2119 memcpy(data, text, 4);
2121 memcpy(data, text, size);
2122 memset(data + size, 0, 4 - size);
2125 for (size_t i(0); i != 4; ++i)
2126 if (isalpha(data[i]))
2134 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2136 /* XXX: ntohl may be more honest */
2137 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2140 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2141 _profile(PackageNameCompare)
2143 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2144 else if (rhn == NULL)
2145 return kCFCompareGreaterThan;
2147 CFIndex length(CFStringGetLength(lhn));
2149 _profile(PackageNameCompare$NumbersLast)
2150 if (length != 0 && CFStringGetLength(rhn) != 0) {
2151 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2152 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2153 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2154 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2155 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2159 _profile(PackageNameCompare$Compare)
2160 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2165 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2166 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2169 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2170 CYString &lhn(PackageName(lhs, @selector(cyname)));
2171 NSString *rhn(PackageName(rhs, @selector(cyname)));
2172 return StringNameCompare(lhn, rhn, lhn.size());
2175 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2176 return PackageNameCompare(*lhs, *rhs, arg);
2179 struct PackageNameOrdering :
2180 std::binary_function<Package *, Package *, bool>
2182 _finline bool operator ()(Package *lhs, Package *rhs) const {
2183 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2187 @implementation Package
2189 - (NSString *) description {
2190 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2196 if (parsed_ != NULL)
2201 + (NSString *) webScriptNameForSelector:(SEL)selector {
2203 else if (selector == @selector(clear))
2205 else if (selector == @selector(getField:))
2207 else if (selector == @selector(getRecord))
2208 return @"getRecord";
2209 else if (selector == @selector(hasTag:))
2211 else if (selector == @selector(install))
2213 else if (selector == @selector(remove))
2219 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2220 return [self webScriptNameForSelector:selector] == nil;
2223 + (NSArray *) _attributeKeys {
2224 return [NSArray arrayWithObjects:
2245 @"shortDescription",
2258 - (NSArray *) attributeKeys {
2259 return [[self class] _attributeKeys];
2262 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2263 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2266 - (NSArray *) relations {
2267 @synchronized (database_) {
2268 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2269 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2270 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2274 - (NSString *) architecture {
2276 @synchronized (database_) {
2277 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2280 - (NSString *) getField:(NSString *)name {
2281 @synchronized (database_) {
2282 if ([database_ era] != era_ || file_.end())
2285 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2287 const char *start, *end;
2288 if (!parser.Find([name UTF8String], start, end))
2289 return (NSString *) [NSNull null];
2291 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2294 - (NSString *) getRecord {
2295 @synchronized (database_) {
2296 if ([database_ era] != era_ || file_.end())
2299 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2301 const char *start, *end;
2302 parser.GetRec(start, end);
2304 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2308 if (parsed_ != NULL)
2310 @synchronized (database_) {
2311 if ([database_ era] != era_ || file_.end())
2314 ParsedPackage *parsed(new ParsedPackage);
2317 _profile(Package$parse)
2318 pkgRecords::Parser *parser;
2320 _profile(Package$parse$Lookup)
2321 parser = &[database_ records]->Lookup(file_);
2327 _profile(Package$parse$Find)
2332 {"architecture", &parsed->architecture_},
2333 {"icon", &parsed->icon_},
2334 {"depiction", &parsed->depiction_},
2335 {"homepage", &parsed->homepage_},
2336 {"website", &website},
2338 {"support", &parsed->support_},
2339 {"author", &parsed->author_},
2340 {"md5sum", &parsed->md5sum_},
2343 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2344 const char *start, *end;
2346 if (parser->Find(names[i].name_, start, end)) {
2347 CYString &value(*names[i].value_);
2348 _profile(Package$parse$Value)
2349 value.set(pool_, start, end - start);
2355 _profile(Package$parse$Tagline)
2356 parsed->tagline_.set(pool_, parser->ShortDesc());
2359 _profile(Package$parse$Retain)
2360 if (parsed->homepage_.empty())
2361 parsed->homepage_ = website;
2362 if (parsed->homepage_ == parsed->depiction_)
2363 parsed->homepage_.clear();
2364 if (parsed->support_.empty())
2365 parsed->support_ = bugs;
2370 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2371 if ((self = [super init]) != nil) {
2372 _profile(Package$initWithVersion)
2374 pool_ = new CYPool();
2380 database_ = database;
2381 era_ = [database era];
2385 pkgCache::PkgIterator iterator(version_.ParentPkg());
2386 iterator_ = iterator;
2388 _profile(Package$initWithVersion$Version)
2389 file_ = version_.FileList();
2392 _profile(Package$initWithVersion$Cache)
2393 name_.set(NULL, version_.Display());
2395 latest_.set(NULL, StripVersion_(version_.VerStr()));
2397 pkgCache::VerIterator current(iterator.CurrentVer());
2399 installed_.set(NULL, StripVersion_(current.VerStr()));
2402 _profile(Package$initWithVersion$Transliterate) do {
2403 if (CollationTransl_ == NULL)
2408 _profile(Package$initWithVersion$Transliterate$utf8)
2409 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2410 for (size_t i(0), e(name_.size()); i != e; ++i)
2411 if (data[i] >= 0x80)
2416 UErrorCode code(U_ZERO_ERROR);
2419 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2420 CollationString_.resize(name_.size());
2421 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2422 if (!U_SUCCESS(code))
2424 CollationString_.resize(length);
2427 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2428 length = CollationString_.size();
2429 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2430 if (!U_SUCCESS(code))
2432 _assert(CollationString_.size() == length);
2435 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2436 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2437 if (code == U_BUFFER_OVERFLOW_ERROR)
2438 code = U_ZERO_ERROR;
2439 else if (!U_SUCCESS(code))
2444 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2445 transform = pool_->malloc<char>(length);
2447 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2448 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2449 if (!U_SUCCESS(code))
2453 transform_.set(NULL, transform, length);
2454 } while (false); _end
2456 _profile(Package$initWithVersion$Tags)
2458 pkgCache::TagIterator tag(version_.TagList());
2460 pkgCache::TagIterator tag(iterator.TagList());
2463 tags_ = [NSMutableArray arrayWithCapacity:8];
2465 goto tag; for (; !tag.end(); ++tag) tag: {
2466 const char *name(tag.Name());
2467 NSString *string((NSString *) CYStringCreate(name));
2471 [tags_ addObject:[string autorelease]];
2473 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2474 if (strcmp(name + 6, "enduser") == 0)
2476 else if (strcmp(name + 6, "hacker") == 0)
2478 else if (strcmp(name + 6, "developer") == 0)
2480 else if (strcmp(name + 6, "cydia") == 0)
2486 if (strncmp(name, "cydia::", 7) == 0) {
2487 if (strcmp(name + 7, "essential") == 0)
2489 else if (strcmp(name + 7, "obsolete") == 0)
2496 _profile(Package$initWithVersion$Metadata)
2497 const char *mixed(iterator.Name());
2498 size_t size(strlen(mixed));
2499 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2500 char lower[prefix + size + 5 + 1];
2502 for (size_t i(0); i != size; ++i)
2503 lower[prefix + i] = mixed[i] | 0x20;
2505 if (!installed_.empty()) {
2506 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2507 memcpy(lower + prefix + size, ".list", 6);
2509 if (stat(lower, &info) != -1)
2510 upgraded_ = info.st_birthtime;
2513 PackageValue *metadata(PackageFind(lower + prefix, size));
2514 metadata_ = metadata;
2516 id_.set(NULL, metadata->name_, size);
2518 const char *latest(version_.VerStr());
2519 size_t length(strlen(latest));
2521 uint16_t vhash(hashlittle(latest, length));
2523 size_t capped(std::min<size_t>(8, length));
2524 latest = latest + length - capped;
2526 if (metadata->first_ == 0)
2527 metadata->first_ = now_;
2529 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2530 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2531 metadata->vhash_ = vhash;
2532 metadata->last_ = now_;
2533 } else if (metadata->last_ == 0)
2534 metadata->last_ = metadata->first_;
2537 _profile(Package$initWithVersion$Section)
2538 section_ = version_.Section();
2541 _profile(Package$initWithVersion$Flags)
2542 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2543 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2548 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2549 pkgCache::VerIterator version;
2551 _profile(Package$packageWithIterator$GetCandidateVer)
2552 version = [database policy]->GetCandidateVer(iterator);
2560 _profile(Package$packageWithIterator$Allocate)
2561 package = [Package allocWithZone:zone];
2564 _profile(Package$packageWithIterator$Initialize)
2566 initWithVersion:version
2576 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2577 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2578 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2581 - (pkgCache::PkgIterator) iterator {
2585 - (NSArray *) downgrades {
2586 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2588 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2589 if (version == version_)
2591 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2592 if ([package source] == nil)
2594 [versions addObject:package];
2600 - (NSString *) section {
2601 if (section$_ == nil) {
2602 if (section_ == NULL)
2605 _profile(Package$section$mappedSectionForPointer)
2606 section$_ = [database_ mappedSectionForPointer:section_];
2611 - (NSString *) simpleSection {
2612 if (NSString *section = [self section])
2613 return Simplify(section);
2618 - (NSString *) longSection {
2619 if (NSString *section = [self section])
2620 return LocalizeSection(section);
2625 - (NSString *) shortSection {
2626 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2629 - (NSString *) uri {
2632 pkgIndexFile *index;
2633 pkgCache::PkgFileIterator file(file_.File());
2634 if (![database_ list].FindIndex(file, index))
2636 return [NSString stringWithUTF8String:iterator_->Path];
2637 //return [NSString stringWithUTF8String:file.Site()];
2638 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2642 - (MIMEAddress *) maintainer {
2643 @synchronized (database_) {
2644 if ([database_ era] != era_ || file_.end())
2647 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2648 const std::string &maintainer(parser->Maintainer());
2649 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2652 - (NSString *) md5sum {
2653 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2657 @synchronized (database_) {
2658 if ([database_ era] != era_ || version_.end())
2661 return version_->InstalledSize;
2664 - (NSString *) longDescription {
2665 @synchronized (database_) {
2666 if ([database_ era] != era_ || file_.end())
2669 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2670 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2672 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2673 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2674 if ([lines count] < 2)
2677 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2678 for (size_t i(1), e([lines count]); i != e; ++i) {
2679 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2680 [trimmed addObject:trim];
2683 return [trimmed componentsJoinedByString:@"\n"];
2686 - (NSString *) shortDescription {
2687 if (parsed_ != NULL)
2688 return static_cast<NSString *>(parsed_->tagline_);
2690 @synchronized (database_) {
2691 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2692 std::string value(parser.ShortDesc());
2695 if (value.size() > 200)
2697 return [(id) CYStringCreate(value) autorelease];
2701 _profile(Package$index)
2702 CFStringRef name((CFStringRef) [self name]);
2703 if (CFStringGetLength(name) == 0)
2705 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2706 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2708 return toupper(character);
2712 - (PackageValue *) metadata {
2717 PackageValue *metadata([self metadata]);
2718 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2721 - (bool) subscribed {
2722 return [self metadata]->subscribed_;
2725 - (bool) setSubscribed:(bool)subscribed {
2726 PackageValue *metadata([self metadata]);
2727 if (metadata->subscribed_ == subscribed)
2729 metadata->subscribed_ = subscribed;
2737 - (NSString *) latest {
2741 - (NSString *) installed {
2745 - (BOOL) uninstalled {
2746 return installed_.empty();
2749 - (BOOL) upgradableAndEssential:(BOOL)essential {
2750 _profile(Package$upgradableAndEssential)
2751 pkgCache::VerIterator current(iterator_.CurrentVer());
2753 return essential && essential_;
2755 return version_ != current;
2759 - (BOOL) essential {
2764 return [database_ cache][iterator_].InstBroken();
2767 - (BOOL) unfiltered {
2768 _profile(Package$unfiltered$obsolete)
2769 if (_unlikely(obsolete_))
2773 _profile(Package$unfiltered$role)
2774 if (_unlikely(role_ > 3))
2782 if (![self unfiltered])
2787 _profile(Package$visible$section)
2788 section = [self section];
2791 _profile(Package$visible$isSectionVisible)
2792 if (!isSectionVisible(section))
2800 unsigned char current(iterator_->CurrentState);
2801 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2804 - (BOOL) halfConfigured {
2805 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2808 - (BOOL) halfInstalled {
2809 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2813 @synchronized (database_) {
2814 if ([database_ era] != era_ || iterator_.end())
2817 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2818 return state.Mode != pkgDepCache::ModeKeep;
2821 - (NSString *) mode {
2822 @synchronized (database_) {
2823 if ([database_ era] != era_ || iterator_.end())
2826 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2828 switch (state.Mode) {
2829 case pkgDepCache::ModeDelete:
2830 if ((state.iFlags & pkgDepCache::Purge) != 0)
2834 case pkgDepCache::ModeKeep:
2835 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2836 return @"REINSTALL";
2837 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2841 case pkgDepCache::ModeInstall:
2842 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2843 return @"REINSTALL";
2844 else*/ switch (state.Status) {
2846 return @"DOWNGRADE";
2852 return @"NEW_INSTALL";
2863 - (NSString *) name {
2864 return name_.empty() ? id_ : name_;
2867 - (UIImage *) icon {
2868 NSString *section = [self simpleSection];
2871 if (parsed_ != NULL)
2872 if (NSString *href = parsed_->icon_)
2873 if ([href hasPrefix:@"file:///"])
2874 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2875 if (icon == nil) if (section != nil)
2876 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2877 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2878 if ([dicon hasPrefix:@"file:///"])
2879 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2881 icon = [UIImage imageNamed:@"unknown.png"];
2885 - (NSString *) homepage {
2886 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2889 - (NSString *) depiction {
2890 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2893 - (MIMEAddress *) author {
2894 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2897 - (NSString *) support {
2898 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2901 - (NSArray *) files {
2902 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2903 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2906 fin.open([path UTF8String]);
2911 while (std::getline(fin, line))
2912 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2917 - (NSString *) state {
2918 @synchronized (database_) {
2919 if ([database_ era] != era_ || file_.end())
2922 switch (iterator_->CurrentState) {
2923 case pkgCache::State::NotInstalled:
2924 return @"NotInstalled";
2925 case pkgCache::State::UnPacked:
2927 case pkgCache::State::HalfConfigured:
2928 return @"HalfConfigured";
2929 case pkgCache::State::HalfInstalled:
2930 return @"HalfInstalled";
2931 case pkgCache::State::ConfigFiles:
2932 return @"ConfigFiles";
2933 case pkgCache::State::Installed:
2934 return @"Installed";
2935 case pkgCache::State::TriggersAwaited:
2936 return @"TriggersAwaited";
2937 case pkgCache::State::TriggersPending:
2938 return @"TriggersPending";
2941 return (NSString *) [NSNull null];
2944 - (NSString *) selection {
2945 @synchronized (database_) {
2946 if ([database_ era] != era_ || file_.end())
2949 switch (iterator_->SelectedState) {
2950 case pkgCache::State::Unknown:
2952 case pkgCache::State::Install:
2954 case pkgCache::State::Hold:
2956 case pkgCache::State::DeInstall:
2957 return @"DeInstall";
2958 case pkgCache::State::Purge:
2962 return (NSString *) [NSNull null];
2965 - (NSArray *) warnings {
2966 @synchronized (database_) {
2967 if ([database_ era] != era_ || file_.end())
2970 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2971 const char *name(iterator_.Name());
2973 size_t length(strlen(name));
2974 if (length < 2) invalid:
2975 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2976 else for (size_t i(0); i != length; ++i)
2978 /* XXX: technically this is not allowed */
2979 (name[i] < 'A' || name[i] > 'Z') &&
2980 (name[i] < 'a' || name[i] > 'z') &&
2981 (name[i] < '0' || name[i] > '9') &&
2982 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2985 if (strcmp(name, "cydia") != 0) {
2988 bool _private = false;
2990 bool dbstash = false;
2991 bool dsstore = false;
2993 bool repository = [[self section] isEqualToString:@"Repositories"];
2995 if (NSArray *files = [self files])
2996 for (NSString *file in files)
2997 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2999 else if (!user && [file isEqualToString:@"/User"])
3001 else if (!_private && [file isEqualToString:@"/private"])
3003 else if (!stash && [file isEqualToString:@"/var/stash"])
3005 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3007 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3010 /* XXX: this is not sensitive enough. only some folders are valid. */
3011 if (cydia && !repository)
3012 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3014 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3016 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3018 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3020 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3022 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3025 return [warnings count] == 0 ? nil : warnings;
3028 - (NSArray *) applications {
3029 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3031 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3033 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3034 if (NSArray *files = [self files])
3035 for (NSString *file in files)
3036 if (application_r(file)) {
3037 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3040 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3041 if (id == nil || [id isEqualToString:me])
3044 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3046 display = application_r[1];
3048 NSString *bundle([file stringByDeletingLastPathComponent]);
3049 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3050 // XXX: maybe this should check if this is really a string, not just for length
3051 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3053 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3055 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3056 [applications addObject:application];
3058 [application addObject:id];
3059 [application addObject:display];
3060 [application addObject:url];
3063 return [applications count] == 0 ? nil : applications;
3066 - (Source *) source {
3067 if (source_ == nil) {
3068 @synchronized (database_) {
3069 if ([database_ era] != era_ || file_.end())
3070 source_ = (Source *) [NSNull null];
3072 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3076 return source_ == (Source *) [NSNull null] ? nil : source_;
3079 - (time_t) upgraded {
3083 - (uint32_t) recent {
3084 return std::numeric_limits<uint32_t>::max() - upgraded_;
3091 - (BOOL) matches:(NSArray *)query {
3092 if (query == nil || [query count] == 0)
3101 string = [self name];
3102 length = [string length];
3105 for (NSString *term in query) {
3106 range = [string rangeOfString:term options:MatchCompareOptions_];
3107 if (range.location != NSNotFound)
3108 rank_ -= 6 * 1000000 / length;
3113 length = [string length];
3116 for (NSString *term in query) {
3117 range = [string rangeOfString:term options:MatchCompareOptions_];
3118 if (range.location != NSNotFound)
3119 rank_ -= 6 * 1000000 / length;
3123 string = [self shortDescription];
3124 length = [string length];
3125 NSUInteger stop(std::min<NSUInteger>(length, 200));
3128 for (NSString *term in query) {
3129 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3130 if (range.location != NSNotFound)
3131 rank_ -= 2 * 100000;
3137 - (NSArray *) tags {
3141 - (BOOL) hasTag:(NSString *)tag {
3142 return tags_ == nil ? NO : [tags_ containsObject:tag];
3145 - (NSString *) primaryPurpose {
3146 for (NSString *tag in (NSArray *) tags_)
3147 if ([tag hasPrefix:@"purpose::"])
3148 return [tag substringFromIndex:9];
3152 - (NSArray *) purposes {
3153 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3154 for (NSString *tag in (NSArray *) tags_)
3155 if ([tag hasPrefix:@"purpose::"])
3156 [purposes addObject:[tag substringFromIndex:9]];
3157 return [purposes count] == 0 ? nil : purposes;
3160 - (bool) isCommercial {
3161 return [self hasTag:@"cydia::commercial"];
3164 - (void) setIndex:(size_t)index {
3165 if (metadata_->index_ != index + 1)
3166 metadata_->index_ = index + 1;
3169 - (CYString &) cyname {
3170 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3173 - (uint32_t) compareBySection:(NSArray *)sections {
3174 NSString *section([self section]);
3175 for (size_t i(0), e([sections count]); i != e; ++i) {
3176 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3180 return _not(uint32_t);
3184 @synchronized (database_) {
3185 if ([database_ era] != era_ || file_.end())
3188 pkgProblemResolver *resolver = [database_ resolver];
3189 resolver->Clear(iterator_);
3191 pkgCacheFile &cache([database_ cache]);
3192 cache->SetReInstall(iterator_, false);
3193 cache->MarkKeep(iterator_, false);
3197 @synchronized (database_) {
3198 if ([database_ era] != era_ || file_.end())
3201 pkgProblemResolver *resolver = [database_ resolver];
3202 resolver->Clear(iterator_);
3203 resolver->Protect(iterator_);
3205 pkgCacheFile &cache([database_ cache]);
3206 cache->SetCandidateVersion(version_);
3207 cache->SetReInstall(iterator_, false);
3208 cache->MarkInstall(iterator_, false);
3210 pkgDepCache::StateCache &state((*cache)[iterator_]);
3211 if (!state.Install())
3212 cache->SetReInstall(iterator_, true);
3216 @synchronized (database_) {
3217 if ([database_ era] != era_ || file_.end())
3220 pkgProblemResolver *resolver = [database_ resolver];
3221 resolver->Clear(iterator_);
3222 resolver->Remove(iterator_);
3223 resolver->Protect(iterator_);
3225 pkgCacheFile &cache([database_ cache]);
3226 cache->SetReInstall(iterator_, false);
3227 cache->MarkDelete(iterator_, true);
3232 /* Section Class {{{ */
3233 @interface Section : NSObject {
3237 _H<NSString> localized_;
3240 - (NSComparisonResult) compareByLocalized:(Section *)section;
3241 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3242 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3243 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3245 - (NSString *) name;
3246 - (void) setName:(NSString *)name;
3252 - (void) addToCount;
3254 - (void) setCount:(size_t)count;
3255 - (NSString *) localized;
3259 @implementation Section
3261 - (NSComparisonResult) compareByLocalized:(Section *)section {
3262 NSString *lhs(localized_);
3263 NSString *rhs([section localized]);
3265 /*if ([lhs length] != 0 && [rhs length] != 0) {
3266 unichar lhc = [lhs characterAtIndex:0];
3267 unichar rhc = [rhs characterAtIndex:0];
3269 if (isalpha(lhc) && !isalpha(rhc))
3270 return NSOrderedAscending;
3271 else if (!isalpha(lhc) && isalpha(rhc))
3272 return NSOrderedDescending;
3275 return [lhs compare:rhs options:LaxCompareOptions_];
3278 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3279 if ((self = [self initWithName:name localize:NO]) != nil) {
3280 if (localized != nil)
3281 localized_ = localized;
3285 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3286 return [self initWithName:name row:0 localize:localize];
3289 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3290 if ((self = [super init]) != nil) {
3294 localized_ = LocalizeSection(name_);
3298 - (NSString *) name {
3302 - (void) setName:(NSString *)name {
3318 - (void) addToCount {
3322 - (void) setCount:(size_t)count {
3326 - (NSString *) localized {
3333 class CydiaLogCleaner :
3334 public pkgArchiveCleaner
3337 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3342 /* Database Implementation {{{ */
3343 @implementation Database
3345 + (Database *) sharedInstance {
3346 static _H<Database> instance;
3347 if (instance == nil)
3348 instance = [[[Database alloc] init] autorelease];
3356 - (void) releasePackages {
3360 - (bool) hasPackages {
3361 return [packages_ count] != 0;
3365 // XXX: actually implement this thing
3367 [self releasePackages];
3368 NSRecycleZone(zone_);
3372 - (void) _readCydia:(NSNumber *)fd {
3373 boost::fdistream is([fd intValue]);
3376 static RegEx finish_r("finish:([^:]*)");
3378 while (std::getline(is, line)) {
3379 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3381 const char *data(line.c_str());
3382 size_t size = line.size();
3383 lprintf("C:%s\n", data);
3385 if (finish_r(data, size)) {
3386 NSString *finish = finish_r[1];
3387 int index = [Finishes_ indexOfObject:finish];
3388 if (index != INT_MAX && index > Finish_)
3398 - (void) _readStatus:(NSNumber *)fd {
3399 boost::fdistream is([fd intValue]);
3402 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3403 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3405 while (std::getline(is, line)) {
3406 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3408 const char *data(line.c_str());
3409 size_t size(line.size());
3410 lprintf("S:%s\n", data);
3412 if (conffile_r(data, size)) {
3413 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3414 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3415 } else if (strncmp(data, "status: ", 8) == 0) {
3416 // status: <package>: {unpacked,half-configured,installed}
3417 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3418 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3419 } else if (strncmp(data, "processing: ", 12) == 0) {
3420 // processing: configure: config-test
3421 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3422 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3423 } else if (pmstatus_r(data, size)) {
3424 std::string type([pmstatus_r[1] UTF8String]);
3426 NSString *package = pmstatus_r[2];
3427 if ([package isEqualToString:@"dpkg-exec"])
3430 float percent([pmstatus_r[3] floatValue]);
3431 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3433 NSString *string = pmstatus_r[4];
3435 if (type == "pmerror") {
3436 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3437 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3438 } else if (type == "pmstatus") {
3439 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3440 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3441 } else if (type == "pmconffile")
3442 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3444 lprintf("E:unknown pmstatus\n");
3446 lprintf("E:unknown status\n");
3454 - (void) _readOutput:(NSNumber *)fd {
3455 boost::fdistream is([fd intValue]);
3458 while (std::getline(is, line)) {
3459 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3461 lprintf("O:%s\n", line.c_str());
3463 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3464 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3476 - (Package *) packageWithName:(NSString *)name {
3479 @synchronized (self) {
3480 if (static_cast<pkgDepCache *>(cache_) == NULL)
3482 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3487 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3491 if ((self = [super init]) != nil) {
3498 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3500 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3504 _assert(pipe(fds) != -1);
3507 _config->Set("APT::Keep-Fds::", cydiafd_);
3508 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3511 detachNewThreadSelector:@selector(_readCydia:)
3513 withObject:[NSNumber numberWithInt:fds[0]]
3516 _assert(pipe(fds) != -1);
3520 detachNewThreadSelector:@selector(_readStatus:)
3522 withObject:[NSNumber numberWithInt:fds[0]]
3525 _assert(pipe(fds) != -1);
3526 _assert(dup2(fds[0], 0) != -1);
3527 _assert(close(fds[0]) != -1);
3529 input_ = fdopen(fds[1], "a");
3531 _assert(pipe(fds) != -1);
3532 _assert(dup2(fds[1], 1) != -1);
3533 _assert(close(fds[1]) != -1);
3536 detachNewThreadSelector:@selector(_readOutput:)
3538 withObject:[NSNumber numberWithInt:fds[0]]
3543 - (pkgCacheFile &) cache {
3547 - (pkgDepCache::Policy *) policy {
3551 - (pkgRecords *) records {
3555 - (pkgProblemResolver *) resolver {
3559 - (pkgAcquire &) fetcher {
3563 - (pkgSourceList &) list {
3567 - (NSArray *) packages {
3571 - (NSArray *) sources {
3575 - (Source *) sourceWithKey:(NSString *)key {
3576 for (Source *source in [self sources]) {
3577 if ([[source key] isEqualToString:key])
3582 - (bool) popErrorWithTitle:(NSString *)title {
3585 while (!_error->empty()) {
3587 bool warning(!_error->PopMessage(error));
3592 size_t size(error.size());
3593 if (size == 0 || error[size - 1] != '\n')
3595 error.resize(size - 1);
3598 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3600 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3601 if (warning && no_pubkey(error.c_str()))
3604 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3610 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3611 return [self popErrorWithTitle:title] || !success;
3614 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3615 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3623 if (access("/etc/apt/sources.list", F_OK) == 0)
3624 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3626 std::string base("/etc/apt/sources.list.d");
3627 if (DIR *sources = opendir(base.c_str())) {
3628 while (dirent *source = readdir(sources))
3629 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)
3630 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3634 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3639 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3640 @synchronized (self) {
3643 [self releasePackages];
3646 [sourceList_ removeAllObjects];
3667 new (&pool_) CYPool();
3669 NSRecycleZone(zone_);
3670 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3672 int chk(creat("/tmp/cydia.chk", 0644));
3676 if (invocation != nil)
3677 [invocation invoke];
3679 NSString *title(UCLocalize("DATABASE"));
3681 list_ = new pkgSourceList();
3682 _profile(reloadDataWithInvocation$ReadMainList)
3683 if ([self popErrorWithTitle:title forReadList:*list_])
3687 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3688 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3689 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3690 [sourceList_ addObject:object];
3695 OpProgress progress;
3698 delock_ = GetStatusDate();
3699 _profile(reloadDataWithInvocation$pkgCacheFile)
3700 opened = cache_.Open(progress, false);
3703 // XXX: this block should probably be merged with popError: in some way
3704 while (!_error->empty()) {
3706 bool warning(!_error->PopMessage(error));
3708 lprintf("cache_.Open():[%s]\n", error.c_str());
3710 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3714 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3715 repair = @selector(configure);
3716 //else if (error == "The package lists or status file could not be parsed or opened.")
3717 // repair = @selector(update);
3718 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3719 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3720 // else if (error == "Malformed Status line")
3721 // else if (error == "The list of sources could not be read.")
3723 if (repair != NULL) {
3725 [delegate_ repairWithSelector:repair];
3731 } else if ([self popErrorWithTitle:title forOperation:true])
3735 unlink("/tmp/cydia.chk");
3737 now_ = [[NSDate date] timeIntervalSince1970];
3739 policy_ = new pkgDepCache::Policy();
3740 records_ = new pkgRecords(cache_);
3741 resolver_ = new pkgProblemResolver(cache_);
3742 fetcher_ = new pkgAcquire(&status_);
3745 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3746 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3750 _profile(reloadDataWithInvocation$pkgApplyStatus)
3751 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3755 if (cache_->BrokenCount() != 0) {
3756 _profile(pkgApplyStatus$pkgFixBroken)
3757 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3761 if (cache_->BrokenCount() != 0) {
3762 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3766 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3767 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3772 for (Source *object in (id) sourceList_) {
3773 metaIndex *source([object metaIndex]);
3774 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3775 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3776 // XXX: this could be more intelligent
3777 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3778 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3780 sourceMap_[cached->ID] = object;
3785 size_t capacity(MetaFile_->active_);
3787 capacity = 128*1024;
3791 std::vector<Package *> packages;
3792 packages.reserve(capacity);
3796 _profile(reloadDataWithInvocation$packageWithIterator)
3797 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3798 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3799 if (unsigned index = package.metadata->index_) {
3801 if (packages.size() == index) {
3802 packages.push_back(package);
3803 } else if (packages.size() <= index) {
3804 packages.resize(index + 1, nil);
3805 packages[index] = package;
3808 std::swap(package, packages[index]);
3809 if (package != nil) {
3810 if (package.metadata->index_ == index + 1)
3819 lost: if (last == packages.size())
3820 packages.push_back(package);
3822 packages[last] = package;
3826 for (; last != packages.size(); ++last)
3827 if (packages[last] == nil)
3832 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3834 if (next == packages.size())
3836 if (packages[next] != nil)
3841 std::swap(packages[last], packages[next]);
3844 packages.resize(last);
3847 NSLog(@"lost = %zu", lost);
3849 _profile(reloadDataWithInvocation$radix$8)
3850 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3853 _profile(reloadDataWithInvocation$radix$4)
3854 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3857 _profile(reloadDataWithInvocation$radix$0)
3858 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3862 _profile(reloadDataWithInvocation$insertion)
3863 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3866 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3868 /*_profile(reloadDataWithInvocation$CFQSortArray)
3869 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3872 /*_profile(reloadDataWithInvocation$stdsort)
3873 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3876 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3877 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3880 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3881 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3884 MetaFile_->active_ = packages.size();
3885 for (size_t index(0), count(packages.size()); index != count; ++index) {
3886 auto package(packages[index]);
3887 [package setIndex:index];
3894 @synchronized (self) {
3896 resolver_ = new pkgProblemResolver(cache_);
3898 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3899 if (!cache_[iterator].Keep())
3900 cache_->MarkKeep(iterator, false);
3901 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3902 cache_->SetReInstall(iterator, false);
3905 - (void) configure {
3906 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3908 system([dpkg UTF8String]);
3913 @synchronized (self) {
3914 // XXX: I don't remember this condition
3919 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3921 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3923 if ([self popErrorWithTitle:title])
3927 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3929 CydiaLogCleaner cleaner;
3930 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3937 fetcher_->Shutdown();
3939 pkgRecords records(cache_);
3941 lock_ = new FileFd();
3942 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3944 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3946 if ([self popErrorWithTitle:title])
3950 if ([self popErrorWithTitle:title forReadList:list])
3953 manager_ = (_system->CreatePM(cache_));
3954 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3961 bool substrate(RestartSubstrate_);
3962 RestartSubstrate_ = false;
3964 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3966 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3968 if ([self popErrorWithTitle:title forReadList:list])
3970 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3971 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3974 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3976 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3978 [self popErrorWithTitle:title];
3982 bool failed = false;
3983 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3984 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3986 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3989 std::string uri = (*item)->DescURI();
3990 std::string error = (*item)->ErrorText;
3992 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3995 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3996 [delegate_ addProgressEventOnMainThread:event forTask:title];
3999 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4007 RestartSubstrate_ = true;
4009 if (![delock_ isEqual:GetStatusDate()]) {
4010 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4016 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4018 NSString *oextended(@"/var/lib/apt/extended_states");
4019 NSString *nextended(Cache("extended_states"));
4022 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4023 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4025 unlink([nextended UTF8String]);
4026 symlink([oextended UTF8String], [nextended UTF8String]);
4028 if ([self popErrorWithTitle:title])
4031 if (result == pkgPackageManager::Failed) {
4036 if (result != pkgPackageManager::Completed) {
4041 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4043 if ([self popErrorWithTitle:title forReadList:list])
4045 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4046 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4049 if (![before isEqualToArray:after])
4054 return ![delock_ isEqual:GetStatusDate()];
4058 NSString *title(UCLocalize("UPGRADE"));
4059 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4065 [self updateWithStatus:status_];
4068 - (void) updateWithStatus:(CancelStatus &)status {
4069 NSString *title(UCLocalize("REFRESHING_DATA"));
4072 if ([self popErrorWithTitle:title forReadList:list])
4076 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4077 if ([self popErrorWithTitle:title])
4080 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4082 bool success(ListUpdate(status, list, PulseInterval_));
4083 if (status.WasCancelled())
4086 [self popErrorWithTitle:title forOperation:success];
4088 [[NSDictionary dictionaryWithObjectsAndKeys:
4089 [NSDate date], @"LastUpdate",
4090 nil] writeToFile:@ CacheState_ atomically:YES];
4093 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4096 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4097 delegate_ = delegate;
4100 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4101 progress_ = delegate;
4102 status_.setDelegate(delegate);
4105 - (NSObject<ProgressDelegate> *) progressDelegate {
4109 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4110 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4111 return i == sourceMap_.end() ? nil : i->second;
4114 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4115 for (Source *source in (id) sourceList_)
4116 [source setFetch:fetch forURI:uri];
4119 - (void) resetFetch {
4120 for (Source *source in (id) sourceList_)
4121 [source resetFetch];
4124 - (NSString *) mappedSectionForPointer:(const char *)section {
4125 _H<NSString> *mapped;
4127 _profile(Database$mappedSectionForPointer$Cache)
4128 mapped = §ions_[section];
4131 if (*mapped == NULL) {
4132 size_t length(strlen(section));
4133 char spaced[length + 1];
4135 _profile(Database$mappedSectionForPointer$Replace)
4136 for (size_t index(0); index != length; ++index)
4137 spaced[index] = section[index] == '_' ? ' ' : section[index];
4138 spaced[length] = '\0';
4143 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4144 string = [NSString stringWithUTF8String:spaced];
4147 _profile(Database$mappedSectionForPointer$Map)
4148 string = [SectionMap_ objectForKey:string] ?: string;
4158 @interface CydiaObject : CyteObject {
4159 _transient id delegate_;
4164 @interface CydiaWebViewController : CyteWebViewController {
4165 _H<CydiaObject> cydia_;
4168 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4169 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4170 - (void) setDelegate:(id)delegate;
4174 /* Web Scripting {{{ */
4175 @implementation CydiaObject
4177 - (void) setDelegate:(id)delegate {
4178 delegate_ = delegate;
4181 - (NSArray *) attributeKeys {
4182 return [[NSArray arrayWithObjects:
4190 nil] arrayByAddingObjectsFromArray:[super attributeKeys]];
4193 - (NSString *) version {
4197 - (NSString *) device {
4198 return UniqueIdentifier();
4201 - (NSArray *) cells {
4202 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4203 if ($_CTServerConnectionCreate == NULL)
4206 struct CTResult { int flag; int error; };
4207 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4208 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4211 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4212 if (connection == nil)
4216 CFArrayRef cells(NULL);
4217 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4218 if (result.flag != 0)
4221 return [(NSArray *) cells autorelease];
4224 - (NSString *) mcc {
4225 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4226 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4230 - (NSString *) mnc {
4231 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4232 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4236 - (NSString *) operator {
4237 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4238 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4242 - (NSString *) role {
4243 return (id) [NSNull null];
4246 + (NSString *) webScriptNameForSelector:(SEL)selector {
4248 else if (selector == @selector(addBridgedHost:))
4249 return @"addBridgedHost";
4250 else if (selector == @selector(addInsecureHost:))
4251 return @"addInsecureHost";
4252 else if (selector == @selector(addSource:::))
4253 return @"addSource";
4254 else if (selector == @selector(addTrivialSource:))
4255 return @"addTrivialSource";
4256 else if (selector == @selector(du:))
4258 else if (selector == @selector(getAllSources))
4259 return @"getAllSources";
4260 else if (selector == @selector(getApplicationInfo:value:))
4261 return @"getApplicationInfoValue";
4262 else if (selector == @selector(getDisplayIdentifiers))
4263 return @"getDisplayIdentifiers";
4264 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4265 return @"getLocalizedNameForDisplayIdentifier";
4266 else if (selector == @selector(getInstalledPackages))
4267 return @"getInstalledPackages";
4268 else if (selector == @selector(getPackageById:))
4269 return @"getPackageById";
4270 else if (selector == @selector(getMetadataKeys))
4271 return @"getMetadataKeys";
4272 else if (selector == @selector(getMetadataValue:))
4273 return @"getMetadataValue";
4274 else if (selector == @selector(getSessionValue:))
4275 return @"getSessionValue";
4276 else if (selector == @selector(installPackages:))
4277 return @"installPackages";
4278 else if (selector == @selector(refreshSources))
4279 return @"refreshSources";
4280 else if (selector == @selector(saveConfig))
4281 return @"saveConfig";
4282 else if (selector == @selector(setMetadataValue::))
4283 return @"setMetadataValue";
4284 else if (selector == @selector(setSessionValue::))
4285 return @"setSessionValue";
4286 else if (selector == @selector(substitutePackageNames:))
4287 return @"substitutePackageNames";
4288 else if (selector == @selector(setToken:))
4294 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4295 return [self webScriptNameForSelector:selector] == nil;
4298 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4300 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4301 return (id) [NSNull null];
4302 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4304 return (id) [NSNull null];
4305 return [info objectForKey:key];
4308 - (NSArray *) getDisplayIdentifiers {
4309 return SBSCopyApplicationDisplayIdentifiers(false, false);
4312 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4313 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4316 - (NSNumber *) getKernelNumber:(NSString *)name {
4317 const char *string([name UTF8String]);
4320 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4321 return (id) [NSNull null];
4323 if (size != sizeof(int))
4324 return (id) [NSNull null];
4327 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4328 return (id) [NSNull null];
4330 return [NSNumber numberWithInt:value];
4333 - (NSArray *) getMetadataKeys {
4334 @synchronized (Values_) {
4335 return [Values_ allKeys];
4338 - (id) getMetadataValue:(NSString *)key {
4339 @synchronized (Values_) {
4340 return [Values_ objectForKey:key];
4343 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4344 @synchronized (Values_) {
4345 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4346 [Values_ removeObjectForKey:key];
4348 [Values_ setObject:value forKey:key];
4351 - (id) getSessionValue:(NSString *)key {
4352 @synchronized (SessionData_) {
4353 return [SessionData_ objectForKey:key];
4356 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4357 @synchronized (SessionData_) {
4358 if (value == (id) [WebUndefined undefined])
4359 [SessionData_ removeObjectForKey:key];
4361 [SessionData_ setObject:value forKey:key];
4364 - (void) addBridgedHost:(NSString *)host {
4365 @synchronized (BridgedHosts_) {
4366 [BridgedHosts_ addObject:host];
4369 - (void) addInsecureHost:(NSString *)host {
4370 @synchronized (InsecureHosts_) {
4371 [InsecureHosts_ addObject:host];
4374 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4375 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4377 for (NSString *section in sections)
4378 [array addObject:section];
4380 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4383 distribution, @"Distribution",
4385 nil] waitUntilDone:NO];
4388 - (BOOL) addTrivialSource:(NSString *)href {
4389 href = VerifySource(href);
4392 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4396 - (void) refreshSources {
4397 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4400 - (void) saveConfig {
4401 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4404 - (NSArray *) getAllSources {
4405 return [[Database sharedInstance] sources];
4408 - (NSArray *) getInstalledPackages {
4409 Database *database([Database sharedInstance]);
4410 @synchronized (database) {
4411 NSArray *packages([database packages]);
4412 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4413 for (Package *package in packages)
4414 if (![package uninstalled])
4415 [installed addObject:package];
4419 - (Package *) getPackageById:(NSString *)id {
4420 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4424 return (Package *) [NSNull null];
4427 - (NSNumber *) du:(NSString *)path {
4428 NSNumber *value(nil);
4430 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4433 while (fgets(line, sizeof(line), du) != NULL) {
4434 size_t length(strlen(line));
4435 while (length != 0 && line[length - 1] == '\n')
4436 line[--length] = '\0';
4437 if (char *tab = strchr(line, '\t')) {
4439 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4448 - (void) installPackages:(NSArray *)packages {
4449 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4452 - (NSString *) substitutePackageNames:(NSString *)message {
4453 auto database([Database sharedInstance]);
4455 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4456 if (![database hasPackages])
4459 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4460 for (size_t i(0), e([words count]); i != e; ++i) {
4461 NSString *word([words objectAtIndex:i]);
4462 if (Package *package = [database packageWithName:word])
4463 [words replaceObjectAtIndex:i withObject:[package name]];
4466 return [words componentsJoinedByString:@" "];
4469 - (void) setToken:(NSString *)token {
4470 // XXX: the website expects this :/
4476 @interface NSURL (CydiaSecure)
4479 @implementation NSURL (CydiaSecure)
4481 - (bool) isCydiaSecure {
4482 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4485 @synchronized (InsecureHosts_) {
4486 if ([InsecureHosts_ containsObject:[self host]])
4495 /* Cydia Browser Controller {{{ */
4496 @implementation CydiaWebViewController
4498 - (NSURL *) navigationURL {
4499 if (NSURLRequest *request = self.request)
4500 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4505 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4506 [super webView:view didClearWindowObject:window forFrame:frame];
4507 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4510 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4511 WebDataSource *source([frame dataSource]);
4512 NSURLResponse *response([source response]);
4513 NSURL *url([response URL]);
4514 NSString *scheme([[url scheme] lowercaseString]);
4516 bool bridged(false);
4518 @synchronized (BridgedHosts_) {
4519 if ([scheme isEqualToString:@"file"])
4521 else if ([scheme isEqualToString:@"https"])
4522 if ([BridgedHosts_ containsObject:[url host]])
4527 [window setValue:cydia forKey:@"cydia"];
4530 - (void) _setupMail:(MFMailComposeViewController *)controller {
4531 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4533 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4534 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4537 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4538 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4541 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4542 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4545 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4546 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4548 NSURL *url([copy URL]);
4549 NSString *href([url absoluteString]);
4550 NSString *host([url host]);
4552 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4553 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4554 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4555 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4558 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4559 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4561 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4565 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4566 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4567 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4568 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4570 bool bridged; @synchronized (BridgedHosts_) {
4571 bridged = [BridgedHosts_ containsObject:host];
4574 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4575 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4580 - (void) setDelegate:(id)delegate {
4581 [super setDelegate:delegate];
4582 [cydia_ setDelegate:delegate];
4586 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4587 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
4593 @interface AppCacheController : CydiaWebViewController {
4598 @implementation AppCacheController
4600 - (void) didReceiveMemoryWarning {
4601 // XXX: this doesn't work
4604 - (bool) retainsNetworkActivityIndicator {
4611 /* Confirmation Controller {{{ */
4612 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4613 if (!iterator.end())
4614 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4615 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4617 pkgCache::PkgIterator package(dep.TargetPkg());
4620 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4627 @protocol ConfirmationControllerDelegate
4628 - (void) cancelAndClear:(bool)clear;
4629 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4633 @interface ConfirmationController : CydiaWebViewController {
4634 _transient Database *database_;
4636 _H<UIAlertView> essential_;
4638 _H<NSDictionary> changes_;
4639 _H<NSMutableArray> issues_;
4640 _H<NSDictionary> sizes_;
4645 - (id) initWithDatabase:(Database *)database;
4649 @implementation ConfirmationController
4653 RestartSubstrate_ = true;
4654 [self.delegate confirmWithNavigationController:[self navigationController]];
4657 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4658 NSString *context([alert context]);
4660 if ([context isEqualToString:@"remove"]) {
4661 if (button == [alert cancelButtonIndex])
4663 else if (button == [alert firstOtherButtonIndex]) {
4664 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4667 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4668 } else if ([context isEqualToString:@"unable"]) {
4669 [self dismissModalViewControllerAnimated:YES];
4670 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4672 [super alertView:alert clickedButtonAtIndex:button];
4676 - (void) _doContinue {
4677 [self.delegate cancelAndClear:NO];
4678 [self dismissModalViewControllerAnimated:YES];
4681 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4682 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4686 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4687 [super webView:view didClearWindowObject:window forFrame:frame];
4689 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4690 (id) changes_, @"changes",
4691 (id) issues_, @"issues",
4692 (id) sizes_, @"sizes",
4694 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4697 - (id) initWithDatabase:(Database *)database {
4698 if ((self = [super init]) != nil) {
4699 database_ = database;
4701 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4702 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4703 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4704 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4705 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4709 pkgCacheFile &cache([database_ cache]);
4710 NSArray *packages([database_ packages]);
4711 pkgDepCache::Policy *policy([database_ policy]);
4713 issues_ = [NSMutableArray arrayWithCapacity:4];
4715 for (Package *package in packages) {
4716 pkgCache::PkgIterator iterator([package iterator]);
4717 NSString *name([package id]);
4719 if ([package broken]) {
4720 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4722 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4724 reasons, @"reasons",
4727 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4731 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4732 pkgCache::DepIterator start;
4733 pkgCache::DepIterator end;
4734 dep.GlobOr(start, end); // ++dep
4736 if (!cache->IsImportantDep(end))
4738 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4741 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4743 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4744 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4745 clauses, @"clauses",
4749 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4751 pkgCache::PkgIterator target(start.TargetPkg());
4752 if (target->ProvidesList != 0)
4753 reason = @"missing";
4755 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4757 reason = @"installed";
4758 installed = [NSString stringWithUTF8String:ver.VerStr()];
4759 } else if (!cache[target].CandidateVerIter(cache).end())
4760 reason = @"uninstalled";
4761 else if (target->ProvidesList == 0)
4762 reason = @"uninstallable";
4764 reason = @"virtual";
4767 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4768 [NSString stringWithUTF8String:start.CompType()], @"operator",
4769 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4772 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4773 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4774 version, @"version",
4776 installed, @"installed",
4779 // yes, seriously. (wtf?)
4787 pkgDepCache::StateCache &state(cache[iterator]);
4789 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
4791 if (state.NewInstall())
4792 [installs addObject:name];
4793 // XXX: else if (state.Install())
4794 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4795 [reinstalls addObject:name];
4796 // XXX: move before previous if
4797 else if (state.Upgrade())
4798 [upgrades addObject:name];
4799 else if (state.Downgrade())
4800 [downgrades addObject:name];
4801 else if (!state.Delete())
4802 // XXX: _assert(state.Keep());
4804 else if (special_r(name))
4805 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4806 [NSNull null], @"package",
4807 [NSArray arrayWithObjects:
4808 [NSDictionary dictionaryWithObjectsAndKeys:
4809 @"Conflicts", @"relationship",
4810 [NSArray arrayWithObjects:
4811 [NSDictionary dictionaryWithObjectsAndKeys:
4813 [NSNull null], @"version",
4814 @"installed", @"reason",
4821 if ([package essential])
4823 [removes addObject:name];
4826 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4827 substrate_ |= DepSubstrate(iterator.CurrentVer());
4832 else if (Advanced_) {
4833 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4835 essential_ = [[[UIAlertView alloc]
4836 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4837 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4839 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4841 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4845 [essential_ setContext:@"remove"];
4846 [essential_ setNumberOfRows:2];
4848 essential_ = [[[UIAlertView alloc]
4849 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4850 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4852 cancelButtonTitle:UCLocalize("OKAY")
4853 otherButtonTitles:nil
4856 [essential_ setContext:@"unable"];
4859 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4860 installs, @"installs",
4861 reinstalls, @"reinstalls",
4862 upgrades, @"upgrades",
4863 downgrades, @"downgrades",
4864 removes, @"removes",
4867 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4868 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4869 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4872 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4876 - (UIBarButtonItem *) leftButton {
4877 return [[[UIBarButtonItem alloc]
4878 initWithTitle:UCLocalize("CANCEL")
4879 style:UIBarButtonItemStylePlain
4881 action:@selector(cancelButtonClicked)
4886 - (void) applyRightButton {
4887 if ([issues_ count] == 0 && ![self isLoading])
4888 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4889 initWithTitle:UCLocalize("CONFIRM")
4890 style:UIBarButtonItemStyleDone
4892 action:@selector(confirmButtonClicked)
4895 [[self navigationItem] setRightBarButtonItem:nil];
4899 - (void) cancelButtonClicked {
4900 [self.delegate cancelAndClear:YES];
4901 [self dismissModalViewControllerAnimated:YES];
4905 - (void) confirmButtonClicked {
4906 if (essential_ != nil)
4916 /* Progress Data {{{ */
4917 @interface CydiaProgressData : NSObject {
4918 _transient id delegate_;
4927 _H<NSMutableArray> events_;
4928 _H<NSString> title_;
4930 _H<NSString> status_;
4931 _H<NSString> finish_;
4936 @implementation CydiaProgressData
4938 + (NSArray *) _attributeKeys {
4939 return [NSArray arrayWithObjects:
4951 - (NSArray *) attributeKeys {
4952 return [[self class] _attributeKeys];
4955 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4956 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4960 if ((self = [super init]) != nil) {
4961 events_ = [NSMutableArray arrayWithCapacity:32];
4969 - (void) setDelegate:(id)delegate {
4970 delegate_ = delegate;
4973 - (void) setPercent:(float)value {
4977 - (NSNumber *) percent {
4978 return [NSNumber numberWithFloat:percent_];
4981 - (void) setCurrent:(float)value {
4985 - (NSNumber *) current {
4986 return [NSNumber numberWithFloat:current_];
4989 - (void) setTotal:(float)value {
4993 - (NSNumber *) total {
4994 return [NSNumber numberWithFloat:total_];
4997 - (void) setSpeed:(float)value {
5001 - (NSNumber *) speed {
5002 return [NSNumber numberWithFloat:speed_];
5005 - (NSArray *) events {
5009 - (void) removeAllEvents {
5010 [events_ removeAllObjects];
5013 - (void) addEvent:(CydiaProgressEvent *)event {
5014 [events_ addObject:event];
5017 - (void) setTitle:(NSString *)text {
5021 - (NSString *) title {
5025 - (void) setFinish:(NSString *)text {
5029 - (NSString *) finish {
5030 return (id) finish_ ?: [NSNull null];
5033 - (void) setRunning:(bool)running {
5037 - (NSNumber *) running {
5038 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5043 /* Progress Controller {{{ */
5044 @interface ProgressController : CydiaWebViewController <
5047 _transient Database *database_;
5048 _H<CydiaProgressData, 1> progress_;
5052 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5054 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5056 - (void) setTitle:(NSString *)title;
5057 - (void) setCancellable:(bool)cancellable;
5061 @implementation ProgressController
5064 [database_ setProgressDelegate:nil];
5068 - (UIBarButtonItem *) leftButton {
5069 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5070 initWithTitle:UCLocalize("CANCEL")
5071 style:UIBarButtonItemStylePlain
5073 action:@selector(cancel)
5074 ] autorelease] : nil;
5077 - (void) updateCancel {
5078 [super applyLeftButton];
5081 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5082 if ((self = [super init]) != nil) {
5083 database_ = database;
5084 self.delegate = delegate;
5086 [database_ setProgressDelegate:self];
5088 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5089 [progress_ setDelegate:self];
5091 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5093 [self setPageColor:[UIColor blackColor]];
5095 [[self navigationItem] setHidesBackButton:YES];
5097 [self updateCancel];
5101 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5102 [super webView:view didClearWindowObject:window forFrame:frame];
5103 [window setValue:progress_ forKey:@"cydiaProgress"];
5106 - (void) updateProgress {
5107 [self dispatchEvent:@"CydiaProgressUpdate"];
5110 - (void) viewWillAppear:(BOOL)animated {
5111 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5112 [super viewWillAppear:animated];
5116 UpdateExternalStatus(0);
5119 [self.delegate saveState];
5123 [self.delegate returnToCydia];
5127 [self.delegate terminateWithSuccess];
5128 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5129 [self.delegate suspendWithAnimation:YES];
5131 [self.delegate suspend];*/
5143 UIProgressHUD *hud([self.delegate addProgressHUD]);
5144 [hud setText:UCLocalize("LOADING")];
5145 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5151 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5152 SBReboot(SBSSpringBoardServerPort());
5154 reboot2(RB_AUTOBOOT);
5161 - (void) setTitle:(NSString *)title {
5162 [progress_ setTitle:title];
5163 [self updateProgress];
5166 - (UIBarButtonItem *) rightButton {
5167 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5168 initWithTitle:UCLocalize("CLOSE")
5169 style:UIBarButtonItemStylePlain
5171 action:@selector(close)
5175 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5176 UpdateExternalStatus(1);
5178 [progress_ setRunning:true];
5179 [self setTitle:title];
5180 // implicit updateProgress
5182 SHA1SumValue notifyconf; {
5184 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5187 MMap mmap(file, MMap::ReadOnly);
5189 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5190 notifyconf = sha1.Result();
5194 SHA1SumValue springlist; {
5196 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5199 MMap mmap(file, MMap::ReadOnly);
5201 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5202 springlist = sha1.Result();
5206 if (invocation != nil) {
5207 [invocation yieldToSelector:@selector(invoke)];
5208 [self setTitle:@"COMPLETE"];
5213 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5216 MMap mmap(file, MMap::ReadOnly);
5218 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5219 if (!(notifyconf == sha1.Result()))
5226 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5229 MMap mmap(file, MMap::ReadOnly);
5231 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5232 if (!(springlist == sha1.Result()))
5238 if (RestartSubstrate_)
5242 RestartSubstrate_ = false;
5245 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5246 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5247 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5248 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5249 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5252 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5254 [progress_ setRunning:false];
5255 [self updateProgress];
5257 [self applyRightButton];
5260 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5261 [progress_ addEvent:event];
5262 [self updateProgress];
5265 - (bool) isProgressCancelled {
5266 return cancel_ == 2;
5271 [self updateCancel];
5274 - (void) setCancellable:(bool)cancellable {
5275 unsigned cancel(cancel_);
5279 else if (cancel_ == 0)
5282 if (cancel != cancel_)
5283 [self updateCancel];
5286 - (void) setProgressCancellable:(NSNumber *)cancellable {
5287 [self setCancellable:[cancellable boolValue]];
5290 - (void) setProgressPercent:(NSNumber *)percent {
5291 [progress_ setPercent:[percent floatValue]];
5292 [self updateProgress];
5295 - (void) setProgressStatus:(NSDictionary *)status {
5296 if (status == nil) {
5297 [progress_ setCurrent:0];
5298 [progress_ setTotal:0];
5299 [progress_ setSpeed:0];
5301 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5303 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5304 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5305 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5308 [self updateProgress];
5314 /* Package Cell {{{ */
5315 @interface PackageCell : CyteTableViewCell <
5316 CyteTableViewCellDelegate
5320 _H<NSString> description_;
5322 _H<NSString> source_;
5324 _H<UIImage> placard_;
5328 - (PackageCell *) init;
5329 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5331 - (void) drawContentRect:(CGRect)rect;
5335 @implementation PackageCell
5337 - (PackageCell *) init {
5338 CGRect frame(CGRectMake(0, 0, 320, 74));
5339 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5340 UIView *content([self contentView]);
5341 CGRect bounds([content bounds]);
5343 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5344 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5345 [content addSubview:self.content];
5347 [self.content setDelegate:self];
5348 [self.content setOpaque:YES];
5352 - (NSString *) accessibilityLabel {
5356 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5357 summarized_ = summary;
5367 [self.content setBackgroundColor:[UIColor whiteColor]];
5371 Source *source = [package source];
5373 icon_ = [package icon];
5375 if (NSString *name = [package name])
5376 name_ = [NSString stringWithString:name];
5378 if (NSString *description = [package shortDescription])
5379 description_ = [NSString stringWithString:description];
5381 commercial_ = [package isCommercial];
5383 NSString *label = nil;
5384 bool trusted = false;
5386 if (source != nil) {
5387 label = [source label];
5388 trusted = [source trusted];
5389 } else if ([[package id] isEqualToString:@"firmware"])
5390 label = UCLocalize("APPLE");
5392 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5394 NSString *from(label);
5396 NSString *section = [package simpleSection];
5397 if (section != nil && ![section isEqualToString:label]) {
5398 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5399 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5402 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5404 if (NSString *purpose = [package primaryPurpose])
5405 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5410 if (NSString *mode = [package mode]) {
5411 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5412 color = RemovingColor_;
5413 placard = @"removing";
5415 color = InstallingColor_;
5416 placard = @"installing";
5419 color = [UIColor whiteColor];
5421 if ([package installed] != nil)
5422 placard = @"installed";
5427 [self.content setBackgroundColor:color];
5430 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5433 [self setNeedsDisplay];
5434 [self.content setNeedsDisplay];
5437 - (void) drawSummaryContentRect:(CGRect)rect {
5438 bool highlighted(self.highlighted);
5439 float width([self bounds].size.width);
5443 rect.size = [(UIImage *) icon_ size];
5445 while (rect.size.width > 16 || rect.size.height > 16) {
5446 rect.size.width /= 2;
5447 rect.size.height /= 2;
5450 rect.origin.x = 19 - rect.size.width / 2;
5451 rect.origin.y = 19 - rect.size.height / 2;
5453 [icon_ drawInRect:Retina(rect)];
5456 if (badge_ != nil) {
5458 rect.size = [(UIImage *) badge_ size];
5460 rect.size.width /= 4;
5461 rect.size.height /= 4;
5463 rect.origin.x = 25 - rect.size.width / 2;
5464 rect.origin.y = 25 - rect.size.height / 2;
5466 [badge_ drawInRect:Retina(rect)];
5469 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5473 UISetColor(commercial_ ? Purple_ : Black_);
5474 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5476 if (placard_ != nil)
5477 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5480 - (void) drawNormalContentRect:(CGRect)rect {
5481 bool highlighted(self.highlighted);
5482 float width([self bounds].size.width);
5486 rect.size = [(UIImage *) icon_ size];
5488 while (rect.size.width > 32 || rect.size.height > 32) {
5489 rect.size.width /= 2;
5490 rect.size.height /= 2;
5493 rect.origin.x = 25 - rect.size.width / 2;
5494 rect.origin.y = 25 - rect.size.height / 2;
5496 [icon_ drawInRect:Retina(rect)];
5499 if (badge_ != nil) {
5501 rect.size = [(UIImage *) badge_ size];
5503 rect.size.width /= 2;
5504 rect.size.height /= 2;
5506 rect.origin.x = 36 - rect.size.width / 2;
5507 rect.origin.y = 36 - rect.size.height / 2;
5509 [badge_ drawInRect:Retina(rect)];
5512 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5516 UISetColor(commercial_ ? Purple_ : Black_);
5517 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5518 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5521 UISetColor(commercial_ ? Purplish_ : Gray_);
5522 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5524 if (placard_ != nil)
5525 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5528 - (void) drawContentRect:(CGRect)rect {
5530 [self drawSummaryContentRect:rect];
5532 [self drawNormalContentRect:rect];
5537 /* Section Cell {{{ */
5538 @interface SectionCell : CyteTableViewCell <
5539 CyteTableViewCellDelegate
5541 _H<NSString> basic_;
5542 _H<NSString> section_;
5544 _H<NSString> count_;
5546 _H<UISwitch> switch_;
5550 - (void) setSection:(Section *)section editing:(BOOL)editing;
5554 @implementation SectionCell
5556 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5557 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5558 icon_ = [UIImage imageNamed:@"folder.png"];
5559 // XXX: this initial frame is wrong, but is fixed later
5560 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5561 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5563 UIView *content([self contentView]);
5564 CGRect bounds([content bounds]);
5566 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5567 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5568 [content addSubview:self.content];
5569 [self.content setBackgroundColor:[UIColor whiteColor]];
5571 [self.content setDelegate:self];
5575 - (void) onSwitch:(id)sender {
5576 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5577 if (metadata == nil) {
5578 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5579 [Sections_ setObject:metadata forKey:basic_];
5582 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5585 - (void) setSection:(Section *)section editing:(BOOL)editing {
5586 if (editing != editing_) {
5588 [switch_ removeFromSuperview];
5590 [self addSubview:switch_];
5599 if (section == nil) {
5600 name_ = UCLocalize("ALL_PACKAGES");
5603 basic_ = [section name];
5604 section_ = [section localized];
5606 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5607 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5610 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5613 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5614 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5616 [self.content setNeedsDisplay];
5619 - (void) setFrame:(CGRect)frame {
5620 [super setFrame:frame];
5622 CGRect rect([switch_ frame]);
5623 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5626 - (NSString *) accessibilityLabel {
5630 - (void) drawContentRect:(CGRect)rect {
5631 bool highlighted(self.highlighted && !editing_);
5633 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5635 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5638 float width(rect.size.width);
5640 width -= 9 + [switch_ frame].size.width;
5644 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
5646 CGSize size = [count_ sizeWithFont:Font14_];
5648 UISetColor(Folder_);
5650 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
5656 /* File Table {{{ */
5657 @interface FileTable : CyteListController <
5658 UITableViewDataSource,
5661 _transient Database *database_;
5662 _H<Package> package_;
5664 _H<NSMutableArray> files_;
5667 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5671 @implementation FileTable
5673 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5674 return files_ == nil ? 0 : [files_ count];
5677 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5681 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5682 static NSString *reuseIdentifier = @"Cell";
5684 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5686 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5687 [cell setFont:[UIFont systemFontOfSize:16]];
5689 [cell setText:[files_ objectAtIndex:indexPath.row]];
5690 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5695 - (NSURL *) navigationURL {
5696 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5699 - (CGFloat) rowHeight {
5703 - (void) releaseSubviews {
5707 [super releaseSubviews];
5710 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5711 if ((self = [super initWithTitle:UCLocalize("INSTALLED_FILES")]) != nil) {
5712 database_ = database;
5717 - (bool) shouldYield {
5721 - (void) _reloadData {
5724 package_ = [database_ packageWithName:name_];
5725 if (package_ != nil) {
5726 files_ = [NSMutableArray arrayWithCapacity:32];
5728 if (NSArray *files = [package_ files])
5729 [files_ addObjectsFromArray:files];
5731 if ([files_ count] != 0) {
5732 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5733 [files_ removeObjectAtIndex:0];
5734 [files_ sortUsingSelector:@selector(compareByPath:)];
5736 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5737 [stack addObject:@"/"];
5739 for (int i(0), e([files_ count]); i != e; ++i) {
5740 NSString *file = [files_ objectAtIndex:i];
5741 while (![file hasPrefix:[stack lastObject]])
5742 [stack removeLastObject];
5743 NSString *directory = [stack lastObject];
5744 [stack addObject:[file stringByAppendingString:@"/"]];
5745 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5746 int(([stack count] - 2) * 3), "",
5747 [file substringFromIndex:[directory length]]
5753 [super _reloadData];
5758 /* Package Controller {{{ */
5759 @interface CYPackageController : CydiaWebViewController <
5760 UIActionSheetDelegate
5762 _transient Database *database_;
5763 _H<Package> package_;
5766 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
5767 _H<UIActionSheet> sheet_;
5768 _H<UIBarButtonItem> button_;
5769 _H<NSArray> versions_;
5772 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5776 @implementation CYPackageController
5778 - (NSURL *) navigationURL {
5779 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5782 - (void) _clickButtonWithPackage:(Package *)package {
5783 [self.delegate installPackage:package];
5786 - (void) _clickButtonWithName:(NSString *)name {
5787 if ([name isEqualToString:@"CLEAR"])
5788 return [self.delegate clearPackage:package_];
5789 else if ([name isEqualToString:@"REMOVE"])
5790 return [self.delegate removePackage:package_];
5791 else if ([name isEqualToString:@"DOWNGRADE"]) {
5792 sheet_ = [[[UIActionSheet alloc]
5795 cancelButtonTitle:nil
5796 destructiveButtonTitle:nil
5797 otherButtonTitles:nil
5800 for (Package *version in (id) versions_)
5801 [sheet_ addButtonWithTitle:[version latest]];
5802 [sheet_ setContext:@"version"];
5804 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5808 else if ([name isEqualToString:@"INSTALL"]);
5809 else if ([name isEqualToString:@"REINSTALL"]);
5810 else if ([name isEqualToString:@"UPGRADE"]);
5811 else _assert(false);
5813 [self.delegate installPackage:package_];
5816 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5817 NSString *context([sheet context]);
5818 if (sheet_ == sheet)
5821 if ([context isEqualToString:@"modify"]) {
5822 if (button != [sheet cancelButtonIndex]) {
5824 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
5826 [self _clickButtonWithName:buttons_[button].first];
5829 [sheet dismissWithClickedButtonIndex:button animated:YES];
5830 } else if ([context isEqualToString:@"version"]) {
5831 if (button != [sheet cancelButtonIndex]) {
5832 Package *version([versions_ objectAtIndex:button]);
5834 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
5836 [self _clickButtonWithPackage:version];
5839 [sheet dismissWithClickedButtonIndex:button animated:YES];
5843 - (bool) _allowJavaScriptPanel {
5848 - (void) _customButtonClicked {
5849 if (commercial_ && self.isLoading && [package_ uninstalled])
5850 return [self reloadURLWithCache:NO];
5852 size_t count(buttons_.size());
5857 [self _clickButtonWithName:buttons_[0].first];
5859 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5860 for (const auto &button : buttons_)
5861 [buttons addObject:button.second];
5863 sheet_ = [[[UIActionSheet alloc]
5866 cancelButtonTitle:nil
5867 destructiveButtonTitle:nil
5868 otherButtonTitles:nil
5871 for (NSString *button in buttons)
5872 [sheet_ addButtonWithTitle:button];
5873 [sheet_ setContext:@"modify"];
5875 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5879 - (void) applyLoadingTitle {
5880 // Don't show "Loading" as the title. Ever.
5883 - (UIBarButtonItem *) rightButton {
5888 - (void) setPageColor:(UIColor *)color {
5889 return [super setPageColor:nil];
5892 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
5893 if ((self = [super init]) != nil) {
5894 database_ = database;
5895 name_ = name == nil ? @"" : [NSString stringWithString:name];
5896 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
5900 - (void) reloadData {
5903 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
5906 package_ = [database_ packageWithName:name_];
5907 versions_ = [package_ downgrades];
5911 if (package_ != nil) {
5912 [(Package *) package_ parse];
5914 commercial_ = [package_ isCommercial];
5916 if ([package_ mode] != nil)
5917 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
5918 if ([package_ source] == nil);
5919 else if ([package_ upgradableAndEssential:NO])
5920 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
5921 else if ([package_ uninstalled])
5922 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
5924 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
5925 if (![package_ uninstalled])
5926 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
5927 if ([versions_ count] != 0)
5928 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
5932 switch (buttons_.size()) {
5933 case 0: title = nil; break;
5934 case 1: title = buttons_[0].second; break;
5935 default: title = UCLocalize("MODIFY"); break;
5938 button_ = [[[UIBarButtonItem alloc]
5940 style:UIBarButtonItemStylePlain
5942 action:@selector(customButtonClicked)
5946 - (bool) isLoading {
5947 return commercial_ ? [super isLoading] : false;
5953 /* Package List Controller {{{ */
5954 @interface PackageListController : CyteListController <
5955 UITableViewDataSource,
5958 _transient Database *database_;
5960 _H<NSArray> packages_;
5961 _H<NSArray> sections_;
5963 _H<NSArray> thumbs_;
5964 std::vector<NSInteger> offset_;
5966 unsigned reloading_;
5969 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5971 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
5975 @implementation PackageListController
5977 - (NSURL *) referrerURL {
5978 return [self navigationURL];
5981 - (bool) isSummarized {
5985 - (bool) showsSections {
5989 - (void) didSelectPackage:(Package *)package {
5990 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
5991 [view setDelegate:self.delegate];
5992 [[self navigationController] pushViewController:view animated:YES];
5995 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5996 NSInteger count([sections_ count]);
5997 return count == 0 ? 1 : count;
6000 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6001 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6003 return [[sections_ objectAtIndex:section] name];
6006 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6007 if ([sections_ count] == 0)
6009 return [[sections_ objectAtIndex:section] count];
6012 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6013 @synchronized (database_) {
6014 if ([database_ era] != era_)
6017 Section *section([sections_ objectAtIndex:[path section]]);
6018 NSInteger row([path row]);
6019 Package *package([packages_ objectAtIndex:([section row] + row)]);
6020 return [[package retain] autorelease];
6023 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6024 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6026 cell = [[[PackageCell alloc] init] autorelease];
6028 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6029 [cell setPackage:package asSummary:[self isSummarized]];
6033 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6034 Package *package([self packageAtIndexPath:path]);
6035 package = [database_ packageWithName:[package id]];
6036 [self didSelectPackage:package];
6039 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6043 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6044 return offset_[index];
6047 - (CGFloat) rowHeight {
6048 return [self isSummarized] ? 38 : 73;
6051 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6052 if ((self = [super initWithTitle:title]) != nil) {
6053 database_ = database;
6057 - (void) releaseSubviews {
6064 [super releaseSubviews];
6067 - (bool) shouldBlock {
6071 - (NSMutableArray *) _reloadPackages {
6072 @synchronized (database_) {
6073 era_ = [database_ era];
6074 NSArray *packages([database_ packages]);
6076 return [NSMutableArray arrayWithArray:packages];
6079 - (void) _reloadData {
6080 if (reloading_ != 0) {
6085 NSMutableArray *packages;
6088 if ([self shouldYield]) {
6092 if (![self shouldBlock])
6095 hud = [self.delegate addProgressHUD];
6096 [hud setText:UCLocalize("LOADING")];
6100 packages = [self yieldToSelector:@selector(_reloadPackages)];
6103 [self.delegate removeProgressHUD:hud];
6104 } while (reloading_ == 2);
6106 packages = [self _reloadPackages];
6109 @synchronized (database_) {
6110 if (era_ != [database_ era])
6117 packages_ = packages;
6119 if ([self showsSections])
6120 sections_ = [self sectionsForPackages:packages];
6122 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6123 [section setCount:[packages_ count]];
6124 sections_ = [NSArray arrayWithObject:section];
6127 [super _reloadData];
6133 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6134 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6135 size_t end([packages count]);
6137 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6138 Section *section(prefix);
6140 thumbs_ = CollationThumbs_;
6141 offset_ = CollationOffset_;
6144 size_t offsets([CollationStarts_ count]);
6146 NSString *start([CollationStarts_ objectAtIndex:offset]);
6147 size_t length([start length]);
6149 for (size_t index(0); index != end; ++index) {
6151 Package *package([packages objectAtIndex:index]);
6152 NSString *name(PackageName(package, @selector(cyname)));
6154 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6155 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6156 NSString *title([CollationTitles_ objectAtIndex:offset]);
6157 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6158 [sections addObject:section];
6160 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6163 length = [start length];
6167 [section addToCount];
6170 for (; offset != offsets; ++offset) {
6171 NSString *title([CollationTitles_ objectAtIndex:offset]);
6172 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6173 [sections addObject:section];
6176 if ([prefix count] != 0) {
6177 Section *suffix([sections lastObject]);
6178 [prefix setName:[suffix name]];
6179 [suffix setName:nil];
6180 [sections insertObject:prefix atIndex:(offsets - 1)];
6188 /* Filtered Package List Controller {{{ */
6189 typedef Function<bool, Package *> PackageFilter;
6190 typedef Function<void, NSMutableArray *> PackageSorter;
6191 @interface FilteredPackageListController : PackageListController {
6192 PackageFilter filter_;
6193 PackageSorter sorter_;
6196 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6198 - (void) setFilter:(PackageFilter)filter;
6199 - (void) setSorter:(PackageSorter)sorter;
6203 @implementation FilteredPackageListController
6205 - (void) setFilter:(PackageFilter)filter {
6206 @synchronized (self) {
6210 - (void) setSorter:(PackageSorter)sorter {
6211 @synchronized (self) {
6215 - (NSMutableArray *) _reloadPackages {
6216 @synchronized (database_) {
6217 era_ = [database_ era];
6219 NSArray *packages([database_ packages]);
6220 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6222 PackageFilter filter;
6223 PackageSorter sorter;
6225 @synchronized (self) {
6230 _profile(PackageTable$reloadData$Filter)
6231 for (Package *package in packages)
6232 if (filter(package))
6233 [filtered addObject:package];
6241 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6242 if ((self = [super initWithDatabase:database title:title]) != nil) {
6243 [self setFilter:filter];
6250 /* Home Controller {{{ */
6251 @interface HomeController : CydiaWebViewController {
6252 CFRunLoopRef runloop_;
6253 SCNetworkReachabilityRef reachability_;
6258 @implementation HomeController
6260 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6261 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6265 if ((self = [super init]) != nil) {
6266 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6269 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6270 if (reachability_ != NULL) {
6271 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6272 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6274 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6275 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6282 if (reachability_ != NULL && runloop_ != NULL)
6283 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6287 - (NSURL *) navigationURL {
6288 return [NSURL URLWithString:@"cydia://home"];
6291 - (void) aboutButtonClicked {
6292 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6294 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6295 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6296 [alert setCancelButtonIndex:0];
6299 @"Copyright \u00a9 2008-2015\n"
6302 "Jay Freeman (saurik)\n"
6303 "saurik@saurik.com\n"
6304 "http://www.saurik.com/"
6310 - (UIBarButtonItem *) leftButton {
6311 return [[[UIBarButtonItem alloc]
6312 initWithTitle:UCLocalize("ABOUT")
6313 style:UIBarButtonItemStylePlain
6315 action:@selector(aboutButtonClicked)
6322 /* Cydia Tab Bar Controller {{{ */
6323 @interface CydiaTabBarController : CyteTabBarController <
6324 UITabBarControllerDelegate,
6327 _transient Database *database_;
6329 _H<UIActivityIndicatorView> indicator_;
6332 // XXX: ok, "updatedelegate_"?...
6333 _transient NSObject<CydiaDelegate> *updatedelegate_;
6336 - (void) beginUpdate;
6341 @implementation CydiaTabBarController
6343 - (id) initWithDatabase:(Database *)database {
6344 if ((self = [super init]) != nil) {
6345 database_ = database;
6346 [self setDelegate:self];
6348 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6349 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6351 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6355 - (void) beginUpdate {
6359 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6360 UITabBarItem *item([controller tabBarItem]);
6362 [item setBadgeValue:@""];
6363 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6365 [indicator_ startAnimating];
6366 [badge addSubview:indicator_];
6368 [updatedelegate_ retainNetworkActivityIndicator];
6372 detachNewThreadSelector:@selector(performUpdate)
6378 - (void) performUpdate {
6379 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6381 SourceStatus status(self, database_);
6382 [database_ updateWithStatus:status];
6385 performSelectorOnMainThread:@selector(completeUpdate)
6393 - (void) stopUpdateWithSelector:(SEL)selector {
6395 [updatedelegate_ releaseNetworkActivityIndicator];
6397 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6398 [[controller tabBarItem] setBadgeValue:nil];
6400 [indicator_ removeFromSuperview];
6401 [indicator_ stopAnimating];
6403 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6406 - (void) completeUpdate {
6409 [self stopUpdateWithSelector:@selector(reloadData)];
6412 - (void) cancelUpdate {
6413 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6416 - (void) cancelPressed {
6417 [self cancelUpdate];
6424 - (bool) isSourceCancelled {
6428 - (void) startSourceFetch:(NSString *)uri {
6431 - (void) stopSourceFetch:(NSString *)uri {
6434 - (void) setUpdateDelegate:(id)delegate {
6435 updatedelegate_ = delegate;
6441 /* Cydia:// Protocol {{{ */
6442 @interface CydiaURLProtocol : CyteURLProtocol {
6447 @implementation CydiaURLProtocol
6449 + (NSString *) scheme {
6453 - (bool) loadForPath:(NSString *)path ofRequest:(NSURLRequest *)request {
6454 NSRange slash([path rangeOfString:@"/"]);
6457 if (slash.location == NSNotFound) {
6461 command = [path substringToIndex:slash.location];
6462 path = [path substringFromIndex:(slash.location + 1)];
6465 Database *database([Database sharedInstance]);
6468 else if ([command isEqualToString:@"application-icon"]) {
6471 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6475 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
6476 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
6477 icon = [UIImage imageWithData:data];
6481 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
6482 icon = [UIImage imageAtPath:file];
6485 icon = [UIImage imageNamed:@"unknown.png"];
6487 [self _returnPNGWithImage:icon forRequest:request];
6488 } else if ([command isEqualToString:@"package-icon"]) {
6491 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6492 Package *package([database packageWithName:path]);
6496 UIImage *icon([package icon]);
6497 [self _returnPNGWithImage:icon forRequest:request];
6498 } else if ([command isEqualToString:@"uikit-image"]) {
6501 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6502 UIImage *icon(_UIImageWithName(path));
6503 [self _returnPNGWithImage:icon forRequest:request];
6504 } else if ([command isEqualToString:@"section-icon"]) {
6507 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6508 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6510 icon = [UIImage imageNamed:@"unknown.png"];
6511 [self _returnPNGWithImage:icon forRequest:request];
6513 return [super loadForPath:path ofRequest:request];
6522 /* Section Controller {{{ */
6523 @interface SectionController : FilteredPackageListController {
6525 _H<NSString> section_;
6528 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
6532 @implementation SectionController
6534 - (NSURL *) referrerURL {
6535 NSString *name(section_);
6536 name = name ?: @"*";
6537 NSString *key(key_);
6539 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6542 - (NSURL *) navigationURL {
6543 NSString *name(section_);
6544 name = name ?: @"*";
6545 NSString *key(key_);
6547 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6550 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
6553 title = UCLocalize("ALL_PACKAGES");
6554 else if (![section isEqual:@""])
6555 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
6557 title = UCLocalize("NO_SECTION");
6559 if ((self = [super initWithDatabase:database title:title]) != nil) {
6560 key_ = [source key];
6565 - (void) reloadData {
6566 Source *source([database_ sourceWithKey:key_]);
6567 _H<NSString> name(section_);
6569 [self setFilter:[=](Package *package) {
6570 NSString *section([package section]);
6574 section == nil && [name length] == 0 ||
6575 [name isEqualToString:section]
6578 [package source] == source
6579 ) && [package visible];
6587 /* Sections Controller {{{ */
6588 @interface SectionsController : CyteViewController <
6589 UITableViewDataSource,
6592 _transient Database *database_;
6594 _H<NSMutableArray> sections_;
6595 _H<NSMutableArray> filtered_;
6596 _H<UITableView, 2> list_;
6599 - (id) initWithDatabase:(Database *)database source:(Source *)source;
6600 - (void) editButtonClicked;
6604 @implementation SectionsController
6606 - (NSURL *) navigationURL {
6607 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
6610 - (Source *) source {
6613 return [database_ sourceWithKey:key_];
6616 - (void) updateNavigationItem {
6617 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6618 if ([sections_ count] == 0) {
6619 [[self navigationItem] setRightBarButtonItem:nil];
6621 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6622 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6624 action:@selector(editButtonClicked)
6625 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6629 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6630 [super setEditing:editing animated:animated];
6635 [self.delegate updateData];
6637 [self updateNavigationItem];
6640 - (void) viewDidAppear:(BOOL)animated {
6641 [super viewDidAppear:animated];
6642 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6645 - (void) viewWillDisappear:(BOOL)animated {
6646 [super viewWillDisappear:animated];
6647 [self setEditing:NO];
6650 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6651 Section *section = nil;
6652 int index = [indexPath row];
6653 if (![self isEditing]) {
6656 section = [filtered_ objectAtIndex:index];
6658 section = [sections_ objectAtIndex:index];
6663 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6664 if ([self isEditing])
6665 return [sections_ count];
6667 return [filtered_ count] + 1;
6670 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6674 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6675 static NSString *reuseIdentifier = @"SectionCell";
6677 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6679 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6681 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6686 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6687 if ([self isEditing])
6690 Section *section = [self sectionAtIndexPath:indexPath];
6692 SectionController *controller = [[[SectionController alloc]
6693 initWithDatabase:database_
6694 source:[self source]
6695 section:[section name]
6697 [controller setDelegate:self.delegate];
6699 [[self navigationController] pushViewController:controller animated:YES];
6703 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6704 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6705 [list_ setRowHeight:46];
6706 [(UITableView *) list_ setDataSource:self];
6707 [list_ setDelegate:self];
6708 [self setView:list_];
6711 - (void) viewDidLoad {
6712 [super viewDidLoad];
6714 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6717 - (void) releaseSubviews {
6723 [super releaseSubviews];
6726 - (id) initWithDatabase:(Database *)database source:(Source *)source {
6727 if ((self = [super init]) != nil) {
6728 database_ = database;
6729 key_ = [source key];
6733 - (void) reloadData {
6736 NSArray *packages = [database_ packages];
6738 sections_ = [NSMutableArray arrayWithCapacity:16];
6739 filtered_ = [NSMutableArray arrayWithCapacity:16];
6741 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6743 Source *source([self source]);
6746 for (Package *package in packages) {
6747 if (source != nil && [package source] != source)
6750 NSString *name([package section]);
6751 NSString *key(name == nil ? @"" : name);
6755 _profile(SectionsView$reloadData$Section)
6756 section = [sections objectForKey:key];
6757 if (section == nil) {
6758 _profile(SectionsView$reloadData$Section$Allocate)
6759 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6760 [sections setObject:section forKey:key];
6765 [section addToCount];
6767 _profile(SectionsView$reloadData$Filter)
6768 if (![package visible])
6776 [sections_ addObjectsFromArray:[sections allValues]];
6778 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6780 for (Section *section in (id) sections_) {
6781 size_t count([section row]);
6785 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6786 [section setCount:count];
6787 [filtered_ addObject:section];
6790 [self updateNavigationItem];
6795 - (void) editButtonClicked {
6796 [self setEditing:![self isEditing] animated:YES];
6802 /* Changes Controller {{{ */
6803 @interface ChangesController : FilteredPackageListController {
6807 - (id) initWithDatabase:(Database *)database;
6811 @implementation ChangesController
6813 - (NSURL *) referrerURL {
6814 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
6817 - (NSURL *) navigationURL {
6818 return [NSURL URLWithString:@"cydia://changes"];
6821 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6822 @synchronized (database_) {
6823 if ([database_ era] != era_)
6826 NSUInteger sectionIndex([path section]);
6827 if (sectionIndex >= [sections_ count])
6829 Section *section([sections_ objectAtIndex:sectionIndex]);
6830 NSInteger row([path row]);
6831 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
6834 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6835 NSString *context([alert context]);
6837 if ([context isEqualToString:@"norefresh"])
6838 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6841 - (void) setLeftBarButtonItem {
6842 if ([self.delegate updating])
6843 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6844 initWithTitle:UCLocalize("CANCEL")
6845 style:UIBarButtonItemStyleDone
6847 action:@selector(cancelButtonClicked)
6848 ] autorelease] animated:YES];
6850 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6851 initWithTitle:UCLocalize("REFRESH")
6852 style:UIBarButtonItemStylePlain
6854 action:@selector(refreshButtonClicked)
6855 ] autorelease] animated:YES];
6858 - (void) refreshButtonClicked {
6859 if ([self.delegate requestUpdate])
6860 [self setLeftBarButtonItem];
6863 - (void) cancelButtonClicked {
6864 [self.delegate cancelUpdate];
6867 - (void) upgradeButtonClicked {
6868 [self.delegate distUpgrade];
6869 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
6872 - (bool) shouldYield {
6876 - (bool) shouldBlock {
6880 - (void) useFilter {
6881 @synchronized (self) {
6882 [self setFilter:[](Package *package) {
6883 return [package upgradableAndEssential:YES] || [package visible];
6886 [self setSorter:[](NSMutableArray *packages) {
6887 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
6891 - (id) initWithDatabase:(Database *)database {
6892 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
6897 - (void) viewDidLoad {
6898 [super viewDidLoad];
6899 [self setLeftBarButtonItem];
6902 - (void) viewWillAppear:(BOOL)animated {
6903 [super viewWillAppear:animated];
6904 [self setLeftBarButtonItem];
6907 - (void) reloadData {
6908 [self setLeftBarButtonItem];
6912 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6913 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6915 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6916 Section *ignored = nil;
6917 Section *section = nil;
6921 bool unseens = false;
6923 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6925 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
6926 Package *package = [packages objectAtIndex:offset];
6928 BOOL uae = [package upgradableAndEssential:YES];
6932 time_t seen([package seen]);
6934 if (section == nil || last != seen) {
6938 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
6941 _profile(ChangesController$reloadData$Allocate)
6942 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
6943 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
6944 [sections addObject:section];
6948 [section addToCount];
6949 } else if ([package ignored]) {
6950 if (ignored == nil) {
6951 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
6953 [ignored addToCount];
6956 [upgradable addToCount];
6961 CFRelease(formatter);
6964 Section *last = [sections lastObject];
6965 size_t count = [last count];
6966 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
6967 [sections removeLastObject];
6970 if ([ignored count] != 0)
6971 [sections insertObject:ignored atIndex:0];
6973 [sections insertObject:upgradable atIndex:0];
6975 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
6976 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
6977 style:UIBarButtonItemStylePlain
6979 action:@selector(upgradeButtonClicked)
6980 ] autorelease]) animated:YES];
6987 /* Search Controller {{{ */
6988 @interface SearchController : FilteredPackageListController <
6991 _H<UISearchBar, 1> search_;
6996 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
6997 - (void) reloadData;
7001 @implementation SearchController
7003 - (NSURL *) referrerURL {
7004 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7007 - (NSURL *) navigationURL {
7008 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7009 return [NSURL URLWithString:@"cydia://search"];
7011 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7014 - (NSArray *) termsForQuery:(NSString *)query {
7015 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7016 for (NSString *component in [query componentsSeparatedByString:@" "])
7017 if ([component length] != 0)
7018 [terms addObject:component];
7023 - (void) useSearch {
7024 _H<NSArray> query([self termsForQuery:[search_ text]]);
7027 @synchronized (self) {
7028 [self setFilter:[=](Package *package) {
7029 if (![package unfiltered])
7031 if (![package matches:query])
7036 [self setSorter:[](NSMutableArray *packages) {
7037 [packages radixSortUsingSelector:@selector(rank)];
7045 - (void) usePrefix:(NSString *)prefix {
7046 _H<NSString> query(prefix);
7049 @synchronized (self) {
7050 [self setFilter:[=](Package *package) {
7051 if ([query length] == 0)
7053 if (![package unfiltered])
7055 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7060 [self setSorter:nullptr];
7066 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7068 [self usePrefix:[search_ text]];
7071 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7072 [search_ resignFirstResponder];
7076 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7077 [search_ setText:@""];
7078 [self searchBarButtonClicked:searchBar];
7081 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7082 [self searchBarButtonClicked:searchBar];
7085 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7086 [self usePrefix:text];
7089 - (bool) shouldYield {
7093 - (bool) shouldBlock {
7097 - (bool) isSummarized {
7101 - (bool) showsSections {
7105 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7106 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7107 search_ = [[[UISearchBar alloc] init] autorelease];
7108 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7109 [search_ setDelegate:self];
7111 UITextField *textField;
7112 if ([search_ respondsToSelector:@selector(searchField)])
7113 textField = [search_ searchField];
7115 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7117 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7118 [textField setEnablesReturnKeyAutomatically:NO];
7119 [[self navigationItem] setTitleView:textField];
7122 [search_ setText:query];
7127 - (void) viewDidAppear:(BOOL)animated {
7128 [super viewDidAppear:animated];
7130 if (!searchloaded_) {
7131 searchloaded_ = YES;
7132 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7133 [search_ layoutSubviews];
7136 if ([self isSummarized])
7137 [search_ becomeFirstResponder];
7140 - (void) reloadData {
7145 - (void) didSelectPackage:(Package *)package {
7146 [search_ resignFirstResponder];
7147 [super didSelectPackage:package];
7152 /* Package Settings Controller {{{ */
7153 @interface PackageSettingsController : CyteViewController <
7154 UITableViewDataSource,
7157 _transient Database *database_;
7159 _H<Package> package_;
7160 _H<UITableView, 2> table_;
7161 _H<UISwitch> subscribedSwitch_;
7162 _H<UISwitch> ignoredSwitch_;
7163 _H<UITableViewCell> subscribedCell_;
7164 _H<UITableViewCell> ignoredCell_;
7167 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7171 @implementation PackageSettingsController
7173 - (NSURL *) navigationURL {
7174 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7177 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7178 if (package_ == nil)
7181 if ([package_ installed] == nil)
7187 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7188 if (package_ == nil)
7191 // both sections contain just one item right now.
7195 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7199 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7201 return UCLocalize("SHOW_ALL_CHANGES_EX");
7203 return UCLocalize("IGNORE_UPGRADES_EX");
7206 - (void) onSubscribed:(id)control {
7207 bool value([control isOn]);
7208 if (package_ == nil)
7210 if ([package_ setSubscribed:value])
7211 [self.delegate updateData];
7214 - (void) _updateIgnored {
7215 const char *package([name_ UTF8String]);
7216 bool on([ignoredSwitch_ isOn]);
7218 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7219 fwrite(package, strlen(package), 1, dpkg);
7222 fwrite(" hold\n", 6, 1, dpkg);
7224 fwrite(" install\n", 9, 1, dpkg);
7229 - (void) onIgnored:(id)control {
7230 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7231 [invocation setTarget:self];
7232 [invocation setSelector:@selector(_updateIgnored)];
7234 [self.delegate reloadDataWithInvocation:invocation];
7237 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7238 if (package_ == nil)
7241 switch ([indexPath section]) {
7242 case 0: return subscribedCell_;
7243 case 1: return ignoredCell_;
7252 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7253 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7254 [self setView:view];
7256 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7257 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7258 [(UITableView *) table_ setDataSource:self];
7259 [table_ setDelegate:self];
7260 [view addSubview:table_];
7262 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7263 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7264 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7266 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7267 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7268 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7270 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7271 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7272 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7273 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7275 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7276 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7277 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7278 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7281 - (void) viewDidLoad {
7282 [super viewDidLoad];
7284 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7287 - (void) releaseSubviews {
7289 subscribedCell_ = nil;
7291 ignoredSwitch_ = nil;
7292 subscribedSwitch_ = nil;
7294 [super releaseSubviews];
7297 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7298 if ((self = [super init]) != nil) {
7299 database_ = database;
7304 - (void) reloadData {
7307 package_ = [database_ packageWithName:name_];
7309 if (package_ != nil) {
7310 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7311 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7312 } // XXX: what now, G?
7314 [table_ reloadData];
7320 /* Installed Controller {{{ */
7321 @interface InstalledController : FilteredPackageListController {
7325 - (id) initWithDatabase:(Database *)database;
7326 - (void) queueStatusDidChange;
7330 @implementation InstalledController
7332 - (NSURL *) referrerURL {
7333 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7336 - (NSURL *) navigationURL {
7337 return [NSURL URLWithString:@"cydia://installed"];
7340 - (void) useRecent {
7343 @synchronized (self) {
7344 [self setFilter:[](Package *package) {
7345 return ![package uninstalled] && package->role_ < 7;
7348 [self setSorter:[](NSMutableArray *packages) {
7349 [packages radixSortUsingSelector:@selector(recent)];
7353 - (void) useFilter:(UISegmentedControl *)segmented {
7354 NSInteger selected([segmented selectedSegmentIndex]);
7356 return [self useRecent];
7357 bool simple(selected == 0);
7360 @synchronized (self) {
7361 [self setFilter:[=](Package *package) {
7362 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7365 [self setSorter:nullptr];
7368 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7370 return [super sectionsForPackages:packages];
7372 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
7374 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7375 Section *section(nil);
7378 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
7379 Package *package([packages objectAtIndex:offset]);
7381 time_t upgraded([package upgraded]);
7382 if (upgraded < 1168364520)
7385 upgraded -= upgraded % (60 * 60 * 24);
7387 if (section == nil || upgraded != last) {
7392 continue; // XXX: name = UCLocalize("...");
7394 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
7398 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7399 [sections addObject:section];
7402 [section addToCount];
7405 CFRelease(formatter);
7409 - (id) initWithDatabase:(Database *)database {
7410 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7411 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7412 [segmented setSelectedSegmentIndex:0];
7413 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7414 [[self navigationItem] setTitleView:segmented];
7416 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7417 [self useFilter:segmented];
7419 [self queueStatusDidChange];
7424 - (void) queueButtonClicked {
7425 [self.delegate queue];
7429 - (void) queueStatusDidChange {
7432 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7433 initWithTitle:UCLocalize("QUEUE")
7434 style:UIBarButtonItemStyleDone
7436 action:@selector(queueButtonClicked)
7439 [[self navigationItem] setRightBarButtonItem:nil];
7444 - (void) modeChanged:(UISegmentedControl *)segmented {
7445 [self useFilter:segmented];
7452 /* Source Cell {{{ */
7453 @interface SourceCell : CyteTableViewCell <
7454 CyteTableViewCellDelegate,
7457 _H<Source, 1> source_;
7460 _H<NSString> origin_;
7461 _H<NSString> label_;
7462 _H<UIActivityIndicatorView> indicator_;
7465 - (void) setSource:(Source *)source;
7466 - (void) setFetch:(NSNumber *)fetch;
7470 @implementation SourceCell
7472 - (void) _setImage:(NSArray *)data {
7473 if ([url_ isEqual:[data objectAtIndex:0]]) {
7474 icon_ = [data objectAtIndex:1];
7475 [self.content setNeedsDisplay];
7479 - (void) _setSource:(NSURL *) url {
7480 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7482 if (NSData *data = [NSURLConnection
7483 sendSynchronousRequest:[NSURLRequest
7485 cachePolicy:NSURLRequestUseProtocolCachePolicy
7489 returningResponse:NULL
7492 if (UIImage *image = [UIImage imageWithData:data])
7493 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
7498 - (void) setSource:(Source *)source {
7500 [source_ setDelegate:self];
7502 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
7504 icon_ = [UIImage imageNamed:@"unknown.png"];
7506 origin_ = [source name];
7507 label_ = [source rooturi];
7509 [self.content setNeedsDisplay];
7511 url_ = [source iconURL];
7512 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
7515 - (void) setAllSource {
7517 [indicator_ stopAnimating];
7519 icon_ = [UIImage imageNamed:@"folder.png"];
7520 origin_ = UCLocalize("ALL_SOURCES");
7521 label_ = UCLocalize("ALL_SOURCES_EX");
7522 [self.content setNeedsDisplay];
7525 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7526 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7527 UIView *content([self contentView]);
7528 CGRect bounds([content bounds]);
7530 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7531 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7532 [self.content setBackgroundColor:[UIColor whiteColor]];
7533 [content addSubview:self.content];
7535 [self.content setDelegate:self];
7536 [self.content setOpaque:YES];
7538 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
7539 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
7540 [content addSubview:indicator_];
7542 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
7546 - (void) layoutSubviews {
7547 [super layoutSubviews];
7549 UIView *content([self contentView]);
7550 CGRect bounds([content bounds]);
7552 CGRect frame([indicator_ frame]);
7553 frame.origin.x = bounds.size.width - frame.size.width;
7554 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
7556 if (kCFCoreFoundationVersionNumber < 800)
7557 frame.origin.x -= 8;
7558 [indicator_ setFrame:frame];
7561 - (NSString *) accessibilityLabel {
7565 - (void) drawContentRect:(CGRect)rect {
7566 bool highlighted(self.highlighted);
7567 float width(rect.size.width);
7571 rect.size = [(UIImage *) icon_ size];
7573 while (rect.size.width > 32 || rect.size.height > 32) {
7574 rect.size.width /= 2;
7575 rect.size.height /= 2;
7578 rect.origin.x = 26 - rect.size.width / 2;
7579 rect.origin.y = 26 - rect.size.height / 2;
7581 [icon_ drawInRect:Retina(rect)];
7584 if (highlighted && kCFCoreFoundationVersionNumber < 800)
7589 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
7593 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
7596 - (void) setFetch:(NSNumber *)fetch {
7597 if ([fetch boolValue])
7598 [indicator_ startAnimating];
7600 [indicator_ stopAnimating];
7605 /* Sources Controller {{{ */
7606 @interface SourcesController : CyteViewController <
7607 UITableViewDataSource,
7610 _transient Database *database_;
7613 _H<UITableView, 2> list_;
7614 _H<NSMutableArray> sources_;
7618 _H<UIProgressHUD> hud_;
7621 NSURLConnection *trivial_bz2_;
7622 NSURLConnection *trivial_gz_;
7627 - (id) initWithDatabase:(Database *)database;
7628 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
7632 @implementation SourcesController
7634 - (void) _releaseConnection:(NSURLConnection *)connection {
7635 if (connection != nil) {
7636 [connection cancel];
7637 //[connection setDelegate:nil];
7638 [connection release];
7643 [self _releaseConnection:trivial_gz_];
7644 [self _releaseConnection:trivial_bz2_];
7649 - (NSURL *) navigationURL {
7650 return [NSURL URLWithString:@"cydia://sources"];
7653 - (void) viewDidAppear:(BOOL)animated {
7654 [super viewDidAppear:animated];
7655 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7658 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7662 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7664 return UCLocalize("INDIVIDUAL_SOURCES");
7668 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7671 case 1: return [sources_ count];
7676 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7677 @synchronized (database_) {
7678 if ([database_ era] != era_)
7680 if ([indexPath section] != 1)
7682 NSUInteger index([indexPath row]);
7683 if (index >= [sources_ count])
7685 return [sources_ objectAtIndex:index];
7688 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7689 static NSString *cellIdentifier = @"SourceCell";
7691 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7692 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7693 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7695 Source *source([self sourceAtIndexPath:indexPath]);
7697 [cell setAllSource];
7699 [cell setSource:source];
7704 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7705 SectionsController *controller([[[SectionsController alloc]
7706 initWithDatabase:database_
7707 source:[self sourceAtIndexPath:indexPath]
7710 [controller setDelegate:self.delegate];
7711 [[self navigationController] pushViewController:controller animated:YES];
7714 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7715 if ([indexPath section] != 1)
7717 Source *source = [self sourceAtIndexPath:indexPath];
7718 return [source record] != nil;
7721 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7722 _assert([indexPath section] == 1);
7723 if (editingStyle == UITableViewCellEditingStyleDelete) {
7724 Source *source = [self sourceAtIndexPath:indexPath];
7725 if (source == nil) return;
7727 [Sources_ removeObjectForKey:[source key]];
7729 [self.delegate syncData];
7733 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
7734 [self updateButtonsForEditingStatusAnimated:YES];
7738 [self.delegate addTrivialSource:href_];
7741 [self.delegate syncData];
7744 - (NSString *) getWarning {
7745 NSString *href(href_);
7746 NSRange colon([href rangeOfString:@"://"]);
7747 if (colon.location != NSNotFound)
7748 href = [href substringFromIndex:(colon.location + 3)];
7749 href = [href stringByAddingPercentEscapes];
7750 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7752 NSURL *url([NSURL URLWithString:href]);
7754 NSStringEncoding encoding;
7755 NSError *error(nil);
7757 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7758 return [warning length] == 0 ? nil : warning;
7762 - (void) _endConnection:(NSURLConnection *)connection {
7763 // XXX: the memory management in this method is horribly awkward
7765 NSURLConnection **field = NULL;
7766 if (connection == trivial_bz2_)
7767 field = &trivial_bz2_;
7768 else if (connection == trivial_gz_)
7769 field = &trivial_gz_;
7770 _assert(field != NULL);
7771 [connection release];
7775 trivial_bz2_ == nil &&
7778 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
7780 [self.delegate releaseNetworkActivityIndicator];
7782 [self.delegate removeProgressHUD:hud_];
7786 if (warning != nil) {
7787 UIAlertView *alert = [[[UIAlertView alloc]
7788 initWithTitle:UCLocalize("SOURCE_WARNING")
7791 cancelButtonTitle:UCLocalize("CANCEL")
7793 UCLocalize("ADD_ANYWAY"),
7797 [alert setContext:@"warning"];
7798 [alert setNumberOfRows:1];
7801 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
7807 } else if (error_ != nil) {
7808 UIAlertView *alert = [[[UIAlertView alloc]
7809 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7810 message:[error_ localizedDescription]
7812 cancelButtonTitle:UCLocalize("OK")
7813 otherButtonTitles:nil
7816 [alert setContext:@"urlerror"];
7821 UIAlertView *alert = [[[UIAlertView alloc]
7822 initWithTitle:UCLocalize("NOT_REPOSITORY")
7823 message:UCLocalize("NOT_REPOSITORY_EX")
7825 cancelButtonTitle:UCLocalize("OK")
7826 otherButtonTitles:nil
7829 [alert setContext:@"trivial"];
7839 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7840 switch ([response statusCode]) {
7846 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7847 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7849 [self _endConnection:connection];
7852 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7853 [self _endConnection:connection];
7856 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7857 NSURL *url([NSURL URLWithString:href]);
7859 NSMutableURLRequest *request = [NSMutableURLRequest
7861 cachePolicy:NSURLRequestUseProtocolCachePolicy
7865 [request setHTTPMethod:method];
7867 if (Machine_ != NULL)
7868 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7870 if (UniqueID_ != nil)
7871 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7873 if ([url isCydiaSecure]) {
7874 if (UniqueID_ != nil)
7875 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
7878 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7881 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7882 NSString *context([alert context]);
7884 if ([context isEqualToString:@"source"]) {
7887 NSString *href = [[alert textField] text];
7888 href = VerifySource(href);
7893 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7894 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7898 // XXX: this is stupid
7899 hud_ = [self.delegate addProgressHUD];
7900 [hud_ setText:UCLocalize("VERIFYING_URL")];
7901 [self.delegate retainNetworkActivityIndicator];
7910 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7911 } else if ([context isEqualToString:@"trivial"])
7912 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7913 else if ([context isEqualToString:@"urlerror"])
7914 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7915 else if ([context isEqualToString:@"warning"]) {
7918 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
7927 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7931 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
7932 BOOL editing([list_ isEditing]);
7935 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7936 initWithTitle:UCLocalize("ADD")
7937 style:UIBarButtonItemStylePlain
7939 action:@selector(addButtonClicked)
7940 ] autorelease] animated:animated];
7941 else if ([self.delegate updating])
7942 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7943 initWithTitle:UCLocalize("CANCEL")
7944 style:UIBarButtonItemStyleDone
7946 action:@selector(cancelButtonClicked)
7947 ] autorelease] animated:animated];
7949 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7950 initWithTitle:UCLocalize("REFRESH")
7951 style:UIBarButtonItemStylePlain
7953 action:@selector(refreshButtonClicked)
7954 ] autorelease] animated:animated];
7956 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7957 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
7958 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7960 action:@selector(editButtonClicked)
7961 ] autorelease] animated:animated];
7965 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
7966 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7967 [list_ setRowHeight:53];
7968 [(UITableView *) list_ setDataSource:self];
7969 [list_ setDelegate:self];
7970 [self setView:list_];
7973 - (void) viewDidLoad {
7974 [super viewDidLoad];
7976 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7977 [self updateButtonsForEditingStatusAnimated:NO];
7980 - (void) viewWillAppear:(BOOL)animated {
7981 [super viewWillAppear:animated];
7983 [list_ setEditing:NO];
7984 [self updateButtonsForEditingStatusAnimated:NO];
7987 - (void) releaseSubviews {
7992 [super releaseSubviews];
7995 - (id) initWithDatabase:(Database *)database {
7996 if ((self = [super init]) != nil) {
7997 database_ = database;
8001 - (void) reloadData {
8003 [self updateButtonsForEditingStatusAnimated:YES];
8005 @synchronized (database_) {
8006 era_ = [database_ era];
8008 sources_ = [NSMutableArray arrayWithCapacity:16];
8009 [sources_ addObjectsFromArray:[database_ sources]];
8011 [sources_ sortUsingSelector:@selector(compareByName:)];
8014 int count([sources_ count]);
8016 for (int i = 0; i != count; i++) {
8017 if ([[sources_ objectAtIndex:i] record] == nil)
8025 - (void) showAddSourcePrompt {
8026 UIAlertView *alert = [[[UIAlertView alloc]
8027 initWithTitle:UCLocalize("ENTER_APT_URL")
8030 cancelButtonTitle:UCLocalize("CANCEL")
8032 UCLocalize("ADD_SOURCE"),
8036 [alert setContext:@"source"];
8038 [alert setNumberOfRows:1];
8039 [alert addTextFieldWithValue:@"http://" label:@""];
8041 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8042 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8043 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8044 [traits setKeyboardType:UIKeyboardTypeURL];
8045 // XXX: UIReturnKeyDone
8046 [traits setReturnKeyType:UIReturnKeyNext];
8051 - (void) addButtonClicked {
8052 [self showAddSourcePrompt];
8055 - (void) refreshButtonClicked {
8056 if ([self.delegate requestUpdate])
8057 [self updateButtonsForEditingStatusAnimated:YES];
8060 - (void) cancelButtonClicked {
8061 [self.delegate cancelUpdate];
8064 - (void) editButtonClicked {
8065 [list_ setEditing:![list_ isEditing] animated:YES];
8066 [self updateButtonsForEditingStatusAnimated:YES];
8072 /* Stash Controller {{{ */
8073 @interface StashController : CyteViewController {
8074 _H<UIActivityIndicatorView> spinner_;
8075 _H<UILabel> status_;
8076 _H<UILabel> caption_;
8081 @implementation StashController
8084 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8085 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8086 [self setView:view];
8088 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8090 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8091 CGRect spinrect = [spinner_ frame];
8092 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8093 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8094 [spinner_ setFrame:spinrect];
8095 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8096 [view addSubview:spinner_];
8097 [spinner_ startAnimating];
8100 captrect.size.width = [[self view] frame].size.width;
8101 captrect.size.height = 40.0f;
8102 captrect.origin.x = 0;
8103 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8104 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8105 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8106 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8107 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8108 [caption_ setTextColor:[UIColor whiteColor]];
8109 [caption_ setBackgroundColor:[UIColor clearColor]];
8110 [caption_ setShadowColor:[UIColor blackColor]];
8111 [caption_ setTextAlignment:NSTextAlignmentCenter];
8112 [view addSubview:caption_];
8115 statusrect.size.width = [[self view] frame].size.width;
8116 statusrect.size.height = 30.0f;
8117 statusrect.origin.x = 0;
8118 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8119 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8120 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8121 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8122 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8123 [status_ setTextColor:[UIColor whiteColor]];
8124 [status_ setBackgroundColor:[UIColor clearColor]];
8125 [status_ setShadowColor:[UIColor blackColor]];
8126 [status_ setTextAlignment:NSTextAlignmentCenter];
8127 [view addSubview:status_];
8130 - (void) releaseSubviews {
8135 [super releaseSubviews];
8141 @interface Cydia : CyteApplication <
8142 ConfirmationControllerDelegate,
8146 _H<CyteWindow> window_;
8147 _H<CydiaTabBarController> tabbar_;
8148 _H<CyteTabBarController> emulated_;
8149 _H<AppCacheController> appcache_;
8151 _H<NSMutableArray> essential_;
8152 _H<NSMutableArray> broken_;
8154 Database *database_;
8156 _H<NSURL> starturl_;
8160 _H<StashController> stash_;
8169 @implementation Cydia
8171 - (void) lockSuspend {
8172 if (locked_++ == 0) {
8173 if ($SBSSetInterceptsMenuButtonForever != NULL)
8174 (*$SBSSetInterceptsMenuButtonForever)(true);
8176 [self setIdleTimerDisabled:YES];
8180 - (void) unlockSuspend {
8181 if (--locked_ == 0) {
8182 [self setIdleTimerDisabled:NO];
8184 if ($SBSSetInterceptsMenuButtonForever != NULL)
8185 (*$SBSSetInterceptsMenuButtonForever)(false);
8189 - (void) beginUpdate {
8190 [tabbar_ beginUpdate];
8193 - (void) cancelUpdate {
8194 [tabbar_ cancelUpdate];
8197 - (bool) requestUpdate {
8198 if (CyteIsReachable("cydia.saurik.com")) {
8202 UIAlertView *alert = [[[UIAlertView alloc]
8203 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8204 message:@"Host Unreachable" // XXX: Localize
8206 cancelButtonTitle:UCLocalize("OK")
8207 otherButtonTitles:nil
8210 [alert setContext:@"norefresh"];
8218 return [tabbar_ updating];
8222 if ([broken_ count] != 0) {
8223 int count = [broken_ count];
8225 UIAlertView *alert = [[[UIAlertView alloc]
8226 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8227 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8229 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8231 UCLocalize("TEMPORARY_IGNORE"),
8235 [alert setContext:@"fixhalf"];
8236 [alert setNumberOfRows:2];
8238 } else if (!Ignored_ && [essential_ count] != 0) {
8239 int count = [essential_ count];
8241 UIAlertView *alert = [[[UIAlertView alloc]
8242 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8243 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8245 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8247 UCLocalize("UPGRADE_ESSENTIAL"),
8248 UCLocalize("COMPLETE_UPGRADE"),
8252 [alert setContext:@"upgrade"];
8257 - (void) returnToCydia {
8261 - (void) reloadSpringBoard {
8262 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8263 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8265 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8267 system("/usr/bin/killall backboardd SpringBoard");
8270 - (void) _saveConfig {
8271 SaveConfig(database_);
8274 // Navigation controller for the queuing badge.
8275 - (UINavigationController *) queueNavigationController {
8276 NSArray *controllers = [tabbar_ viewControllers];
8277 return [controllers objectAtIndex:3];
8280 - (void) _updateData {
8282 [window_ unloadData];
8284 UINavigationController *navigation = [self queueNavigationController];
8286 id queuedelegate = nil;
8287 if ([[navigation viewControllers] count] > 0)
8288 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8290 [queuedelegate queueStatusDidChange];
8291 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8294 - (void) _refreshIfPossible {
8295 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8297 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
8299 bool recently = false;
8300 if (update != nil) {
8301 NSTimeInterval interval([update timeIntervalSinceNow]);
8302 if (interval > -(15*60))
8306 // Don't automatic refresh if:
8307 // - We already refreshed recently.
8308 // - We already auto-refreshed this launch.
8309 // - Auto-refresh is disabled.
8310 // - Cydia's server is not reachable
8311 if (recently || loaded_ || ManualRefresh || !CyteIsReachable("cydia.saurik.com")) {
8312 // If we are cancelling, we need to make sure it knows it's already loaded.
8315 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8317 // We are going to load, so remember that.
8320 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
8326 - (void) refreshIfPossible {
8327 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8330 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8331 _profile(reloadDataWithInvocation)
8332 @synchronized (self) {
8333 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8335 [hud setText:UCLocalize("RELOADING_DATA")];
8337 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8341 [essential_ removeAllObjects];
8342 [broken_ removeAllObjects];
8344 _profile(reloadDataWithInvocation$Essential)
8345 NSArray *packages([database_ packages]);
8346 for (Package *package in packages) {
8348 [broken_ addObject:package];
8349 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8350 if ([package essential] && [package installed] != nil)
8351 [essential_ addObject:package];
8357 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8360 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8361 [changesItem setBadgeValue:badge];
8362 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8363 [self setApplicationIconBadgeNumber:changes];
8366 [changesItem setBadgeValue:nil];
8367 [changesItem setAnimatedBadge:NO];
8368 [self setApplicationIconBadgeNumber:0];
8375 [self removeProgressHUD:hud];
8382 - (void) updateData {
8386 - (void) updateDataAndLoad {
8388 if ([database_ progressDelegate] == nil)
8394 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8397 - (void) disemulate {
8398 if (emulated_ == nil)
8401 [window_ setRootViewController:tabbar_];
8404 [window_ setUserInteractionEnabled:YES];
8407 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8408 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8410 UIViewController *parent;
8411 if (emulated_ == nil)
8421 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8422 [parent presentModalViewController:navigation animated:YES];
8425 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8426 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8428 if (navigation != nil)
8429 [navigation pushViewController:progress animated:YES];
8431 [self presentModalViewController:progress force:YES];
8433 [progress invoke:invocation withTitle:title];
8437 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8438 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8441 - (void) repairWithInvocation:(NSInvocation *)invocation {
8443 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8447 - (void) repairWithSelector:(SEL)selector {
8448 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8451 - (void) reloadData {
8452 [self reloadDataWithInvocation:nil];
8453 if ([database_ progressDelegate] == nil)
8459 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8462 - (void) addSource:(NSDictionary *) source {
8463 CydiaAddSource(source);
8466 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
8467 CydiaAddSource(href, distribution, sections);
8470 // XXX: this method should not return anything
8471 - (BOOL) addTrivialSource:(NSString *)href {
8472 CydiaAddSource(href, @"./");
8477 pkgProblemResolver *resolver = [database_ resolver];
8479 resolver->InstallProtect();
8480 if (!resolver->Resolve(true))
8485 // XXX: this is a really crappy way of doing this.
8486 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8487 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8488 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8489 if ([tabbar_ updating])
8490 [tabbar_ cancelUpdate];
8492 if (![database_ prepare])
8495 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8496 [page setDelegate:self];
8497 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8500 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8501 [tabbar_ presentModalViewController:confirm_ animated:YES];
8507 @synchronized (self) {
8512 - (void) clearPackage:(Package *)package {
8513 @synchronized (self) {
8520 - (void) installPackages:(NSArray *)packages {
8521 @synchronized (self) {
8522 for (Package *package in packages)
8529 - (void) installPackage:(Package *)package {
8530 @synchronized (self) {
8537 - (void) removePackage:(Package *)package {
8538 @synchronized (self) {
8545 - (void) distUpgrade {
8546 @synchronized (self) {
8547 if (![database_ upgrade])
8555 system("/usr/bin/uicache");
8560 UIProgressHUD *hud([self addProgressHUD]);
8561 [hud setText:UCLocalize("LOADING")];
8562 [self yieldToSelector:@selector(_uicache)];
8563 [self removeProgressHUD:hud];
8567 [database_ perform];
8568 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8569 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
8572 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8575 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8576 [self unlockSuspend];
8579 - (void) cancelAndClear:(bool)clear {
8580 @synchronized (self) {
8592 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8593 NSString *context([alert context]);
8595 if ([context isEqualToString:@"conffile"]) {
8596 FILE *input = [database_ input];
8597 if (button == [alert cancelButtonIndex])
8598 fprintf(input, "N\n");
8599 else if (button == [alert firstOtherButtonIndex])
8600 fprintf(input, "Y\n");
8603 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8604 } else if ([context isEqualToString:@"fixhalf"]) {
8605 if (button == [alert cancelButtonIndex]) {
8606 @synchronized (self) {
8607 for (Package *broken in (id) broken_) {
8609 NSString *id(ShellEscape([broken id]));
8610 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
8611 " /var/lib/dpkg/info/%@.prerm"
8612 " /var/lib/dpkg/info/%@.postrm"
8613 " /var/lib/dpkg/info/%@.preinst"
8614 " /var/lib/dpkg/info/%@.postinst"
8615 " /var/lib/dpkg/info/%@.extrainst_"
8616 "", id, id, id, id, id] UTF8String]);
8622 } else if (button == [alert firstOtherButtonIndex]) {
8623 [broken_ removeAllObjects];
8627 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8628 } else if ([context isEqualToString:@"upgrade"]) {
8629 if (button == [alert firstOtherButtonIndex]) {
8630 @synchronized (self) {
8631 for (Package *essential in (id) essential_)
8632 [essential install];
8637 } else if (button == [alert firstOtherButtonIndex] + 1) {
8639 } else if (button == [alert cancelButtonIndex]) {
8643 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8647 - (void) system:(NSString *)command {
8648 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8651 system([command UTF8String]);
8657 - (void) applicationWillSuspend {
8659 [super applicationWillSuspend];
8662 - (BOOL) isSafeToSuspend {
8665 NSLog(@"isSafeToSuspend: locked_ != 0");
8670 if ([tabbar_ modalViewController] != nil)
8673 // Use external process status API internally.
8674 // This is probably a really bad idea.
8675 // XXX: what is the point of this? does this solve anything at all?
8676 uint64_t status = 0;
8678 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8679 notify_get_state(notify_token, &status);
8680 notify_cancel(notify_token);
8685 NSLog(@"isSafeToSuspend: status != 0");
8691 NSLog(@"isSafeToSuspend: -> true");
8696 - (void) suspendReturningToLastApp:(BOOL)returning {
8697 if ([self isSafeToSuspend])
8698 [super suspendReturningToLastApp:returning];
8702 if ([self isSafeToSuspend])
8706 - (void) applicationSuspend {
8707 if ([self isSafeToSuspend])
8708 [super applicationSuspend];
8711 - (void) applicationSuspend:(GSEventRef)event {
8712 if ([self isSafeToSuspend])
8713 [super applicationSuspend:event];
8716 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8717 if ([self isSafeToSuspend])
8718 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8721 - (void) _setSuspended:(BOOL)value {
8722 if ([self isSafeToSuspend])
8723 [super _setSuspended:value];
8726 - (UIProgressHUD *) addProgressHUD {
8727 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
8728 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8730 [window_ setUserInteractionEnabled:NO];
8732 UIViewController *target(tabbar_);
8733 if (UIViewController *modal = [target modalViewController])
8736 [hud showInView:[target view]];
8742 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8743 [self unlockSuspend];
8745 [hud removeFromSuperview];
8746 [window_ setUserInteractionEnabled:YES];
8749 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
8750 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
8753 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
8754 NSString *scheme([[url scheme] lowercaseString]);
8755 if ([[url absoluteString] length] <= [scheme length] + 3)
8757 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8758 NSArray *components([path componentsSeparatedByString:@"/"]);
8760 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
8761 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
8762 if (controller != nil)
8763 [controller setDelegate:self];
8767 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8770 NSString *base([components objectAtIndex:0]);
8772 CyteViewController *controller = nil;
8774 if ([base isEqualToString:@"url"]) {
8775 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8776 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8777 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
8778 } else if (!external && [components count] == 1) {
8779 if ([base isEqualToString:@"sources"]) {
8780 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8783 if ([base isEqualToString:@"home"]) {
8784 controller = [[[HomeController alloc] init] autorelease];
8787 if ([base isEqualToString:@"sections"]) {
8788 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
8791 if ([base isEqualToString:@"search"]) {
8792 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
8795 if ([base isEqualToString:@"changes"]) {
8796 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8799 if ([base isEqualToString:@"installed"]) {
8800 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8802 } else if ([components count] == 2) {
8803 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8805 if ([base isEqualToString:@"package"]) {
8806 controller = [self pageForPackage:argument withReferrer:referrer];
8809 if (!external && [base isEqualToString:@"search"]) {
8810 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
8813 if (!external && [base isEqualToString:@"sections"]) {
8814 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
8816 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
8819 if ([base isEqualToString:@"sources"]) {
8820 if ([argument isEqualToString:@"add"]) {
8821 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8822 [(SourcesController *)controller showAddSourcePrompt];
8824 Source *source([database_ sourceWithKey:argument]);
8825 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
8829 if (!external && [base isEqualToString:@"launch"]) {
8830 [self launchApplicationWithIdentifier:argument suspended:NO];
8833 } else if (!external && [components count] == 3) {
8834 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8835 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
8837 if ([base isEqualToString:@"package"]) {
8838 if ([arg2 isEqualToString:@"settings"]) {
8839 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8840 } else if ([arg2 isEqualToString:@"files"]) {
8841 controller = [[[FileTable alloc] initWithDatabase:database_ forPackage:arg1] autorelease];
8845 if ([base isEqualToString:@"sections"]) {
8846 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
8847 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
8848 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
8852 [controller setDelegate:self];
8856 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
8857 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
8860 [tabbar_ setUnselectedViewController:page];
8865 - (void) applicationOpenURL:(NSURL *)url {
8866 [super applicationOpenURL:url];
8871 [self openCydiaURL:url forExternal:YES];
8874 - (void) applicationWillResignActive:(UIApplication *)application {
8875 // Stop refreshing if you get a phone call or lock the device.
8876 if ([tabbar_ updating])
8877 [tabbar_ cancelUpdate];
8879 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8880 [super applicationWillResignActive:application];
8883 - (void) saveState {
8884 [[NSDictionary dictionaryWithObjectsAndKeys:
8885 @"InterfaceState", [tabbar_ navigationURLCollection],
8886 @"LastClosed", [NSDate date],
8887 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
8888 nil] writeToFile:@ SavedState_ atomically:YES];
8893 - (void) applicationWillTerminate:(UIApplication *)application {
8897 - (void) applicationDidEnterBackground:(UIApplication *)application {
8898 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
8899 return [self terminateWithSuccess];
8900 Backgrounded_ = [NSDate date];
8904 - (void) applicationWillEnterForeground:(UIApplication *)application {
8905 if (Backgrounded_ == nil)
8908 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
8910 if (interval <= -(30*60)) {
8911 [tabbar_ setSelectedIndex:0];
8912 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
8915 if (interval <= -(15*60)) {
8916 if (CyteIsReachable("cydia.saurik.com")) {
8917 [tabbar_ beginUpdate];
8918 [appcache_ reloadURLWithCache:YES];
8922 if ([database_ delocked])
8926 - (void) setConfigurationData:(NSString *)data {
8927 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
8929 if (!conffile_r(data)) {
8930 lprintf("E:invalid conffile\n");
8934 NSString *ofile = conffile_r[1];
8935 //NSString *nfile = conffile_r[2];
8937 UIAlertView *alert = [[[UIAlertView alloc]
8938 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
8939 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
8941 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
8943 UCLocalize("ACCEPT_NEW_COPY"),
8944 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
8948 [alert setContext:@"conffile"];
8949 [alert setNumberOfRows:2];
8953 - (void) addStashController {
8955 stash_ = [[[StashController alloc] init] autorelease];
8956 [window_ addSubview:[stash_ view]];
8959 - (void) removeStashController {
8960 [[stash_ view] removeFromSuperview];
8962 [self unlockSuspend];
8966 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8967 UpdateExternalStatus(1);
8968 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
8969 UpdateExternalStatus(0);
8971 [self removeStashController];
8972 [self reloadSpringBoard];
8975 - (void) applicationDidFinishLaunching:(id)unused {
8976 [super applicationDidFinishLaunching:unused];
8977 [CyteWebViewController _initialize];
8979 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
8981 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8983 // this would disallow http{,s} URLs from accessing this data
8984 //[WebView registerURLSchemeAsLocal:@"cydia"];
8986 Font12_ = [UIFont systemFontOfSize:12];
8987 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
8988 Font14_ = [UIFont systemFontOfSize:14];
8989 Font18_ = [UIFont systemFontOfSize:18];
8990 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
8991 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
8993 essential_ = [NSMutableArray arrayWithCapacity:4];
8994 broken_ = [NSMutableArray arrayWithCapacity:4];
8996 // XXX: I really need this thing... like, seriously... I'm sorry
8997 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
8998 [appcache_ reloadData];
9000 window_ = [[[CyteWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9001 [window_ orderFront:self];
9002 [window_ makeKey:self];
9003 [window_ setHidden:NO];
9005 if (access("/.cydia_no_stash", F_OK) == 0);
9009 [self addStashController];
9010 // XXX: this would be much cleaner as a yieldToSelector:
9011 // that way the removeStashController could happen right here inline
9012 // we also could no longer require the useless stash_ field anymore
9013 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9018 int error(stat("/", &root));
9019 _assert(error != -1);
9021 #define Stash_(path) do { \
9022 struct stat folder; \
9023 int error(lstat((path), &folder)); \
9024 if (error != -1 && ( \
9025 folder.st_dev == root.st_dev && \
9026 S_ISDIR(folder.st_mode) \
9027 ) || error == -1 && ( \
9028 errno == ENOENT || \
9033 Stash_("/Applications");
9034 Stash_("/Library/Ringtones");
9035 Stash_("/Library/Wallpaper");
9036 //Stash_("/usr/bin");
9037 Stash_("/usr/include");
9038 Stash_("/usr/share");
9039 //Stash_("/var/lib");
9043 database_ = [Database sharedInstance];
9044 [database_ setDelegate:self];
9046 [window_ setUserInteractionEnabled:NO];
9048 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9050 [tabbar_ addViewControllers:nil,
9051 @"Cydia", @"home.png", @"home7.png", @"home7s.png",
9052 UCLocalize("SOURCES"), @"install.png", @"install7.png", @"install7s.png",
9053 UCLocalize("CHANGES"), @"changes.png", @"changes7.png", @"changes7s.png",
9054 UCLocalize("INSTALLED"), @"manage.png", @"manage7.png", @"manage7s.png",
9055 UCLocalize("SEARCH"), @"search.png", @"search7.png", @"search7s.png",
9058 [tabbar_ setUpdateDelegate:self];
9060 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9061 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9062 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9064 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9065 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9066 [emulated_ setSelectedIndex:0];
9068 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9069 [emulated_ concealTabBarSelection];
9071 [window_ setRootViewController:emulated_];
9073 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9077 - (NSArray *) defaultStartPages {
9078 NSMutableArray *standard = [NSMutableArray array];
9079 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9080 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9081 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9082 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9083 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9089 if ([emulated_ modalViewController] != nil)
9090 [emulated_ dismissModalViewControllerAnimated:YES];
9091 [window_ setUserInteractionEnabled:NO];
9093 [self reloadDataWithInvocation:nil];
9094 [self refreshIfPossible];
9097 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9099 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9100 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9101 int standardIndex = 0;
9102 NSArray *standard = [self defaultStartPages];
9109 NSDate *closed = [state objectForKey:@"LastClosed"];
9110 if (valid && closed != nil) {
9111 NSTimeInterval interval([closed timeIntervalSinceNow]);
9112 if (interval <= -(30*60))
9116 if (valid && [saved count] != [standard count])
9120 for (unsigned int i = 0; i < [standard count]; i++) {
9121 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9122 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9123 // but it's good enough for now.
9124 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9131 NSArray *items = nil;
9133 [tabbar_ setSelectedIndex:savedIndex];
9136 [tabbar_ setSelectedIndex:standardIndex];
9140 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9141 NSArray *stack = [items objectAtIndex:tab];
9142 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9143 NSMutableArray *current = [NSMutableArray array];
9145 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9146 NSString *addr = [stack objectAtIndex:nav];
9147 NSURL *url = [NSURL URLWithString:addr];
9148 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9150 [current addObject:page];
9153 [navigation setViewControllers:current];
9156 // (Try to) show the startup URL.
9157 if (starturl_ != nil) {
9158 [self openCydiaURL:starturl_ forExternal:YES];
9163 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9165 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9166 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9169 if (item != nil && IsWildcat_) {
9170 [sheet showFromBarButtonItem:item animated:YES];
9172 [sheet showInView:window_];
9176 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9177 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9178 [progress setTitle:task];
9179 [progress addProgressEvent:event];
9182 - (void) addProgressEventForTask:(NSArray *)data {
9183 CydiaProgressEvent *event([data objectAtIndex:0]);
9184 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9185 [self addProgressEvent:event forTask:task];
9188 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9189 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9195 id Alloc_(id self, SEL selector) {
9196 id object = alloc_(self, selector);
9197 lprintf("[%s]A-%p\n", self->isa->name, object);
9202 id Dealloc_(id self, SEL selector) {
9203 id object = dealloc_(self, selector);
9204 lprintf("[%s]D-%p\n", self->isa->name, object);
9208 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9211 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9213 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9215 return [(NSMutableDictionary *) copy autorelease];
9218 int main_store(int, char *argv[]);
9220 int main(int argc, char *argv[]) {
9222 const char *argv0(argv[0]);
9223 if (const char *slash = strrchr(argv0, '/'))
9226 else if (!strcmp(argv0, "store"))
9227 return main_store(argc, argv);
9230 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9234 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9238 CyteInitialize(@"Cydia", Cydia_);
9239 UpdateExternalStatus(0);
9241 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9242 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9243 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9245 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@/1.1", IsWildcat_ ? @"ipad" : @"iphone"]);
9246 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9248 /* Set Locale {{{ */
9249 Locale_ = CFLocaleCopyCurrent();
9250 Languages_ = [NSLocale preferredLanguages];
9252 std::string languages;
9253 const char *translation(NULL);
9255 // XXX: this isn't really a language, but this is compatible with older Cydia builds
9256 if (Locale_ != NULL)
9257 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
9258 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
9259 if (pattern(language)) {
9260 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
9261 languages += translation;
9266 if (Languages_ != nil)
9267 for (NSString *locale : Languages_) {
9268 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
9269 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
9270 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
9271 language = [NSString stringWithFormat:@"%@-%@", language, script];
9272 languages += [language UTF8String];
9277 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
9279 /* Index Collation {{{ */
9280 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
9281 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
9282 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
9283 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
9284 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
9285 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
9287 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
9289 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
9290 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
9291 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})
9292 CollationOffset_.push_back(offset);
9293 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];
9294 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];
9297 CollationThumbs_ = [collation sectionIndexTitles];
9298 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
9299 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
9301 CollationTitles_ = [collation sectionTitles];
9302 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
9304 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
9305 if (&transform != NULL && transform != nil) {
9306 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
9307 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
9308 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
9309 UErrorCode code(U_ZERO_ERROR);
9310 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
9311 if (!U_SUCCESS(code))
9312 NSLog(@"%s", u_errorName(code));
9316 } @catch (NSException *e) {
9320 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
9322 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];
9323 for (NSInteger offset(0); offset != 28; ++offset)
9324 CollationOffset_.push_back(offset);
9326 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];
9327 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];
9331 App_ = [[NSBundle mainBundle] bundlePath];
9334 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
9335 mkdir([Cache_ UTF8String], 0755);
9337 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9338 alloc_ = alloc->method_imp;
9339 alloc->method_imp = (IMP) &Alloc_;*/
9341 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9342 dealloc_ = dealloc->method_imp;
9343 dealloc->method_imp = (IMP) &Dealloc_;*/
9345 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
9346 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
9347 UniqueID_ = UniqueIdentifier([UIDevice currentDevice]);
9349 /* System Information {{{ */
9353 size = sizeof(maxproc);
9354 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9355 perror("sysctlbyname(\"kern.maxproc\", ?)");
9356 else if (maxproc < 64) {
9358 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9359 perror("sysctlbyname(\"kern.maxproc\", #)");
9362 /* Load Database {{{ */
9363 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9366 mkdir("/var/mobile/Library/Cydia", 0755);
9367 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
9370 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
9371 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
9372 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
9373 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
9376 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
9379 Values_ = [metadata objectForKey:@"Values"];
9381 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
9383 if (Sections_ == nil)
9384 Sections_ = [metadata objectForKey:@"Sections"];
9385 if (Sections_ == nil)
9386 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9388 if (Sources_ == nil)
9389 Sources_ = [metadata objectForKey:@"Sources"];
9390 if (Sources_ == nil)
9391 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9393 // XXX: this wrong, but in a way that doesn't matter :/
9394 if (Version_ == nil)
9395 Version_ = [metadata objectForKey:@"Version"];
9396 if (Version_ == nil)
9397 Version_ = [NSNumber numberWithUnsignedInt:0];
9399 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
9401 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
9404 NSLog(@"unable to import package preferences... from 2010? oh well :/");
9407 if ([Version_ unsignedIntValue] == 0) {
9408 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9409 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9410 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9411 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
9413 Version_ = [NSNumber numberWithUnsignedInt:1];
9415 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
9416 [cache removeObjectForKey:@"LastUpdate"];
9417 [cache writeToFile:@ CacheState_ atomically:YES];
9421 _H<NSMutableArray> broken([NSMutableArray array]);
9422 for (NSString *key in (id) Sources_)
9423 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
9424 [broken addObject:key];
9425 if ([broken count] != 0)
9426 for (NSString *key in (id) broken)
9427 [Sources_ removeObjectForKey:key];
9431 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
9434 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9436 if (kCFCoreFoundationVersionNumber > 1000)
9437 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
9439 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9441 if (access("/User", F_OK) != 0 || version != 6) {
9443 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
9447 if (access("/tmp/cydia.chk", F_OK) == 0) {
9448 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
9449 _assert(errno == ENOENT);
9450 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
9451 _assert(errno == ENOENT);
9454 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
9456 /* APT Initialization {{{ */
9457 _assert(pkgInitConfig(*_config));
9458 _assert(pkgInitSystem(*_config, _system));
9460 _config->Set("Acquire::AllowInsecureRepositories", true);
9461 _config->Set("Acquire::Check-Valid-Until", false);
9462 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
9464 _config->Set("pkgCacheGen::ForceEssential", "");
9466 if (translation != NULL)
9467 _config->Set("APT::Acquire::Translation", translation);
9468 _config->Set("Acquire::Languages", languages);
9470 // XXX: this timeout might be important :(
9471 //_config->Set("Acquire::http::Timeout", 15);
9474 size = sizeof(usermem);
9475 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
9477 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
9479 mkdir([Cache("archives") UTF8String], 0755);
9480 mkdir([Cache("archives/partial") UTF8String], 0755);
9481 _config->Set("Dir::Cache", [Cache_ UTF8String]);
9483 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
9484 _config->Set("Dir::State", [Cache_ UTF8String]);
9486 mkdir([Cache("lists") UTF8String], 0755);
9487 mkdir([Cache("lists/partial") UTF8String], 0755);
9488 mkdir([Cache("periodic") UTF8String], 0755);
9489 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
9491 std::string logs("/var/mobile/Library/Logs/Cydia");
9492 mkdir(logs.c_str(), 0755);
9493 _config->Set("Dir::Log", logs);
9495 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
9497 /* Color Choices {{{ */
9498 space_ = CGColorSpaceCreateDeviceRGB();
9500 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9501 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9502 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9503 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
9504 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9505 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9506 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9507 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9508 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9509 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9511 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9512 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9514 /* UIKit Configuration {{{ */
9515 // XXX: I have a feeling this was important
9516 //UIKeyboardDisableAutomaticAppearance();
9519 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
9520 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
9522 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
9523 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
9524 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
9526 PulseInterval_ = fast ? 50000 : 500000;
9528 Colon_ = UCLocalize("COLON_DELIMITED");
9529 Elision_ = UCLocalize("ELISION");
9530 Error_ = UCLocalize("ERROR");
9531 Warning_ = UCLocalize("WARNING");
9534 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9536 CGColorSpaceRelease(space_);