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 static CGFloat CYStatusBarHeight() {
276 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
277 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
280 /* NSForcedOrderingSearch doesn't work on the iPhone */
281 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
282 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
283 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
285 /* Insertion Sort {{{ */
287 template <typename Type_>
288 size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
289 const char *ptr = (const char *)list;
291 size_t half = count / 2;
292 const char *probe = ptr + sizeof(Type_) * half;
293 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
294 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
295 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
296 count = (cr < 0) ? half : (half + (count & 1) - 1);
298 return (ptr - (const char *)list) / sizeof(Type_);
301 template <typename Type_>
302 void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
306 #if HistogramInsertionSort > 0
307 uint32_t total(0), *offsets(new uint32_t[length]);
310 for (size_t index(1); index != length; ++index) {
311 Type_ value(values[index]);
313 size_t correct(CFBSearch_(value, values, index, comparator, context));
315 size_t correct(index);
316 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
317 #if HistogramInsertionSort > 1
318 NSLog(@"%@ < %@", value, values[correct - 1]);
322 if (index - correct >= 8) {
323 correct = CFBSearch_(value, values, correct, comparator, context);
328 if (correct != index) {
329 size_t offset(index - correct);
330 #if HistogramInsertionSort
334 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
336 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
337 values[correct] = value;
341 #if HistogramInsertionSort > 0
342 for (size_t index(0); index != range.length; ++index)
343 if (offsets[index] != 0)
344 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
345 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
352 /* Cydia NSString Additions {{{ */
353 @interface NSString (Cydia)
354 - (NSComparisonResult) compareByPath:(NSString *)other;
355 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
358 @implementation NSString (Cydia)
360 - (NSComparisonResult) compareByPath:(NSString *)other {
361 NSString *prefix = [self commonPrefixWithString:other options:0];
362 size_t length = [prefix length];
364 NSRange lrange = NSMakeRange(length, [self length] - length);
365 NSRange rrange = NSMakeRange(length, [other length] - length);
367 lrange = [self rangeOfString:@"/" options:0 range:lrange];
368 rrange = [other rangeOfString:@"/" options:0 range:rrange];
370 NSComparisonResult value;
372 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
373 value = NSOrderedSame;
374 else if (lrange.location == NSNotFound)
375 value = NSOrderedAscending;
376 else if (rrange.location == NSNotFound)
377 value = NSOrderedDescending;
379 value = NSOrderedSame;
381 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
382 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
383 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
384 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
386 NSComparisonResult result = [lpath compare:rpath];
387 return result == NSOrderedSame ? value : result;
390 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
391 return [(id)CFURLCreateStringByAddingPercentEscapes(
396 kCFStringEncodingUTF8
403 /* C++ NSString Wrapper Cache {{{ */
404 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
405 return size == 0 ? NULL :
406 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
407 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
410 static _finline CFStringRef CYStringCreate(const std::string &data) {
411 return CYStringCreate(data.data(), data.size());
414 static _finline CFStringRef CYStringCreate(const char *data) {
415 return CYStringCreate(data, strlen(data));
424 _finline void clear_() {
425 if (cache_ != NULL) {
432 _finline bool empty() const {
436 _finline size_t size() const {
440 _finline char *data() const {
444 _finline void clear() {
449 _finline CYString() :
456 _finline ~CYString() {
460 void operator =(const CYString &rhs) {
464 if (rhs.cache_ == nil)
467 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
470 void copy(CYPool *pool) {
471 char *temp(pool->malloc<char>(size_ + 1));
472 memcpy(temp, data_, size_);
477 void set(CYPool *pool, const char *data, size_t size) {
483 data_ = const_cast<char *>(data);
491 _finline void set(CYPool *pool, const char *data) {
492 set(pool, data, data == NULL ? 0 : strlen(data));
495 _finline void set(CYPool *pool, const std::string &rhs) {
496 set(pool, rhs.data(), rhs.size());
499 bool operator ==(const CYString &rhs) const {
500 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
503 _finline operator CFStringRef() {
505 cache_ = CYStringCreate(data_, size_);
509 _finline operator id() {
510 return (NSString *) static_cast<CFStringRef>(*this);
513 _finline operator const char *() {
514 return reinterpret_cast<const char *>(data_);
518 /* C++ NSString Algorithm Adapters {{{ */
520 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
523 struct NSStringMapHash :
524 std::unary_function<NSString *, size_t>
526 _finline size_t operator ()(NSString *value) const {
527 return CFStringHashNSString((CFStringRef) value);
531 struct NSStringMapLess :
532 std::binary_function<NSString *, NSString *, bool>
534 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
535 return [lhs compare:rhs] == NSOrderedAscending;
539 struct NSStringMapEqual :
540 std::binary_function<NSString *, NSString *, bool>
542 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
543 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
544 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
545 //[lhs isEqualToString:rhs];
550 /* CoreGraphics Primitives {{{ */
555 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
556 CGFloat color[] = {red, green, blue, alpha};
557 return CGColorCreate(space, color);
566 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
567 color_(Create_(space, red, green, blue, alpha))
569 Set(space, red, green, blue, alpha);
574 CGColorRelease(color_);
581 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
583 color_ = Create_(space, red, green, blue, alpha);
586 operator CGColorRef() {
592 /* Random Global Variables {{{ */
593 static int PulseInterval_ = 500000;
595 static const NSString *UI_;
598 static bool RestartSubstrate_;
599 static NSArray *Finishes_;
601 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
602 #define NotifyConfig_ "/etc/notify.conf"
604 static bool Queuing_;
606 static CYColor Blue_;
607 static CYColor Blueish_;
608 static CYColor Black_;
609 static CYColor Folder_;
611 static CYColor White_;
612 static CYColor Gray_;
613 static CYColor Green_;
614 static CYColor Purple_;
615 static CYColor Purplish_;
617 static UIColor *InstallingColor_;
618 static UIColor *RemovingColor_;
620 static NSString *App_;
622 static BOOL Advanced_;
623 static BOOL Ignored_;
625 static _H<UIFont> Font12_;
626 static _H<UIFont> Font12Bold_;
627 static _H<UIFont> Font14_;
628 static _H<UIFont> Font18_;
629 static _H<UIFont> Font18Bold_;
630 static _H<UIFont> Font22Bold_;
632 static _H<NSString> UniqueID_;
634 static _H<NSLocale> CollationLocale_;
635 static _H<NSArray> CollationThumbs_;
636 static std::vector<NSInteger> CollationOffset_;
637 static _H<NSArray> CollationTitles_;
638 static _H<NSArray> CollationStarts_;
639 static UTransliterator *CollationTransl_;
640 //static Function<NSString *, NSString *> CollationModify_;
642 typedef std::basic_string<UChar> ustring;
643 static ustring CollationString_;
645 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
646 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
647 static struct UReplaceableCallbacks CollationUCalls_ = {
648 .length = [](const UReplaceable *rep) -> int32_t { CUC;
652 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
653 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
654 if (offset >= str.size())
659 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
660 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
661 if (offset >= str.size())
664 U16_GET(str.data(), 0, offset, str.size(), c);
668 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
669 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
670 str.replace(start, limit - start, text, length);
673 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
674 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
675 str.copy(dst, limit - start, start);
678 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
679 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
680 str.replace(dest, 0, str, start, limit - start);
684 static CFLocaleRef Locale_;
685 static NSArray *Languages_;
686 static CGColorSpaceRef space_;
688 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
689 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
691 static NSDictionary *SectionMap_;
692 static _H<NSDate> Backgrounded_;
693 static _transient NSMutableDictionary *Values_;
694 static _transient NSMutableDictionary *Sections_;
695 _H<NSMutableDictionary> Sources_;
696 static _transient NSNumber *Version_;
699 static _H<NSString> Firmware_;
700 static NSString *Major_;
702 static _H<NSMutableDictionary> SessionData_;
703 static _H<NSMutableSet> BridgedHosts_;
704 static _H<NSMutableSet> InsecureHosts_;
706 static NSString *kCydiaProgressEventTypeError = @"Error";
707 static NSString *kCydiaProgressEventTypeInformation = @"Information";
708 static NSString *kCydiaProgressEventTypeStatus = @"Status";
709 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
712 /* Display Helpers {{{ */
713 inline float Interpolate(float begin, float end, float fraction) {
714 return (end - begin) * fraction + begin;
717 static inline double Retina(double value) {
718 value *= ScreenScale_;
719 value = round(value);
720 value /= ScreenScale_;
724 static inline CGRect Retina(CGRect value) {
725 value.origin.x *= ScreenScale_;
726 value.origin.y *= ScreenScale_;
727 value.size.width *= ScreenScale_;
728 value.size.height *= ScreenScale_;
729 value = CGRectIntegral(value);
730 value.origin.x /= ScreenScale_;
731 value.origin.y /= ScreenScale_;
732 value.size.width /= ScreenScale_;
733 value.size.height /= ScreenScale_;
737 static _finline const char *StripVersion_(const char *version) {
738 const char *colon(strchr(version, ':'));
739 return colon == NULL ? version : colon + 1;
742 NSString *LocalizeSection(NSString *section) {
743 static RegEx title_r("(.*?) \\((.*)\\)");
744 if (title_r(section)) {
745 NSString *parent(title_r[1]);
746 NSString *child(title_r[2]);
748 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
749 LocalizeSection(parent),
750 LocalizeSection(child)
754 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
757 NSString *Simplify(NSString *title) {
758 const char *data = [title UTF8String];
759 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
761 static RegEx square_r("\\[(.*)\\]");
762 if (square_r(data, size))
763 return Simplify(square_r[1]);
765 static RegEx paren_r("\\((.*)\\)");
766 if (paren_r(data, size))
767 return Simplify(paren_r[1]);
769 static RegEx title_r("(.*?) \\((.*)\\)");
770 if (title_r(data, size))
771 return Simplify(title_r[1]);
777 bool isSectionVisible(NSString *section) {
778 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
779 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
780 return hidden == nil || ![hidden boolValue];
783 static NSString *VerifySource(NSString *href) {
784 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
786 [[[[UIAlertView alloc]
787 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
788 message:UCLocalize("INVALID_URL_EX")
790 cancelButtonTitle:UCLocalize("OK")
791 otherButtonTitles:nil
792 ] autorelease] show];
797 if (![href hasSuffix:@"/"])
798 href = [href stringByAppendingString:@"/"];
804 /* Delegate Prototypes {{{ */
807 @class CydiaProgressEvent;
809 @protocol DatabaseDelegate
810 - (void) repairWithSelector:(SEL)selector;
811 - (void) setConfigurationData:(NSString *)data;
812 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
815 @class CYPackageController;
817 @protocol SourceDelegate
818 - (void) setFetch:(NSNumber *)fetch;
821 @protocol FetchDelegate
822 - (bool) isSourceCancelled;
823 - (void) startSourceFetch:(NSString *)uri;
824 - (void) stopSourceFetch:(NSString *)uri;
827 @protocol CydiaDelegate
828 - (void) returnToCydia;
830 - (void) retainNetworkActivityIndicator;
831 - (void) releaseNetworkActivityIndicator;
832 - (void) clearPackage:(Package *)package;
833 - (void) installPackage:(Package *)package;
834 - (void) installPackages:(NSArray *)packages;
835 - (void) removePackage:(Package *)package;
836 - (void) beginUpdate;
838 - (bool) requestUpdate;
839 - (void) distUpgrade;
842 - (void) _saveConfig;
844 - (void) addSource:(NSDictionary *)source;
845 - (BOOL) addTrivialSource:(NSString *)href;
846 - (UIProgressHUD *) addProgressHUD;
847 - (void) removeProgressHUD:(UIProgressHUD *)hud;
848 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
849 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
853 /* CancelStatus {{{ */
855 public pkgAcquireStatus
866 virtual bool MediaChange(std::string media, std::string drive) {
870 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
874 virtual bool Pulse_(pkgAcquire *Owner) = 0;
876 virtual bool Pulse(pkgAcquire *Owner) {
877 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
885 _finline bool WasCancelled() const {
890 /* DelegateStatus {{{ */
895 _transient NSObject<ProgressDelegate> *delegate_;
903 void setDelegate(NSObject<ProgressDelegate> *delegate) {
904 delegate_ = delegate;
907 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
908 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
909 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
910 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
913 virtual void Done(pkgAcquire::ItemDesc &desc) {
914 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
915 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
916 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
919 virtual void Fail(pkgAcquire::ItemDesc &desc) {
921 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
922 desc.Owner->Status == pkgAcquire::Item::StatDone
926 std::string &error(desc.Owner->ErrorText);
930 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
931 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
934 virtual bool Pulse_(pkgAcquire *Owner) {
936 double(CurrentBytes + CurrentItems) /
937 double(TotalBytes + TotalItems)
940 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
941 [NSNumber numberWithDouble:percent], @"Percent",
943 [NSNumber numberWithDouble:CurrentBytes], @"Current",
944 [NSNumber numberWithDouble:TotalBytes], @"Total",
945 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
946 nil] waitUntilDone:YES];
948 return ![delegate_ isProgressCancelled];
951 virtual void Start() {
952 pkgAcquireStatus::Start();
953 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
956 virtual void Stop() {
957 pkgAcquireStatus::Stop();
958 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
959 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
963 /* Database Interface {{{ */
964 typedef std::map< unsigned long, _H<Source> > SourceMap;
966 @interface Database : NSObject {
974 pkgDepCache::Policy *policy_;
975 pkgRecords *records_;
976 pkgProblemResolver *resolver_;
977 pkgAcquire *fetcher_;
979 SPtr<pkgPackageManager> manager_;
980 pkgSourceList *list_;
982 SourceMap sourceMap_;
983 _H<NSMutableArray> sourceList_;
985 _H<NSArray> packages_;
987 _transient NSObject<DatabaseDelegate> *delegate_;
988 _transient NSObject<ProgressDelegate> *progress_;
996 std::map<const char *, _H<NSString> > sections_;
999 + (Database *) sharedInstance;
1001 - (bool) hasPackages;
1003 - (void) _readCydia:(NSNumber *)fd;
1004 - (void) _readStatus:(NSNumber *)fd;
1005 - (void) _readOutput:(NSNumber *)fd;
1009 - (Package *) packageWithName:(NSString *)name;
1011 - (pkgCacheFile &) cache;
1012 - (pkgDepCache::Policy *) policy;
1013 - (pkgRecords *) records;
1014 - (pkgProblemResolver *) resolver;
1015 - (pkgAcquire &) fetcher;
1016 - (pkgSourceList &) list;
1017 - (NSArray *) packages;
1018 - (NSArray *) sources;
1019 - (Source *) sourceWithKey:(NSString *)key;
1020 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1028 - (void) updateWithStatus:(CancelStatus &)status;
1030 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1032 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1033 - (NSObject<ProgressDelegate> *) progressDelegate;
1035 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1036 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1037 - (void) resetFetch;
1039 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1043 /* SourceStatus {{{ */
1044 class SourceStatus :
1048 _transient NSObject<FetchDelegate> *delegate_;
1049 _transient Database *database_;
1050 std::set<std::string> fetches_;
1053 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1054 delegate_(delegate),
1059 void Set(bool fetch, const std::string &uri) {
1061 if (!fetches_.insert(uri).second)
1064 if (fetches_.erase(uri) == 0)
1068 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1070 auto slash(uri.rfind('/'));
1071 if (slash != std::string::npos)
1072 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1075 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1076 /*unsigned long ID(fetch ? 1 : 0);
1080 Set(fetch, item->DescURI());
1083 void Log(const char *tag, pkgAcquire::Item *item) {
1084 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1087 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1088 Log("Fetch", desc.Owner);
1089 Set(true, desc.Owner);
1092 virtual void Done(pkgAcquire::ItemDesc &desc) {
1093 Log("Done", desc.Owner);
1094 Set(false, desc.Owner);
1097 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1098 Log("Fail", desc.Owner);
1099 Set(false, desc.Owner);
1102 virtual bool Pulse_(pkgAcquire *Owner) {
1103 std::set<std::string> fetches;
1104 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1106 if ((*item)->QueueCounter == 0)
1108 else switch ((*item)->Status) {
1109 case pkgAcquire::Item::StatFetching:
1110 fetches.insert((*item)->DescURI());
1119 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1123 std::vector<std::string> stops;
1124 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1125 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1126 //printf("Stop(%s)\n", stop->c_str());
1130 return ![delegate_ isSourceCancelled];
1133 virtual void Stop() {
1134 pkgAcquireStatus::Stop();
1135 [database_ resetFetch];
1139 /* ProgressEvent Implementation {{{ */
1140 @implementation CydiaProgressEvent
1142 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1143 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1146 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1147 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1148 [event setPackage:package];
1152 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1153 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1155 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1156 NSArray *fields([description componentsSeparatedByString:@" "]);
1157 [event setItem:fields];
1159 if ([fields count] > 3) {
1160 [event setPackage:[fields objectAtIndex:2]];
1161 [event setVersion:[fields objectAtIndex:3]];
1164 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1169 + (NSArray *) _attributeKeys {
1170 return [NSArray arrayWithObjects:
1180 - (NSArray *) attributeKeys {
1181 return [[self class] _attributeKeys];
1184 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1185 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1188 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1189 if ((self = [super init]) != nil) {
1195 - (NSString *) message {
1199 - (NSString *) type {
1203 - (NSArray *) item {
1204 return (id) item_ ?: [NSNull null];
1207 - (void) setItem:(NSArray *)item {
1211 - (NSString *) package {
1212 return (id) package_ ?: [NSNull null];
1215 - (void) setPackage:(NSString *)package {
1219 - (NSString *) url {
1220 return (id) url_ ?: [NSNull null];
1223 - (void) setURL:(NSString *)url {
1227 - (void) setVersion:(NSString *)version {
1231 - (NSString *) version {
1232 return (id) version_ ?: [NSNull null];
1235 - (NSString *) compound:(NSString *)value {
1237 NSString *mode(nil); {
1238 NSString *type([self type]);
1239 if ([type isEqualToString:kCydiaProgressEventTypeError])
1240 mode = UCLocalize("ERROR");
1241 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1242 mode = UCLocalize("WARNING");
1246 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1252 - (NSString *) compoundMessage {
1253 return [self compound:[self message]];
1256 - (NSString *) compoundTitle {
1259 if (package_ == nil)
1261 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1262 title = [package name];
1266 return [self compound:title];
1272 // Cytore Definitions {{{
1273 struct PackageValue :
1276 Cytore::Offset<PackageValue> next_;
1278 uint32_t index_ : 23;
1279 uint32_t subscribed_ : 1;
1296 Cytore::Offset<PackageValue> packages_[1 << 16];
1299 static Cytore::File<MetaValue> MetaFile_;
1301 // Cytore Helper Functions {{{
1302 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1303 SplitHash nhash = { hashlittle(name, length) };
1305 PackageValue *metadata;
1307 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1308 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1309 *offset = MetaFile_.New<PackageValue>(length + 1);
1310 metadata = &MetaFile_.Get(*offset);
1312 if (metadata == NULL) {
1316 metadata = new PackageValue();
1317 memset(metadata, 0, sizeof(*metadata));
1320 memcpy(metadata->name_, name, length);
1321 metadata->name_[length] = '\0';
1322 metadata->nhash_ = nhash.u16[1];
1324 metadata = &MetaFile_.Get(*offset);
1325 if (metadata->nhash_ != nhash.u16[1])
1327 if (strncmp(metadata->name_, name, length) != 0)
1329 if (metadata->name_[length] != '\0')
1336 static void PackageImport(const void *key, const void *value, void *context) {
1337 bool &fail(*reinterpret_cast<bool *>(context));
1340 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1341 NSLog(@"failed to import package %@", key);
1345 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1346 NSDictionary *package((NSDictionary *) value);
1348 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1349 if ([subscribed boolValue] && !metadata->subscribed_)
1350 metadata->subscribed_ = true;
1352 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1353 time_t time([date timeIntervalSince1970]);
1354 if (metadata->first_ > time || metadata->first_ == 0)
1355 metadata->first_ = time;
1358 NSDate *date([package objectForKey:@"LastSeen"]);
1359 NSString *version([package objectForKey:@"LastVersion"]);
1361 if (date != nil && version != nil) {
1362 time_t time([date timeIntervalSince1970]);
1363 if (metadata->last_ < time || metadata->last_ == 0)
1364 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1365 size_t length(strlen(buffer));
1366 uint16_t vhash(hashlittle(buffer, length));
1368 size_t capped(std::min<size_t>(8, length));
1369 char *latest(buffer + length - capped);
1371 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1372 metadata->vhash_ = vhash;
1374 metadata->last_ = time;
1380 static NSDate *GetStatusDate() {
1381 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1384 static void SaveConfig(NSObject *lock) {
1385 @synchronized (lock) {
1391 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1392 Values_, @"CydiaValues",
1393 Sections_, @"CydiaSections",
1394 (id) Sources_, @"CydiaSources",
1395 Version_, @"CydiaVersion",
1396 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1398 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1399 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1401 CydiaWriteSources();
1404 /* Source Class {{{ */
1405 @interface Source : NSObject {
1407 Database *database_;
1410 CYString depiction_;
1411 CYString description_;
1417 CYString distribution_;
1423 _H<NSString> authority_;
1425 CYString defaultIcon_;
1427 _H<NSMutableDictionary> record_;
1430 std::set<std::string> fetches_;
1431 std::set<std::string> files_;
1432 _transient NSObject<SourceDelegate> *delegate_;
1435 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1437 - (NSComparisonResult) compareByName:(Source *)source;
1439 - (NSString *) depictionForPackage:(NSString *)package;
1440 - (NSString *) supportForPackage:(NSString *)package;
1442 - (metaIndex *) metaIndex;
1443 - (NSDictionary *) record;
1446 - (NSString *) rooturi;
1447 - (NSString *) distribution;
1448 - (NSString *) type;
1451 - (NSString *) host;
1453 - (NSString *) name;
1454 - (NSString *) shortDescription;
1455 - (NSString *) label;
1456 - (NSString *) origin;
1457 - (NSString *) version;
1459 - (NSString *) defaultIcon;
1460 - (NSURL *) iconURL;
1462 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1463 - (void) resetFetch;
1467 @implementation Source
1469 + (NSString *) webScriptNameForSelector:(SEL)selector {
1471 else if (selector == @selector(addSection:))
1472 return @"addSection";
1473 else if (selector == @selector(getField:))
1475 else if (selector == @selector(removeSection:))
1476 return @"removeSection";
1477 else if (selector == @selector(remove))
1483 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1484 return [self webScriptNameForSelector:selector] == nil;
1487 + (NSArray *) _attributeKeys {
1488 return [NSArray arrayWithObjects:
1499 @"shortDescription",
1506 - (NSArray *) attributeKeys {
1507 return [[self class] _attributeKeys];
1510 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1511 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1514 - (metaIndex *) metaIndex {
1518 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1519 trusted_ = index->IsTrusted();
1521 uri_.set(pool, index->GetURI());
1522 distribution_.set(pool, index->GetDist());
1523 type_.set(pool, index->GetType());
1525 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1526 if (dindex != NULL) {
1527 std::string file(dindex->MetaIndexURI(""));
1528 base_.set(pool, file);
1531 _profile(Source$setMetaIndex$GetIndexes)
1532 dindex->GetIndexes(&acquire, true);
1534 _profile(Source$setMetaIndex$DescURI)
1535 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1536 std::string file((*item)->DescURI());
1537 auto slash(file.rfind('/'));
1538 if (slash == std::string::npos)
1540 files_.insert(file.substr(0, slash));
1545 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1548 pkgTagFile tags(&fd);
1550 pkgTagSection section;
1557 {"default-icon", &defaultIcon_},
1558 {"depiction", &depiction_},
1559 {"description", &description_},
1561 {"origin", &origin_},
1562 {"support", &support_},
1563 {"version", &version_},
1566 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1567 const char *start, *end;
1569 if (section.Find(names[i].name_, start, end)) {
1570 CYString &value(*names[i].value_);
1571 value.set(pool, start, end - start);
1577 record_ = [Sources_ objectForKey:[self key]];
1579 NSURL *url([NSURL URLWithString:uri_]);
1583 host_ = [host_ lowercaseString];
1588 authority_ = [url path];
1591 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1592 if ((self = [super init]) != nil) {
1593 era_ = [database era];
1594 database_ = database;
1597 _profile(Source$initWithMetaIndex$setMetaIndex)
1598 [self setMetaIndex:index inPool:pool];
1603 - (NSString *) getField:(NSString *)name {
1604 @synchronized (database_) {
1605 if ([database_ era] != era_ || index_ == NULL)
1608 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1613 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1618 pkgTagFile tags(&fd);
1620 pkgTagSection section;
1623 const char *start, *end;
1624 if (!section.Find([name UTF8String], start, end))
1625 return (NSString *) [NSNull null];
1627 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1630 - (NSComparisonResult) compareByName:(Source *)source {
1631 NSString *lhs = [self name];
1632 NSString *rhs = [source name];
1634 if ([lhs length] != 0 && [rhs length] != 0) {
1635 unichar lhc = [lhs characterAtIndex:0];
1636 unichar rhc = [rhs characterAtIndex:0];
1638 if (isalpha(lhc) && !isalpha(rhc))
1639 return NSOrderedAscending;
1640 else if (!isalpha(lhc) && isalpha(rhc))
1641 return NSOrderedDescending;
1644 return [lhs compare:rhs options:LaxCompareOptions_];
1647 - (NSString *) depictionForPackage:(NSString *)package {
1648 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1651 - (NSString *) supportForPackage:(NSString *)package {
1652 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1655 - (NSArray *) sections {
1656 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1659 - (void) _addSection:(NSString *)section {
1662 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1663 if (![sections containsObject:section])
1664 [sections addObject:section];
1666 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1669 - (bool) addSection:(NSString *)section {
1673 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1677 - (void) _removeSection:(NSString *)section {
1681 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1682 if ([sections containsObject:section])
1683 [sections removeObject:section];
1686 - (bool) removeSection:(NSString *)section {
1690 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1695 [Sources_ removeObjectForKey:[self key]];
1699 bool value(record_ != nil);
1700 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1704 - (NSDictionary *) record {
1712 - (NSString *) rooturi {
1716 - (NSString *) distribution {
1717 return distribution_;
1720 - (NSString *) type {
1724 - (NSString *) baseuri {
1725 return base_.empty() ? nil : (id) base_;
1728 - (NSString *) iconuri {
1729 if (NSString *base = [self baseuri])
1730 return [base stringByAppendingString:@"CydiaIcon.png"];
1735 - (NSURL *) iconURL {
1736 if (NSString *uri = [self iconuri])
1737 return [NSURL URLWithString:uri];
1741 - (NSString *) key {
1742 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1745 - (NSString *) host {
1749 - (NSString *) name {
1750 return origin_.empty() ? (id) authority_ : origin_;
1753 - (NSString *) shortDescription {
1754 return description_;
1757 - (NSString *) label {
1758 return label_.empty() ? (id) authority_ : label_;
1761 - (NSString *) origin {
1765 - (NSString *) version {
1769 - (NSString *) defaultIcon {
1770 return defaultIcon_;
1773 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1774 delegate_ = delegate;
1778 return !fetches_.empty();
1781 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1783 if (fetches_.erase(uri) == 0)
1785 } else if (files_.find(uri) == files_.end())
1787 else if (!fetches_.insert(uri).second)
1790 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1793 - (void) resetFetch {
1795 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1800 /* CydiaOperation Class {{{ */
1801 @interface CydiaOperation : NSObject {
1802 _H<NSString> operator_;
1803 _H<NSString> value_;
1806 - (NSString *) operator;
1807 - (NSString *) value;
1811 @implementation CydiaOperation
1813 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1814 if ((self = [super init]) != nil) {
1815 operator_ = [NSString stringWithUTF8String:_operator];
1816 value_ = [NSString stringWithUTF8String:value];
1820 + (NSArray *) _attributeKeys {
1821 return [NSArray arrayWithObjects:
1827 - (NSArray *) attributeKeys {
1828 return [[self class] _attributeKeys];
1831 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1832 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1835 - (NSString *) operator {
1839 - (NSString *) value {
1845 /* CydiaClause Class {{{ */
1846 @interface CydiaClause : NSObject {
1847 _H<NSString> package_;
1848 _H<CydiaOperation> version_;
1851 - (NSString *) package;
1852 - (CydiaOperation *) version;
1856 @implementation CydiaClause
1858 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1859 if ((self = [super init]) != nil) {
1860 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1862 if (const char *version = dep.TargetVer())
1863 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1865 version_ = (id) [NSNull null];
1869 + (NSArray *) _attributeKeys {
1870 return [NSArray arrayWithObjects:
1876 - (NSArray *) attributeKeys {
1877 return [[self class] _attributeKeys];
1880 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1881 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1884 - (NSString *) package {
1888 - (CydiaOperation *) version {
1894 /* CydiaRelation Class {{{ */
1895 @interface CydiaRelation : NSObject {
1896 _H<NSString> relationship_;
1897 _H<NSMutableArray> clauses_;
1900 - (NSString *) relationship;
1901 - (NSArray *) clauses;
1905 @implementation CydiaRelation
1907 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1908 if ((self = [super init]) != nil) {
1909 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1910 clauses_ = [NSMutableArray arrayWithCapacity:8];
1912 pkgCache::DepIterator start;
1913 pkgCache::DepIterator end;
1914 dep.GlobOr(start, end); // ++dep
1917 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1919 // yes, seriously. (wtf?)
1927 + (NSArray *) _attributeKeys {
1928 return [NSArray arrayWithObjects:
1934 - (NSArray *) attributeKeys {
1935 return [[self class] _attributeKeys];
1938 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1939 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1942 - (NSString *) relationship {
1943 return relationship_;
1946 - (NSArray *) clauses {
1950 - (void) addClause:(CydiaClause *)clause {
1951 [clauses_ addObject:clause];
1956 /* Package Class {{{ */
1957 struct ParsedPackage {
1961 CYString architecture_;
1964 CYString depiction_;
1971 @interface Package : NSObject {
1973 @public uint32_t role_ : 3;
1974 uint32_t essential_ : 1;
1975 uint32_t obsolete_ : 1;
1976 uint32_t ignored_ : 1;
1977 uint32_t pooled_ : 1;
1983 _transient Database *database_;
1985 pkgCache::VerIterator version_;
1986 pkgCache::PkgIterator iterator_;
1987 pkgCache::VerFileIterator file_;
1991 CYString transform_;
1994 CYString installed_;
1997 const char *section_;
1998 _transient NSString *section$_;
2002 PackageValue *metadata_;
2003 ParsedPackage *parsed_;
2005 _H<NSMutableArray> tags_;
2008 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2009 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2011 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2013 - (pkgCache::PkgIterator) iterator;
2016 - (NSString *) section;
2017 - (NSString *) simpleSection;
2019 - (NSString *) longSection;
2020 - (NSString *) shortSection;
2024 - (MIMEAddress *) maintainer;
2026 - (NSString *) longDescription;
2027 - (NSString *) shortDescription;
2030 - (PackageValue *) metadata;
2033 - (bool) subscribed;
2034 - (bool) setSubscribed:(bool)subscribed;
2038 - (NSString *) latest;
2039 - (NSString *) installed;
2040 - (BOOL) uninstalled;
2042 - (BOOL) upgradableAndEssential:(BOOL)essential;
2045 - (BOOL) unfiltered;
2049 - (BOOL) halfConfigured;
2050 - (BOOL) halfInstalled;
2052 - (NSString *) mode;
2055 - (NSString *) name;
2057 - (NSString *) homepage;
2058 - (NSString *) depiction;
2059 - (MIMEAddress *) author;
2061 - (NSString *) support;
2063 - (NSArray *) files;
2064 - (NSArray *) warnings;
2065 - (NSArray *) applications;
2067 - (Source *) source;
2070 - (BOOL) matches:(NSArray *)query;
2072 - (BOOL) hasTag:(NSString *)tag;
2073 - (NSString *) primaryPurpose;
2074 - (NSArray *) purposes;
2075 - (bool) isCommercial;
2077 - (void) setIndex:(size_t)index;
2079 - (CYString &) cyname;
2081 - (uint32_t) compareBySection:(NSArray *)sections;
2088 uint32_t PackageChangesRadix(Package *self, void *) {
2093 uint32_t timestamp : 30;
2094 uint32_t ignored : 1;
2095 uint32_t upgradable : 1;
2099 bool upgradable([self upgradableAndEssential:YES]);
2100 value.bits.upgradable = upgradable ? 1 : 0;
2103 value.bits.timestamp = 0;
2104 value.bits.ignored = [self ignored] ? 0 : 1;
2105 value.bits.upgradable = 1;
2107 value.bits.timestamp = [self seen] >> 2;
2108 value.bits.ignored = 0;
2109 value.bits.upgradable = 0;
2112 return _not(uint32_t) - value.key;
2115 CYString &(*PackageName)(Package *self, SEL sel);
2117 uint32_t PackagePrefixRadix(Package *self, void *context) {
2118 size_t offset(reinterpret_cast<size_t>(context));
2119 CYString &name(PackageName(self, @selector(cyname)));
2121 size_t size(name.size());
2124 char *text(name.data());
2127 if (!isdigit(text[0]))
2131 while (size != digits && isdigit(text[digits]))
2139 if (offset == 0 && zeros != 0) {
2140 memset(data, '0', zeros);
2141 memcpy(data + zeros, text, 4 - zeros);
2143 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2144 if (size <= offset - zeros)
2147 text += offset - zeros;
2148 size -= offset - zeros;
2151 memcpy(data, text, 4);
2153 memcpy(data, text, size);
2154 memset(data + size, 0, 4 - size);
2157 for (size_t i(0); i != 4; ++i)
2158 if (isalpha(data[i]))
2166 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2168 /* XXX: ntohl may be more honest */
2169 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2172 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2173 _profile(PackageNameCompare)
2175 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2176 else if (rhn == NULL)
2177 return kCFCompareGreaterThan;
2179 CFIndex length(CFStringGetLength(lhn));
2181 _profile(PackageNameCompare$NumbersLast)
2182 if (length != 0 && CFStringGetLength(rhn) != 0) {
2183 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2184 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2185 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2186 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2187 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2191 _profile(PackageNameCompare$Compare)
2192 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2197 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2198 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2201 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2202 CYString &lhn(PackageName(lhs, @selector(cyname)));
2203 NSString *rhn(PackageName(rhs, @selector(cyname)));
2204 return StringNameCompare(lhn, rhn, lhn.size());
2207 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2208 return PackageNameCompare(*lhs, *rhs, arg);
2211 struct PackageNameOrdering :
2212 std::binary_function<Package *, Package *, bool>
2214 _finline bool operator ()(Package *lhs, Package *rhs) const {
2215 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2219 @implementation Package
2221 - (NSString *) description {
2222 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2228 if (parsed_ != NULL)
2233 + (NSString *) webScriptNameForSelector:(SEL)selector {
2235 else if (selector == @selector(clear))
2237 else if (selector == @selector(getField:))
2239 else if (selector == @selector(getRecord))
2240 return @"getRecord";
2241 else if (selector == @selector(hasTag:))
2243 else if (selector == @selector(install))
2245 else if (selector == @selector(remove))
2251 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2252 return [self webScriptNameForSelector:selector] == nil;
2255 + (NSArray *) _attributeKeys {
2256 return [NSArray arrayWithObjects:
2277 @"shortDescription",
2290 - (NSArray *) attributeKeys {
2291 return [[self class] _attributeKeys];
2294 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2295 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2298 - (NSArray *) relations {
2299 @synchronized (database_) {
2300 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2301 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2302 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2306 - (NSString *) architecture {
2308 @synchronized (database_) {
2309 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2312 - (NSString *) getField:(NSString *)name {
2313 @synchronized (database_) {
2314 if ([database_ era] != era_ || file_.end())
2317 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2319 const char *start, *end;
2320 if (!parser.Find([name UTF8String], start, end))
2321 return (NSString *) [NSNull null];
2323 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2326 - (NSString *) getRecord {
2327 @synchronized (database_) {
2328 if ([database_ era] != era_ || file_.end())
2331 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2333 const char *start, *end;
2334 parser.GetRec(start, end);
2336 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2340 if (parsed_ != NULL)
2342 @synchronized (database_) {
2343 if ([database_ era] != era_ || file_.end())
2346 ParsedPackage *parsed(new ParsedPackage);
2349 _profile(Package$parse)
2350 pkgRecords::Parser *parser;
2352 _profile(Package$parse$Lookup)
2353 parser = &[database_ records]->Lookup(file_);
2359 _profile(Package$parse$Find)
2364 {"architecture", &parsed->architecture_},
2365 {"icon", &parsed->icon_},
2366 {"depiction", &parsed->depiction_},
2367 {"homepage", &parsed->homepage_},
2368 {"website", &website},
2370 {"support", &parsed->support_},
2371 {"author", &parsed->author_},
2372 {"md5sum", &parsed->md5sum_},
2375 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2376 const char *start, *end;
2378 if (parser->Find(names[i].name_, start, end)) {
2379 CYString &value(*names[i].value_);
2380 _profile(Package$parse$Value)
2381 value.set(pool_, start, end - start);
2387 _profile(Package$parse$Tagline)
2388 parsed->tagline_.set(pool_, parser->ShortDesc());
2391 _profile(Package$parse$Retain)
2392 if (parsed->homepage_.empty())
2393 parsed->homepage_ = website;
2394 if (parsed->homepage_ == parsed->depiction_)
2395 parsed->homepage_.clear();
2396 if (parsed->support_.empty())
2397 parsed->support_ = bugs;
2402 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2403 if ((self = [super init]) != nil) {
2404 _profile(Package$initWithVersion)
2406 pool_ = new CYPool();
2412 database_ = database;
2413 era_ = [database era];
2417 pkgCache::PkgIterator iterator(version_.ParentPkg());
2418 iterator_ = iterator;
2420 _profile(Package$initWithVersion$Version)
2421 file_ = version_.FileList();
2424 _profile(Package$initWithVersion$Cache)
2425 name_.set(NULL, version_.Display());
2427 latest_.set(NULL, StripVersion_(version_.VerStr()));
2429 pkgCache::VerIterator current(iterator.CurrentVer());
2431 installed_.set(NULL, StripVersion_(current.VerStr()));
2434 _profile(Package$initWithVersion$Transliterate) do {
2435 if (CollationTransl_ == NULL)
2440 _profile(Package$initWithVersion$Transliterate$utf8)
2441 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2442 for (size_t i(0), e(name_.size()); i != e; ++i)
2443 if (data[i] >= 0x80)
2448 UErrorCode code(U_ZERO_ERROR);
2451 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2452 CollationString_.resize(name_.size());
2453 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2454 if (!U_SUCCESS(code))
2456 CollationString_.resize(length);
2459 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2460 length = CollationString_.size();
2461 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2462 if (!U_SUCCESS(code))
2464 _assert(CollationString_.size() == length);
2467 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2468 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2469 if (code == U_BUFFER_OVERFLOW_ERROR)
2470 code = U_ZERO_ERROR;
2471 else if (!U_SUCCESS(code))
2476 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2477 transform = pool_->malloc<char>(length);
2479 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2480 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2481 if (!U_SUCCESS(code))
2485 transform_.set(NULL, transform, length);
2486 } while (false); _end
2488 _profile(Package$initWithVersion$Tags)
2490 pkgCache::TagIterator tag(version_.TagList());
2492 pkgCache::TagIterator tag(iterator.TagList());
2495 tags_ = [NSMutableArray arrayWithCapacity:8];
2497 goto tag; for (; !tag.end(); ++tag) tag: {
2498 const char *name(tag.Name());
2499 NSString *string((NSString *) CYStringCreate(name));
2503 [tags_ addObject:[string autorelease]];
2505 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2506 if (strcmp(name + 6, "enduser") == 0)
2508 else if (strcmp(name + 6, "hacker") == 0)
2510 else if (strcmp(name + 6, "developer") == 0)
2512 else if (strcmp(name + 6, "cydia") == 0)
2518 if (strncmp(name, "cydia::", 7) == 0) {
2519 if (strcmp(name + 7, "essential") == 0)
2521 else if (strcmp(name + 7, "obsolete") == 0)
2528 _profile(Package$initWithVersion$Metadata)
2529 const char *mixed(iterator.Name());
2530 size_t size(strlen(mixed));
2531 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2532 char lower[prefix + size + 5 + 1];
2534 for (size_t i(0); i != size; ++i)
2535 lower[prefix + i] = mixed[i] | 0x20;
2537 if (!installed_.empty()) {
2538 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2539 memcpy(lower + prefix + size, ".list", 6);
2541 if (stat(lower, &info) != -1)
2542 upgraded_ = info.st_birthtime;
2545 PackageValue *metadata(PackageFind(lower + prefix, size));
2546 metadata_ = metadata;
2548 id_.set(NULL, metadata->name_, size);
2550 const char *latest(version_.VerStr());
2551 size_t length(strlen(latest));
2553 uint16_t vhash(hashlittle(latest, length));
2555 size_t capped(std::min<size_t>(8, length));
2556 latest = latest + length - capped;
2558 if (metadata->first_ == 0)
2559 metadata->first_ = now_;
2561 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2562 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2563 metadata->vhash_ = vhash;
2564 metadata->last_ = now_;
2565 } else if (metadata->last_ == 0)
2566 metadata->last_ = metadata->first_;
2569 _profile(Package$initWithVersion$Section)
2570 section_ = version_.Section();
2573 _profile(Package$initWithVersion$Flags)
2574 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2575 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2580 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2581 pkgCache::VerIterator version;
2583 _profile(Package$packageWithIterator$GetCandidateVer)
2584 version = [database policy]->GetCandidateVer(iterator);
2592 _profile(Package$packageWithIterator$Allocate)
2593 package = [Package allocWithZone:zone];
2596 _profile(Package$packageWithIterator$Initialize)
2598 initWithVersion:version
2608 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2609 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2610 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2613 - (pkgCache::PkgIterator) iterator {
2617 - (NSArray *) downgrades {
2618 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2620 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2621 if (version == version_)
2623 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2624 if ([package source] == nil)
2626 [versions addObject:package];
2632 - (NSString *) section {
2633 if (section$_ == nil) {
2634 if (section_ == NULL)
2637 _profile(Package$section$mappedSectionForPointer)
2638 section$_ = [database_ mappedSectionForPointer:section_];
2643 - (NSString *) simpleSection {
2644 if (NSString *section = [self section])
2645 return Simplify(section);
2650 - (NSString *) longSection {
2651 if (NSString *section = [self section])
2652 return LocalizeSection(section);
2657 - (NSString *) shortSection {
2658 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2661 - (NSString *) uri {
2664 pkgIndexFile *index;
2665 pkgCache::PkgFileIterator file(file_.File());
2666 if (![database_ list].FindIndex(file, index))
2668 return [NSString stringWithUTF8String:iterator_->Path];
2669 //return [NSString stringWithUTF8String:file.Site()];
2670 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2674 - (MIMEAddress *) maintainer {
2675 @synchronized (database_) {
2676 if ([database_ era] != era_ || file_.end())
2679 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2680 const std::string &maintainer(parser->Maintainer());
2681 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2684 - (NSString *) md5sum {
2685 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2689 @synchronized (database_) {
2690 if ([database_ era] != era_ || version_.end())
2693 return version_->InstalledSize;
2696 - (NSString *) longDescription {
2697 @synchronized (database_) {
2698 if ([database_ era] != era_ || file_.end())
2701 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2702 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2704 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2705 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2706 if ([lines count] < 2)
2709 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2710 for (size_t i(1), e([lines count]); i != e; ++i) {
2711 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2712 [trimmed addObject:trim];
2715 return [trimmed componentsJoinedByString:@"\n"];
2718 - (NSString *) shortDescription {
2719 if (parsed_ != NULL)
2720 return static_cast<NSString *>(parsed_->tagline_);
2722 @synchronized (database_) {
2723 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2724 std::string value(parser.ShortDesc());
2727 if (value.size() > 200)
2729 return [(id) CYStringCreate(value) autorelease];
2733 _profile(Package$index)
2734 CFStringRef name((CFStringRef) [self name]);
2735 if (CFStringGetLength(name) == 0)
2737 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2738 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2740 return toupper(character);
2744 - (PackageValue *) metadata {
2749 PackageValue *metadata([self metadata]);
2750 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2753 - (bool) subscribed {
2754 return [self metadata]->subscribed_;
2757 - (bool) setSubscribed:(bool)subscribed {
2758 PackageValue *metadata([self metadata]);
2759 if (metadata->subscribed_ == subscribed)
2761 metadata->subscribed_ = subscribed;
2769 - (NSString *) latest {
2773 - (NSString *) installed {
2777 - (BOOL) uninstalled {
2778 return installed_.empty();
2781 - (BOOL) upgradableAndEssential:(BOOL)essential {
2782 _profile(Package$upgradableAndEssential)
2783 pkgCache::VerIterator current(iterator_.CurrentVer());
2785 return essential && essential_;
2787 return version_ != current;
2791 - (BOOL) essential {
2796 return [database_ cache][iterator_].InstBroken();
2799 - (BOOL) unfiltered {
2800 _profile(Package$unfiltered$obsolete)
2801 if (_unlikely(obsolete_))
2805 _profile(Package$unfiltered$role)
2806 if (_unlikely(role_ > 3))
2814 if (![self unfiltered])
2819 _profile(Package$visible$section)
2820 section = [self section];
2823 _profile(Package$visible$isSectionVisible)
2824 if (!isSectionVisible(section))
2832 unsigned char current(iterator_->CurrentState);
2833 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2836 - (BOOL) halfConfigured {
2837 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2840 - (BOOL) halfInstalled {
2841 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2845 @synchronized (database_) {
2846 if ([database_ era] != era_ || iterator_.end())
2849 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2850 return state.Mode != pkgDepCache::ModeKeep;
2853 - (NSString *) mode {
2854 @synchronized (database_) {
2855 if ([database_ era] != era_ || iterator_.end())
2858 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2860 switch (state.Mode) {
2861 case pkgDepCache::ModeDelete:
2862 if ((state.iFlags & pkgDepCache::Purge) != 0)
2866 case pkgDepCache::ModeKeep:
2867 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2868 return @"REINSTALL";
2869 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2873 case pkgDepCache::ModeInstall:
2874 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2875 return @"REINSTALL";
2876 else*/ switch (state.Status) {
2878 return @"DOWNGRADE";
2884 return @"NEW_INSTALL";
2895 - (NSString *) name {
2896 return name_.empty() ? id_ : name_;
2899 - (UIImage *) icon {
2900 NSString *section = [self simpleSection];
2903 if (parsed_ != NULL)
2904 if (NSString *href = parsed_->icon_)
2905 if ([href hasPrefix:@"file:///"])
2906 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2907 if (icon == nil) if (section != nil)
2908 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2909 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2910 if ([dicon hasPrefix:@"file:///"])
2911 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2913 icon = [UIImage imageNamed:@"unknown.png"];
2917 - (NSString *) homepage {
2918 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2921 - (NSString *) depiction {
2922 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2925 - (MIMEAddress *) author {
2926 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2929 - (NSString *) support {
2930 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2933 - (NSArray *) files {
2934 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2935 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2938 fin.open([path UTF8String]);
2943 while (std::getline(fin, line))
2944 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2949 - (NSString *) state {
2950 @synchronized (database_) {
2951 if ([database_ era] != era_ || file_.end())
2954 switch (iterator_->CurrentState) {
2955 case pkgCache::State::NotInstalled:
2956 return @"NotInstalled";
2957 case pkgCache::State::UnPacked:
2959 case pkgCache::State::HalfConfigured:
2960 return @"HalfConfigured";
2961 case pkgCache::State::HalfInstalled:
2962 return @"HalfInstalled";
2963 case pkgCache::State::ConfigFiles:
2964 return @"ConfigFiles";
2965 case pkgCache::State::Installed:
2966 return @"Installed";
2967 case pkgCache::State::TriggersAwaited:
2968 return @"TriggersAwaited";
2969 case pkgCache::State::TriggersPending:
2970 return @"TriggersPending";
2973 return (NSString *) [NSNull null];
2976 - (NSString *) selection {
2977 @synchronized (database_) {
2978 if ([database_ era] != era_ || file_.end())
2981 switch (iterator_->SelectedState) {
2982 case pkgCache::State::Unknown:
2984 case pkgCache::State::Install:
2986 case pkgCache::State::Hold:
2988 case pkgCache::State::DeInstall:
2989 return @"DeInstall";
2990 case pkgCache::State::Purge:
2994 return (NSString *) [NSNull null];
2997 - (NSArray *) warnings {
2998 @synchronized (database_) {
2999 if ([database_ era] != era_ || file_.end())
3002 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3003 const char *name(iterator_.Name());
3005 size_t length(strlen(name));
3006 if (length < 2) invalid:
3007 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3008 else for (size_t i(0); i != length; ++i)
3010 /* XXX: technically this is not allowed */
3011 (name[i] < 'A' || name[i] > 'Z') &&
3012 (name[i] < 'a' || name[i] > 'z') &&
3013 (name[i] < '0' || name[i] > '9') &&
3014 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3017 if (strcmp(name, "cydia") != 0) {
3020 bool _private = false;
3022 bool dbstash = false;
3023 bool dsstore = false;
3025 bool repository = [[self section] isEqualToString:@"Repositories"];
3027 if (NSArray *files = [self files])
3028 for (NSString *file in files)
3029 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3031 else if (!user && [file isEqualToString:@"/User"])
3033 else if (!_private && [file isEqualToString:@"/private"])
3035 else if (!stash && [file isEqualToString:@"/var/stash"])
3037 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3039 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3042 /* XXX: this is not sensitive enough. only some folders are valid. */
3043 if (cydia && !repository)
3044 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3046 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3048 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3050 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3052 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3054 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3057 return [warnings count] == 0 ? nil : warnings;
3060 - (NSArray *) applications {
3061 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3063 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3065 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3066 if (NSArray *files = [self files])
3067 for (NSString *file in files)
3068 if (application_r(file)) {
3069 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3072 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3073 if (id == nil || [id isEqualToString:me])
3076 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3078 display = application_r[1];
3080 NSString *bundle([file stringByDeletingLastPathComponent]);
3081 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3082 // XXX: maybe this should check if this is really a string, not just for length
3083 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3085 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3087 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3088 [applications addObject:application];
3090 [application addObject:id];
3091 [application addObject:display];
3092 [application addObject:url];
3095 return [applications count] == 0 ? nil : applications;
3098 - (Source *) source {
3099 if (source_ == nil) {
3100 @synchronized (database_) {
3101 if ([database_ era] != era_ || file_.end())
3102 source_ = (Source *) [NSNull null];
3104 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3108 return source_ == (Source *) [NSNull null] ? nil : source_;
3111 - (time_t) upgraded {
3115 - (uint32_t) recent {
3116 return std::numeric_limits<uint32_t>::max() - upgraded_;
3123 - (BOOL) matches:(NSArray *)query {
3124 if (query == nil || [query count] == 0)
3133 string = [self name];
3134 length = [string length];
3137 for (NSString *term in query) {
3138 range = [string rangeOfString:term options:MatchCompareOptions_];
3139 if (range.location != NSNotFound)
3140 rank_ -= 6 * 1000000 / length;
3145 length = [string length];
3148 for (NSString *term in query) {
3149 range = [string rangeOfString:term options:MatchCompareOptions_];
3150 if (range.location != NSNotFound)
3151 rank_ -= 6 * 1000000 / length;
3155 string = [self shortDescription];
3156 length = [string length];
3157 NSUInteger stop(std::min<NSUInteger>(length, 200));
3160 for (NSString *term in query) {
3161 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3162 if (range.location != NSNotFound)
3163 rank_ -= 2 * 100000;
3169 - (NSArray *) tags {
3173 - (BOOL) hasTag:(NSString *)tag {
3174 return tags_ == nil ? NO : [tags_ containsObject:tag];
3177 - (NSString *) primaryPurpose {
3178 for (NSString *tag in (NSArray *) tags_)
3179 if ([tag hasPrefix:@"purpose::"])
3180 return [tag substringFromIndex:9];
3184 - (NSArray *) purposes {
3185 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3186 for (NSString *tag in (NSArray *) tags_)
3187 if ([tag hasPrefix:@"purpose::"])
3188 [purposes addObject:[tag substringFromIndex:9]];
3189 return [purposes count] == 0 ? nil : purposes;
3192 - (bool) isCommercial {
3193 return [self hasTag:@"cydia::commercial"];
3196 - (void) setIndex:(size_t)index {
3197 if (metadata_->index_ != index + 1)
3198 metadata_->index_ = index + 1;
3201 - (CYString &) cyname {
3202 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3205 - (uint32_t) compareBySection:(NSArray *)sections {
3206 NSString *section([self section]);
3207 for (size_t i(0), e([sections count]); i != e; ++i) {
3208 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3212 return _not(uint32_t);
3216 @synchronized (database_) {
3217 if ([database_ era] != era_ || file_.end())
3220 pkgProblemResolver *resolver = [database_ resolver];
3221 resolver->Clear(iterator_);
3223 pkgCacheFile &cache([database_ cache]);
3224 cache->SetReInstall(iterator_, false);
3225 cache->MarkKeep(iterator_, false);
3229 @synchronized (database_) {
3230 if ([database_ era] != era_ || file_.end())
3233 pkgProblemResolver *resolver = [database_ resolver];
3234 resolver->Clear(iterator_);
3235 resolver->Protect(iterator_);
3237 pkgCacheFile &cache([database_ cache]);
3238 cache->SetCandidateVersion(version_);
3239 cache->SetReInstall(iterator_, false);
3240 cache->MarkInstall(iterator_, false);
3242 pkgDepCache::StateCache &state((*cache)[iterator_]);
3243 if (!state.Install())
3244 cache->SetReInstall(iterator_, true);
3248 @synchronized (database_) {
3249 if ([database_ era] != era_ || file_.end())
3252 pkgProblemResolver *resolver = [database_ resolver];
3253 resolver->Clear(iterator_);
3254 resolver->Remove(iterator_);
3255 resolver->Protect(iterator_);
3257 pkgCacheFile &cache([database_ cache]);
3258 cache->SetReInstall(iterator_, false);
3259 cache->MarkDelete(iterator_, true);
3264 /* Section Class {{{ */
3265 @interface Section : NSObject {
3269 _H<NSString> localized_;
3272 - (NSComparisonResult) compareByLocalized:(Section *)section;
3273 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3274 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3275 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3277 - (NSString *) name;
3278 - (void) setName:(NSString *)name;
3284 - (void) addToCount;
3286 - (void) setCount:(size_t)count;
3287 - (NSString *) localized;
3291 @implementation Section
3293 - (NSComparisonResult) compareByLocalized:(Section *)section {
3294 NSString *lhs(localized_);
3295 NSString *rhs([section localized]);
3297 /*if ([lhs length] != 0 && [rhs length] != 0) {
3298 unichar lhc = [lhs characterAtIndex:0];
3299 unichar rhc = [rhs characterAtIndex:0];
3301 if (isalpha(lhc) && !isalpha(rhc))
3302 return NSOrderedAscending;
3303 else if (!isalpha(lhc) && isalpha(rhc))
3304 return NSOrderedDescending;
3307 return [lhs compare:rhs options:LaxCompareOptions_];
3310 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3311 if ((self = [self initWithName:name localize:NO]) != nil) {
3312 if (localized != nil)
3313 localized_ = localized;
3317 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3318 return [self initWithName:name row:0 localize:localize];
3321 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3322 if ((self = [super init]) != nil) {
3326 localized_ = LocalizeSection(name_);
3330 - (NSString *) name {
3334 - (void) setName:(NSString *)name {
3350 - (void) addToCount {
3354 - (void) setCount:(size_t)count {
3358 - (NSString *) localized {
3365 class CydiaLogCleaner :
3366 public pkgArchiveCleaner
3369 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3374 /* Database Implementation {{{ */
3375 @implementation Database
3377 + (Database *) sharedInstance {
3378 static _H<Database> instance;
3379 if (instance == nil)
3380 instance = [[[Database alloc] init] autorelease];
3388 - (void) releasePackages {
3392 - (bool) hasPackages {
3393 return [packages_ count] != 0;
3397 // XXX: actually implement this thing
3399 [self releasePackages];
3400 NSRecycleZone(zone_);
3404 - (void) _readCydia:(NSNumber *)fd {
3405 boost::fdistream is([fd intValue]);
3408 static RegEx finish_r("finish:([^:]*)");
3410 while (std::getline(is, line)) {
3411 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3413 const char *data(line.c_str());
3414 size_t size = line.size();
3415 lprintf("C:%s\n", data);
3417 if (finish_r(data, size)) {
3418 NSString *finish = finish_r[1];
3419 int index = [Finishes_ indexOfObject:finish];
3420 if (index != INT_MAX && index > Finish_)
3430 - (void) _readStatus:(NSNumber *)fd {
3431 boost::fdistream is([fd intValue]);
3434 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3435 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3437 while (std::getline(is, line)) {
3438 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3440 const char *data(line.c_str());
3441 size_t size(line.size());
3442 lprintf("S:%s\n", data);
3444 if (conffile_r(data, size)) {
3445 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3446 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3447 } else if (strncmp(data, "status: ", 8) == 0) {
3448 // status: <package>: {unpacked,half-configured,installed}
3449 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3450 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3451 } else if (strncmp(data, "processing: ", 12) == 0) {
3452 // processing: configure: config-test
3453 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3454 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3455 } else if (pmstatus_r(data, size)) {
3456 std::string type([pmstatus_r[1] UTF8String]);
3458 NSString *package = pmstatus_r[2];
3459 if ([package isEqualToString:@"dpkg-exec"])
3462 float percent([pmstatus_r[3] floatValue]);
3463 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3465 NSString *string = pmstatus_r[4];
3467 if (type == "pmerror") {
3468 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3469 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3470 } else if (type == "pmstatus") {
3471 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3472 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3473 } else if (type == "pmconffile")
3474 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3476 lprintf("E:unknown pmstatus\n");
3478 lprintf("E:unknown status\n");
3486 - (void) _readOutput:(NSNumber *)fd {
3487 boost::fdistream is([fd intValue]);
3490 while (std::getline(is, line)) {
3491 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3493 lprintf("O:%s\n", line.c_str());
3495 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3496 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3508 - (Package *) packageWithName:(NSString *)name {
3511 @synchronized (self) {
3512 if (static_cast<pkgDepCache *>(cache_) == NULL)
3514 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3519 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3523 if ((self = [super init]) != nil) {
3530 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3532 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3536 _assert(pipe(fds) != -1);
3539 _config->Set("APT::Keep-Fds::", cydiafd_);
3540 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3543 detachNewThreadSelector:@selector(_readCydia:)
3545 withObject:[NSNumber numberWithInt:fds[0]]
3548 _assert(pipe(fds) != -1);
3552 detachNewThreadSelector:@selector(_readStatus:)
3554 withObject:[NSNumber numberWithInt:fds[0]]
3557 _assert(pipe(fds) != -1);
3558 _assert(dup2(fds[0], 0) != -1);
3559 _assert(close(fds[0]) != -1);
3561 input_ = fdopen(fds[1], "a");
3563 _assert(pipe(fds) != -1);
3564 _assert(dup2(fds[1], 1) != -1);
3565 _assert(close(fds[1]) != -1);
3568 detachNewThreadSelector:@selector(_readOutput:)
3570 withObject:[NSNumber numberWithInt:fds[0]]
3575 - (pkgCacheFile &) cache {
3579 - (pkgDepCache::Policy *) policy {
3583 - (pkgRecords *) records {
3587 - (pkgProblemResolver *) resolver {
3591 - (pkgAcquire &) fetcher {
3595 - (pkgSourceList &) list {
3599 - (NSArray *) packages {
3603 - (NSArray *) sources {
3607 - (Source *) sourceWithKey:(NSString *)key {
3608 for (Source *source in [self sources]) {
3609 if ([[source key] isEqualToString:key])
3614 - (bool) popErrorWithTitle:(NSString *)title {
3617 while (!_error->empty()) {
3619 bool warning(!_error->PopMessage(error));
3624 size_t size(error.size());
3625 if (size == 0 || error[size - 1] != '\n')
3627 error.resize(size - 1);
3630 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3632 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3633 if (warning && no_pubkey(error.c_str()))
3636 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3642 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3643 return [self popErrorWithTitle:title] || !success;
3646 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3647 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3655 if (access("/etc/apt/sources.list", F_OK) == 0)
3656 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3658 std::string base("/etc/apt/sources.list.d");
3659 if (DIR *sources = opendir(base.c_str())) {
3660 while (dirent *source = readdir(sources))
3661 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)
3662 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3666 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3671 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3672 @synchronized (self) {
3675 [self releasePackages];
3678 [sourceList_ removeAllObjects];
3699 new (&pool_) CYPool();
3701 NSRecycleZone(zone_);
3702 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3704 int chk(creat("/tmp/cydia.chk", 0644));
3708 if (invocation != nil)
3709 [invocation invoke];
3711 NSString *title(UCLocalize("DATABASE"));
3713 list_ = new pkgSourceList();
3714 _profile(reloadDataWithInvocation$ReadMainList)
3715 if ([self popErrorWithTitle:title forReadList:*list_])
3719 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3720 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3721 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3722 [sourceList_ addObject:object];
3727 OpProgress progress;
3730 delock_ = GetStatusDate();
3731 _profile(reloadDataWithInvocation$pkgCacheFile)
3732 opened = cache_.Open(progress, false);
3735 // XXX: this block should probably be merged with popError: in some way
3736 while (!_error->empty()) {
3738 bool warning(!_error->PopMessage(error));
3740 lprintf("cache_.Open():[%s]\n", error.c_str());
3742 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3746 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3747 repair = @selector(configure);
3748 //else if (error == "The package lists or status file could not be parsed or opened.")
3749 // repair = @selector(update);
3750 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3751 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3752 // else if (error == "Malformed Status line")
3753 // else if (error == "The list of sources could not be read.")
3755 if (repair != NULL) {
3757 [delegate_ repairWithSelector:repair];
3763 } else if ([self popErrorWithTitle:title forOperation:true])
3767 unlink("/tmp/cydia.chk");
3769 now_ = [[NSDate date] timeIntervalSince1970];
3771 policy_ = new pkgDepCache::Policy();
3772 records_ = new pkgRecords(cache_);
3773 resolver_ = new pkgProblemResolver(cache_);
3774 fetcher_ = new pkgAcquire(&status_);
3777 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3778 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3782 _profile(reloadDataWithInvocation$pkgApplyStatus)
3783 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3787 if (cache_->BrokenCount() != 0) {
3788 _profile(pkgApplyStatus$pkgFixBroken)
3789 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3793 if (cache_->BrokenCount() != 0) {
3794 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3798 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3799 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3804 for (Source *object in (id) sourceList_) {
3805 metaIndex *source([object metaIndex]);
3806 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3807 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3808 // XXX: this could be more intelligent
3809 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3810 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3812 sourceMap_[cached->ID] = object;
3817 size_t capacity(MetaFile_->active_);
3819 capacity = 128*1024;
3823 std::vector<Package *> packages;
3824 packages.reserve(capacity);
3828 _profile(reloadDataWithInvocation$packageWithIterator)
3829 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3830 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3831 if (unsigned index = package.metadata->index_) {
3833 if (packages.size() == index) {
3834 packages.push_back(package);
3835 } else if (packages.size() <= index) {
3836 packages.resize(index + 1, nil);
3837 packages[index] = package;
3840 std::swap(package, packages[index]);
3841 if (package != nil) {
3842 if (package.metadata->index_ == index + 1)
3851 lost: if (last == packages.size())
3852 packages.push_back(package);
3854 packages[last] = package;
3858 for (; last != packages.size(); ++last)
3859 if (packages[last] == nil)
3864 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3866 if (next == packages.size())
3868 if (packages[next] != nil)
3873 std::swap(packages[last], packages[next]);
3876 packages.resize(last);
3879 NSLog(@"lost = %zu", lost);
3881 _profile(reloadDataWithInvocation$radix$8)
3882 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3885 _profile(reloadDataWithInvocation$radix$4)
3886 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3889 _profile(reloadDataWithInvocation$radix$0)
3890 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3894 _profile(reloadDataWithInvocation$insertion)
3895 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3898 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3900 /*_profile(reloadDataWithInvocation$CFQSortArray)
3901 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3904 /*_profile(reloadDataWithInvocation$stdsort)
3905 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3908 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3909 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3912 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3913 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3916 MetaFile_->active_ = packages.size();
3917 for (size_t index(0), count(packages.size()); index != count; ++index) {
3918 auto package(packages[index]);
3919 [package setIndex:index];
3926 @synchronized (self) {
3928 resolver_ = new pkgProblemResolver(cache_);
3930 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3931 if (!cache_[iterator].Keep())
3932 cache_->MarkKeep(iterator, false);
3933 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3934 cache_->SetReInstall(iterator, false);
3937 - (void) configure {
3938 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3940 system([dpkg UTF8String]);
3945 @synchronized (self) {
3946 // XXX: I don't remember this condition
3951 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3953 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3955 if ([self popErrorWithTitle:title])
3959 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3961 CydiaLogCleaner cleaner;
3962 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3969 fetcher_->Shutdown();
3971 pkgRecords records(cache_);
3973 lock_ = new FileFd();
3974 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3976 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3978 if ([self popErrorWithTitle:title])
3982 if ([self popErrorWithTitle:title forReadList:list])
3985 manager_ = (_system->CreatePM(cache_));
3986 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3993 bool substrate(RestartSubstrate_);
3994 RestartSubstrate_ = false;
3996 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3998 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4000 if ([self popErrorWithTitle:title forReadList:list])
4002 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4003 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4006 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4008 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4010 [self popErrorWithTitle:title];
4014 bool failed = false;
4015 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4016 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4018 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4021 std::string uri = (*item)->DescURI();
4022 std::string error = (*item)->ErrorText;
4024 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4027 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4028 [delegate_ addProgressEventOnMainThread:event forTask:title];
4031 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4039 RestartSubstrate_ = true;
4041 if (![delock_ isEqual:GetStatusDate()]) {
4042 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4048 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4050 NSString *oextended(@"/var/lib/apt/extended_states");
4051 NSString *nextended(Cache("extended_states"));
4054 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4055 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4057 unlink([nextended UTF8String]);
4058 symlink([oextended UTF8String], [nextended UTF8String]);
4060 if ([self popErrorWithTitle:title])
4063 if (result == pkgPackageManager::Failed) {
4068 if (result != pkgPackageManager::Completed) {
4073 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4075 if ([self popErrorWithTitle:title forReadList:list])
4077 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4078 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4081 if (![before isEqualToArray:after])
4086 return ![delock_ isEqual:GetStatusDate()];
4090 NSString *title(UCLocalize("UPGRADE"));
4091 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4097 [self updateWithStatus:status_];
4100 - (void) updateWithStatus:(CancelStatus &)status {
4101 NSString *title(UCLocalize("REFRESHING_DATA"));
4104 if ([self popErrorWithTitle:title forReadList:list])
4108 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4109 if ([self popErrorWithTitle:title])
4112 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4114 bool success(ListUpdate(status, list, PulseInterval_));
4115 if (status.WasCancelled())
4118 [self popErrorWithTitle:title forOperation:success];
4120 [[NSDictionary dictionaryWithObjectsAndKeys:
4121 [NSDate date], @"LastUpdate",
4122 nil] writeToFile:@ CacheState_ atomically:YES];
4125 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4128 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4129 delegate_ = delegate;
4132 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4133 progress_ = delegate;
4134 status_.setDelegate(delegate);
4137 - (NSObject<ProgressDelegate> *) progressDelegate {
4141 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4142 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4143 return i == sourceMap_.end() ? nil : i->second;
4146 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4147 for (Source *source in (id) sourceList_)
4148 [source setFetch:fetch forURI:uri];
4151 - (void) resetFetch {
4152 for (Source *source in (id) sourceList_)
4153 [source resetFetch];
4156 - (NSString *) mappedSectionForPointer:(const char *)section {
4157 _H<NSString> *mapped;
4159 _profile(Database$mappedSectionForPointer$Cache)
4160 mapped = §ions_[section];
4163 if (*mapped == NULL) {
4164 size_t length(strlen(section));
4165 char spaced[length + 1];
4167 _profile(Database$mappedSectionForPointer$Replace)
4168 for (size_t index(0); index != length; ++index)
4169 spaced[index] = section[index] == '_' ? ' ' : section[index];
4170 spaced[length] = '\0';
4175 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4176 string = [NSString stringWithUTF8String:spaced];
4179 _profile(Database$mappedSectionForPointer$Map)
4180 string = [SectionMap_ objectForKey:string] ?: string;
4190 @interface CydiaObject : CyteObject {
4191 _transient id delegate_;
4196 @interface CydiaWebViewController : CyteWebViewController {
4197 _H<CydiaObject> cydia_;
4200 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4201 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4202 - (void) setDelegate:(id)delegate;
4206 /* Web Scripting {{{ */
4207 @implementation CydiaObject
4209 - (void) setDelegate:(id)delegate {
4210 delegate_ = delegate;
4213 - (NSArray *) attributeKeys {
4214 return [[NSArray arrayWithObjects:
4222 nil] arrayByAddingObjectsFromArray:[super attributeKeys]];
4225 - (NSString *) version {
4229 - (NSString *) device {
4230 return UniqueIdentifier();
4233 - (NSArray *) cells {
4234 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4235 if ($_CTServerConnectionCreate == NULL)
4238 struct CTResult { int flag; int error; };
4239 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4240 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4243 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4244 if (connection == nil)
4248 CFArrayRef cells(NULL);
4249 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4250 if (result.flag != 0)
4253 return [(NSArray *) cells autorelease];
4256 - (NSString *) mcc {
4257 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4258 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4262 - (NSString *) mnc {
4263 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4264 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4268 - (NSString *) operator {
4269 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4270 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4274 - (NSString *) role {
4275 return (id) [NSNull null];
4278 + (NSString *) webScriptNameForSelector:(SEL)selector {
4280 else if (selector == @selector(addBridgedHost:))
4281 return @"addBridgedHost";
4282 else if (selector == @selector(addInsecureHost:))
4283 return @"addInsecureHost";
4284 else if (selector == @selector(addSource:::))
4285 return @"addSource";
4286 else if (selector == @selector(addTrivialSource:))
4287 return @"addTrivialSource";
4288 else if (selector == @selector(du:))
4290 else if (selector == @selector(getAllSources))
4291 return @"getAllSources";
4292 else if (selector == @selector(getApplicationInfo:value:))
4293 return @"getApplicationInfoValue";
4294 else if (selector == @selector(getDisplayIdentifiers))
4295 return @"getDisplayIdentifiers";
4296 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4297 return @"getLocalizedNameForDisplayIdentifier";
4298 else if (selector == @selector(getInstalledPackages))
4299 return @"getInstalledPackages";
4300 else if (selector == @selector(getPackageById:))
4301 return @"getPackageById";
4302 else if (selector == @selector(getMetadataKeys))
4303 return @"getMetadataKeys";
4304 else if (selector == @selector(getMetadataValue:))
4305 return @"getMetadataValue";
4306 else if (selector == @selector(getSessionValue:))
4307 return @"getSessionValue";
4308 else if (selector == @selector(installPackages:))
4309 return @"installPackages";
4310 else if (selector == @selector(refreshSources))
4311 return @"refreshSources";
4312 else if (selector == @selector(saveConfig))
4313 return @"saveConfig";
4314 else if (selector == @selector(setMetadataValue::))
4315 return @"setMetadataValue";
4316 else if (selector == @selector(setSessionValue::))
4317 return @"setSessionValue";
4318 else if (selector == @selector(substitutePackageNames:))
4319 return @"substitutePackageNames";
4320 else if (selector == @selector(setToken:))
4326 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4327 return [self webScriptNameForSelector:selector] == nil;
4330 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4332 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4333 return (id) [NSNull null];
4334 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4336 return (id) [NSNull null];
4337 return [info objectForKey:key];
4340 - (NSArray *) getDisplayIdentifiers {
4341 return SBSCopyApplicationDisplayIdentifiers(false, false);
4344 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4345 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4348 - (NSNumber *) getKernelNumber:(NSString *)name {
4349 const char *string([name UTF8String]);
4352 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4353 return (id) [NSNull null];
4355 if (size != sizeof(int))
4356 return (id) [NSNull null];
4359 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4360 return (id) [NSNull null];
4362 return [NSNumber numberWithInt:value];
4365 - (NSArray *) getMetadataKeys {
4366 @synchronized (Values_) {
4367 return [Values_ allKeys];
4370 - (id) getMetadataValue:(NSString *)key {
4371 @synchronized (Values_) {
4372 return [Values_ objectForKey:key];
4375 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4376 @synchronized (Values_) {
4377 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4378 [Values_ removeObjectForKey:key];
4380 [Values_ setObject:value forKey:key];
4383 - (id) getSessionValue:(NSString *)key {
4384 @synchronized (SessionData_) {
4385 return [SessionData_ objectForKey:key];
4388 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4389 @synchronized (SessionData_) {
4390 if (value == (id) [WebUndefined undefined])
4391 [SessionData_ removeObjectForKey:key];
4393 [SessionData_ setObject:value forKey:key];
4396 - (void) addBridgedHost:(NSString *)host {
4397 @synchronized (BridgedHosts_) {
4398 [BridgedHosts_ addObject:host];
4401 - (void) addInsecureHost:(NSString *)host {
4402 @synchronized (InsecureHosts_) {
4403 [InsecureHosts_ addObject:host];
4406 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4407 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4409 for (NSString *section in sections)
4410 [array addObject:section];
4412 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4415 distribution, @"Distribution",
4417 nil] waitUntilDone:NO];
4420 - (BOOL) addTrivialSource:(NSString *)href {
4421 href = VerifySource(href);
4424 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4428 - (void) refreshSources {
4429 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4432 - (void) saveConfig {
4433 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4436 - (NSArray *) getAllSources {
4437 return [[Database sharedInstance] sources];
4440 - (NSArray *) getInstalledPackages {
4441 Database *database([Database sharedInstance]);
4442 @synchronized (database) {
4443 NSArray *packages([database packages]);
4444 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4445 for (Package *package in packages)
4446 if (![package uninstalled])
4447 [installed addObject:package];
4451 - (Package *) getPackageById:(NSString *)id {
4452 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4456 return (Package *) [NSNull null];
4459 - (NSNumber *) du:(NSString *)path {
4460 NSNumber *value(nil);
4462 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4465 while (fgets(line, sizeof(line), du) != NULL) {
4466 size_t length(strlen(line));
4467 while (length != 0 && line[length - 1] == '\n')
4468 line[--length] = '\0';
4469 if (char *tab = strchr(line, '\t')) {
4471 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4480 - (void) installPackages:(NSArray *)packages {
4481 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4484 - (NSString *) substitutePackageNames:(NSString *)message {
4485 auto database([Database sharedInstance]);
4487 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4488 if (![database hasPackages])
4491 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4492 for (size_t i(0), e([words count]); i != e; ++i) {
4493 NSString *word([words objectAtIndex:i]);
4494 if (Package *package = [database packageWithName:word])
4495 [words replaceObjectAtIndex:i withObject:[package name]];
4498 return [words componentsJoinedByString:@" "];
4501 - (void) setToken:(NSString *)token {
4502 // XXX: the website expects this :/
4508 @interface NSURL (CydiaSecure)
4511 @implementation NSURL (CydiaSecure)
4513 - (bool) isCydiaSecure {
4514 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4517 @synchronized (InsecureHosts_) {
4518 if ([InsecureHosts_ containsObject:[self host]])
4527 /* Cydia Browser Controller {{{ */
4528 @implementation CydiaWebViewController
4530 - (NSURL *) navigationURL {
4531 if (NSURLRequest *request = self.request)
4532 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4537 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4538 [super webView:view didClearWindowObject:window forFrame:frame];
4539 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4542 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4543 WebDataSource *source([frame dataSource]);
4544 NSURLResponse *response([source response]);
4545 NSURL *url([response URL]);
4546 NSString *scheme([[url scheme] lowercaseString]);
4548 bool bridged(false);
4550 @synchronized (BridgedHosts_) {
4551 if ([scheme isEqualToString:@"file"])
4553 else if ([scheme isEqualToString:@"https"])
4554 if ([BridgedHosts_ containsObject:[url host]])
4559 [window setValue:cydia forKey:@"cydia"];
4562 - (void) _setupMail:(MFMailComposeViewController *)controller {
4563 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4565 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4566 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4569 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4570 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4573 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4574 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4577 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4578 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4580 NSURL *url([copy URL]);
4581 NSString *href([url absoluteString]);
4582 NSString *host([url host]);
4584 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4585 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4586 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4587 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4590 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4591 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4593 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4597 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4598 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4599 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4600 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4602 bool bridged; @synchronized (BridgedHosts_) {
4603 bridged = [BridgedHosts_ containsObject:host];
4606 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4607 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4612 - (void) setDelegate:(id)delegate {
4613 [super setDelegate:delegate];
4614 [cydia_ setDelegate:delegate];
4618 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4619 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
4625 @interface AppCacheController : CydiaWebViewController {
4630 @implementation AppCacheController
4632 - (void) didReceiveMemoryWarning {
4633 // XXX: this doesn't work
4636 - (bool) retainsNetworkActivityIndicator {
4643 /* Confirmation Controller {{{ */
4644 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4645 if (!iterator.end())
4646 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4647 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4649 pkgCache::PkgIterator package(dep.TargetPkg());
4652 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4659 @protocol ConfirmationControllerDelegate
4660 - (void) cancelAndClear:(bool)clear;
4661 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4665 @interface ConfirmationController : CydiaWebViewController {
4666 _transient Database *database_;
4668 _H<UIAlertView> essential_;
4670 _H<NSDictionary> changes_;
4671 _H<NSMutableArray> issues_;
4672 _H<NSDictionary> sizes_;
4677 - (id) initWithDatabase:(Database *)database;
4681 @implementation ConfirmationController
4685 RestartSubstrate_ = true;
4686 [self.delegate confirmWithNavigationController:[self navigationController]];
4689 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4690 NSString *context([alert context]);
4692 if ([context isEqualToString:@"remove"]) {
4693 if (button == [alert cancelButtonIndex])
4695 else if (button == [alert firstOtherButtonIndex]) {
4696 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4699 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4700 } else if ([context isEqualToString:@"unable"]) {
4701 [self dismissModalViewControllerAnimated:YES];
4702 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4704 [super alertView:alert clickedButtonAtIndex:button];
4708 - (void) _doContinue {
4709 [self.delegate cancelAndClear:NO];
4710 [self dismissModalViewControllerAnimated:YES];
4713 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4714 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4718 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4719 [super webView:view didClearWindowObject:window forFrame:frame];
4721 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4722 (id) changes_, @"changes",
4723 (id) issues_, @"issues",
4724 (id) sizes_, @"sizes",
4726 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4729 - (id) initWithDatabase:(Database *)database {
4730 if ((self = [super init]) != nil) {
4731 database_ = database;
4733 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4734 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4735 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4736 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4737 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4741 pkgCacheFile &cache([database_ cache]);
4742 NSArray *packages([database_ packages]);
4743 pkgDepCache::Policy *policy([database_ policy]);
4745 issues_ = [NSMutableArray arrayWithCapacity:4];
4747 for (Package *package in packages) {
4748 pkgCache::PkgIterator iterator([package iterator]);
4749 NSString *name([package id]);
4751 if ([package broken]) {
4752 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4754 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4756 reasons, @"reasons",
4759 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4763 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4764 pkgCache::DepIterator start;
4765 pkgCache::DepIterator end;
4766 dep.GlobOr(start, end); // ++dep
4768 if (!cache->IsImportantDep(end))
4770 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4773 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4775 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4776 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4777 clauses, @"clauses",
4781 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4783 pkgCache::PkgIterator target(start.TargetPkg());
4784 if (target->ProvidesList != 0)
4785 reason = @"missing";
4787 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4789 reason = @"installed";
4790 installed = [NSString stringWithUTF8String:ver.VerStr()];
4791 } else if (!cache[target].CandidateVerIter(cache).end())
4792 reason = @"uninstalled";
4793 else if (target->ProvidesList == 0)
4794 reason = @"uninstallable";
4796 reason = @"virtual";
4799 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4800 [NSString stringWithUTF8String:start.CompType()], @"operator",
4801 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4804 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4805 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4806 version, @"version",
4808 installed, @"installed",
4811 // yes, seriously. (wtf?)
4819 pkgDepCache::StateCache &state(cache[iterator]);
4821 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
4823 if (state.NewInstall())
4824 [installs addObject:name];
4825 // XXX: else if (state.Install())
4826 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4827 [reinstalls addObject:name];
4828 // XXX: move before previous if
4829 else if (state.Upgrade())
4830 [upgrades addObject:name];
4831 else if (state.Downgrade())
4832 [downgrades addObject:name];
4833 else if (!state.Delete())
4834 // XXX: _assert(state.Keep());
4836 else if (special_r(name))
4837 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4838 [NSNull null], @"package",
4839 [NSArray arrayWithObjects:
4840 [NSDictionary dictionaryWithObjectsAndKeys:
4841 @"Conflicts", @"relationship",
4842 [NSArray arrayWithObjects:
4843 [NSDictionary dictionaryWithObjectsAndKeys:
4845 [NSNull null], @"version",
4846 @"installed", @"reason",
4853 if ([package essential])
4855 [removes addObject:name];
4858 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4859 substrate_ |= DepSubstrate(iterator.CurrentVer());
4864 else if (Advanced_) {
4865 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4867 essential_ = [[[UIAlertView alloc]
4868 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4869 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4871 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4873 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4877 [essential_ setContext:@"remove"];
4878 [essential_ setNumberOfRows:2];
4880 essential_ = [[[UIAlertView alloc]
4881 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4882 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4884 cancelButtonTitle:UCLocalize("OKAY")
4885 otherButtonTitles:nil
4888 [essential_ setContext:@"unable"];
4891 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4892 installs, @"installs",
4893 reinstalls, @"reinstalls",
4894 upgrades, @"upgrades",
4895 downgrades, @"downgrades",
4896 removes, @"removes",
4899 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4900 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4901 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4904 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4908 - (UIBarButtonItem *) leftButton {
4909 return [[[UIBarButtonItem alloc]
4910 initWithTitle:UCLocalize("CANCEL")
4911 style:UIBarButtonItemStylePlain
4913 action:@selector(cancelButtonClicked)
4918 - (void) applyRightButton {
4919 if ([issues_ count] == 0 && ![self isLoading])
4920 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4921 initWithTitle:UCLocalize("CONFIRM")
4922 style:UIBarButtonItemStyleDone
4924 action:@selector(confirmButtonClicked)
4927 [[self navigationItem] setRightBarButtonItem:nil];
4931 - (void) cancelButtonClicked {
4932 [self.delegate cancelAndClear:YES];
4933 [self dismissModalViewControllerAnimated:YES];
4937 - (void) confirmButtonClicked {
4938 if (essential_ != nil)
4948 /* Progress Data {{{ */
4949 @interface CydiaProgressData : NSObject {
4950 _transient id delegate_;
4959 _H<NSMutableArray> events_;
4960 _H<NSString> title_;
4962 _H<NSString> status_;
4963 _H<NSString> finish_;
4968 @implementation CydiaProgressData
4970 + (NSArray *) _attributeKeys {
4971 return [NSArray arrayWithObjects:
4983 - (NSArray *) attributeKeys {
4984 return [[self class] _attributeKeys];
4987 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4988 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4992 if ((self = [super init]) != nil) {
4993 events_ = [NSMutableArray arrayWithCapacity:32];
5001 - (void) setDelegate:(id)delegate {
5002 delegate_ = delegate;
5005 - (void) setPercent:(float)value {
5009 - (NSNumber *) percent {
5010 return [NSNumber numberWithFloat:percent_];
5013 - (void) setCurrent:(float)value {
5017 - (NSNumber *) current {
5018 return [NSNumber numberWithFloat:current_];
5021 - (void) setTotal:(float)value {
5025 - (NSNumber *) total {
5026 return [NSNumber numberWithFloat:total_];
5029 - (void) setSpeed:(float)value {
5033 - (NSNumber *) speed {
5034 return [NSNumber numberWithFloat:speed_];
5037 - (NSArray *) events {
5041 - (void) removeAllEvents {
5042 [events_ removeAllObjects];
5045 - (void) addEvent:(CydiaProgressEvent *)event {
5046 [events_ addObject:event];
5049 - (void) setTitle:(NSString *)text {
5053 - (NSString *) title {
5057 - (void) setFinish:(NSString *)text {
5061 - (NSString *) finish {
5062 return (id) finish_ ?: [NSNull null];
5065 - (void) setRunning:(bool)running {
5069 - (NSNumber *) running {
5070 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5075 /* Progress Controller {{{ */
5076 @interface ProgressController : CydiaWebViewController <
5079 _transient Database *database_;
5080 _H<CydiaProgressData, 1> progress_;
5084 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5086 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5088 - (void) setTitle:(NSString *)title;
5089 - (void) setCancellable:(bool)cancellable;
5093 @implementation ProgressController
5096 [database_ setProgressDelegate:nil];
5100 - (UIBarButtonItem *) leftButton {
5101 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5102 initWithTitle:UCLocalize("CANCEL")
5103 style:UIBarButtonItemStylePlain
5105 action:@selector(cancel)
5106 ] autorelease] : nil;
5109 - (void) updateCancel {
5110 [super applyLeftButton];
5113 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5114 if ((self = [super init]) != nil) {
5115 database_ = database;
5116 self.delegate = delegate;
5118 [database_ setProgressDelegate:self];
5120 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5121 [progress_ setDelegate:self];
5123 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5125 [self setPageColor:[UIColor blackColor]];
5127 [[self navigationItem] setHidesBackButton:YES];
5129 [self updateCancel];
5133 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5134 [super webView:view didClearWindowObject:window forFrame:frame];
5135 [window setValue:progress_ forKey:@"cydiaProgress"];
5138 - (void) updateProgress {
5139 [self dispatchEvent:@"CydiaProgressUpdate"];
5142 - (void) viewWillAppear:(BOOL)animated {
5143 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5144 [super viewWillAppear:animated];
5148 UpdateExternalStatus(0);
5151 [self.delegate saveState];
5155 [self.delegate returnToCydia];
5159 [self.delegate terminateWithSuccess];
5160 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5161 [self.delegate suspendWithAnimation:YES];
5163 [self.delegate suspend];*/
5175 UIProgressHUD *hud([self.delegate addProgressHUD]);
5176 [hud setText:UCLocalize("LOADING")];
5177 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5183 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5184 SBReboot(SBSSpringBoardServerPort());
5186 reboot2(RB_AUTOBOOT);
5193 - (void) setTitle:(NSString *)title {
5194 [progress_ setTitle:title];
5195 [self updateProgress];
5198 - (UIBarButtonItem *) rightButton {
5199 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5200 initWithTitle:UCLocalize("CLOSE")
5201 style:UIBarButtonItemStylePlain
5203 action:@selector(close)
5207 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5208 UpdateExternalStatus(1);
5210 [progress_ setRunning:true];
5211 [self setTitle:title];
5212 // implicit updateProgress
5214 SHA1SumValue notifyconf; {
5216 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5219 MMap mmap(file, MMap::ReadOnly);
5221 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5222 notifyconf = sha1.Result();
5226 SHA1SumValue springlist; {
5228 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5231 MMap mmap(file, MMap::ReadOnly);
5233 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5234 springlist = sha1.Result();
5238 if (invocation != nil) {
5239 [invocation yieldToSelector:@selector(invoke)];
5240 [self setTitle:@"COMPLETE"];
5245 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5248 MMap mmap(file, MMap::ReadOnly);
5250 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5251 if (!(notifyconf == sha1.Result()))
5258 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5261 MMap mmap(file, MMap::ReadOnly);
5263 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5264 if (!(springlist == sha1.Result()))
5270 if (RestartSubstrate_)
5274 RestartSubstrate_ = false;
5277 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5278 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5279 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5280 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5281 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5284 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5286 [progress_ setRunning:false];
5287 [self updateProgress];
5289 [self applyRightButton];
5292 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5293 [progress_ addEvent:event];
5294 [self updateProgress];
5297 - (bool) isProgressCancelled {
5298 return cancel_ == 2;
5303 [self updateCancel];
5306 - (void) setCancellable:(bool)cancellable {
5307 unsigned cancel(cancel_);
5311 else if (cancel_ == 0)
5314 if (cancel != cancel_)
5315 [self updateCancel];
5318 - (void) setProgressCancellable:(NSNumber *)cancellable {
5319 [self setCancellable:[cancellable boolValue]];
5322 - (void) setProgressPercent:(NSNumber *)percent {
5323 [progress_ setPercent:[percent floatValue]];
5324 [self updateProgress];
5327 - (void) setProgressStatus:(NSDictionary *)status {
5328 if (status == nil) {
5329 [progress_ setCurrent:0];
5330 [progress_ setTotal:0];
5331 [progress_ setSpeed:0];
5333 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5335 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5336 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5337 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5340 [self updateProgress];
5346 /* Package Cell {{{ */
5347 @interface PackageCell : CyteTableViewCell <
5348 CyteTableViewCellDelegate
5352 _H<NSString> description_;
5354 _H<NSString> source_;
5356 _H<UIImage> placard_;
5360 - (PackageCell *) init;
5361 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5363 - (void) drawContentRect:(CGRect)rect;
5367 @implementation PackageCell
5369 - (PackageCell *) init {
5370 CGRect frame(CGRectMake(0, 0, 320, 74));
5371 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5372 UIView *content([self contentView]);
5373 CGRect bounds([content bounds]);
5375 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5376 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5377 [content addSubview:self.content];
5379 [self.content setDelegate:self];
5380 [self.content setOpaque:YES];
5384 - (NSString *) accessibilityLabel {
5388 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5389 summarized_ = summary;
5399 [self.content setBackgroundColor:[UIColor whiteColor]];
5403 Source *source = [package source];
5405 icon_ = [package icon];
5407 if (NSString *name = [package name])
5408 name_ = [NSString stringWithString:name];
5410 if (NSString *description = [package shortDescription])
5411 description_ = [NSString stringWithString:description];
5413 commercial_ = [package isCommercial];
5415 NSString *label = nil;
5416 bool trusted = false;
5418 if (source != nil) {
5419 label = [source label];
5420 trusted = [source trusted];
5421 } else if ([[package id] isEqualToString:@"firmware"])
5422 label = UCLocalize("APPLE");
5424 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5426 NSString *from(label);
5428 NSString *section = [package simpleSection];
5429 if (section != nil && ![section isEqualToString:label]) {
5430 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5431 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5434 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5436 if (NSString *purpose = [package primaryPurpose])
5437 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5442 if (NSString *mode = [package mode]) {
5443 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5444 color = RemovingColor_;
5445 placard = @"removing";
5447 color = InstallingColor_;
5448 placard = @"installing";
5451 color = [UIColor whiteColor];
5453 if ([package installed] != nil)
5454 placard = @"installed";
5459 [self.content setBackgroundColor:color];
5462 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5465 [self setNeedsDisplay];
5466 [self.content setNeedsDisplay];
5469 - (void) drawSummaryContentRect:(CGRect)rect {
5470 bool highlighted(self.highlighted);
5471 float width([self bounds].size.width);
5475 rect.size = [(UIImage *) icon_ size];
5477 while (rect.size.width > 16 || rect.size.height > 16) {
5478 rect.size.width /= 2;
5479 rect.size.height /= 2;
5482 rect.origin.x = 19 - rect.size.width / 2;
5483 rect.origin.y = 19 - rect.size.height / 2;
5485 [icon_ drawInRect:Retina(rect)];
5488 if (badge_ != nil) {
5490 rect.size = [(UIImage *) badge_ size];
5492 rect.size.width /= 4;
5493 rect.size.height /= 4;
5495 rect.origin.x = 25 - rect.size.width / 2;
5496 rect.origin.y = 25 - rect.size.height / 2;
5498 [badge_ drawInRect:Retina(rect)];
5501 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5505 UISetColor(commercial_ ? Purple_ : Black_);
5506 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5508 if (placard_ != nil)
5509 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5512 - (void) drawNormalContentRect:(CGRect)rect {
5513 bool highlighted(self.highlighted);
5514 float width([self bounds].size.width);
5518 rect.size = [(UIImage *) icon_ size];
5520 while (rect.size.width > 32 || rect.size.height > 32) {
5521 rect.size.width /= 2;
5522 rect.size.height /= 2;
5525 rect.origin.x = 25 - rect.size.width / 2;
5526 rect.origin.y = 25 - rect.size.height / 2;
5528 [icon_ drawInRect:Retina(rect)];
5531 if (badge_ != nil) {
5533 rect.size = [(UIImage *) badge_ size];
5535 rect.size.width /= 2;
5536 rect.size.height /= 2;
5538 rect.origin.x = 36 - rect.size.width / 2;
5539 rect.origin.y = 36 - rect.size.height / 2;
5541 [badge_ drawInRect:Retina(rect)];
5544 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5548 UISetColor(commercial_ ? Purple_ : Black_);
5549 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5550 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5553 UISetColor(commercial_ ? Purplish_ : Gray_);
5554 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5556 if (placard_ != nil)
5557 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5560 - (void) drawContentRect:(CGRect)rect {
5562 [self drawSummaryContentRect:rect];
5564 [self drawNormalContentRect:rect];
5569 /* Section Cell {{{ */
5570 @interface SectionCell : CyteTableViewCell <
5571 CyteTableViewCellDelegate
5573 _H<NSString> basic_;
5574 _H<NSString> section_;
5576 _H<NSString> count_;
5578 _H<UISwitch> switch_;
5582 - (void) setSection:(Section *)section editing:(BOOL)editing;
5586 @implementation SectionCell
5588 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5589 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5590 icon_ = [UIImage imageNamed:@"folder.png"];
5591 // XXX: this initial frame is wrong, but is fixed later
5592 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5593 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5595 UIView *content([self contentView]);
5596 CGRect bounds([content bounds]);
5598 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5599 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5600 [content addSubview:self.content];
5601 [self.content setBackgroundColor:[UIColor whiteColor]];
5603 [self.content setDelegate:self];
5607 - (void) onSwitch:(id)sender {
5608 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5609 if (metadata == nil) {
5610 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5611 [Sections_ setObject:metadata forKey:basic_];
5614 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5617 - (void) setSection:(Section *)section editing:(BOOL)editing {
5618 if (editing != editing_) {
5620 [switch_ removeFromSuperview];
5622 [self addSubview:switch_];
5631 if (section == nil) {
5632 name_ = UCLocalize("ALL_PACKAGES");
5635 basic_ = [section name];
5636 section_ = [section localized];
5638 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5639 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5642 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5645 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5646 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5648 [self.content setNeedsDisplay];
5651 - (void) setFrame:(CGRect)frame {
5652 [super setFrame:frame];
5654 CGRect rect([switch_ frame]);
5655 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5658 - (NSString *) accessibilityLabel {
5662 - (void) drawContentRect:(CGRect)rect {
5663 bool highlighted(self.highlighted && !editing_);
5665 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5667 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5670 float width(rect.size.width);
5672 width -= 9 + [switch_ frame].size.width;
5676 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
5678 CGSize size = [count_ sizeWithFont:Font14_];
5680 UISetColor(Folder_);
5682 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
5688 /* File Table {{{ */
5689 @interface FileTable : CyteViewController <
5690 UITableViewDataSource,
5693 _transient Database *database_;
5694 _H<Package> package_;
5696 _H<NSMutableArray> files_;
5697 _H<UITableView, 2> list_;
5700 - (id) initWithDatabase:(Database *)database;
5701 - (void) setPackage:(Package *)package;
5705 @implementation FileTable
5707 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5708 return files_ == nil ? 0 : [files_ count];
5711 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5715 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5716 static NSString *reuseIdentifier = @"Cell";
5718 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5720 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5721 [cell setFont:[UIFont systemFontOfSize:16]];
5723 [cell setText:[files_ objectAtIndex:indexPath.row]];
5724 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5729 - (NSURL *) navigationURL {
5730 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5734 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5735 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5736 [list_ setRowHeight:24.0f];
5737 [(UITableView *) list_ setDataSource:self];
5738 [list_ setDelegate:self];
5739 [self setView:list_];
5742 - (void) viewDidLoad {
5743 [super viewDidLoad];
5745 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5748 - (void) releaseSubviews {
5754 [super releaseSubviews];
5757 - (id) initWithDatabase:(Database *)database {
5758 if ((self = [super init]) != nil) {
5759 database_ = database;
5763 - (void) setPackage:(Package *)package {
5767 files_ = [NSMutableArray arrayWithCapacity:32];
5769 if (package != nil) {
5771 name_ = [package id];
5773 if (NSArray *files = [package files])
5774 [files_ addObjectsFromArray:files];
5776 if ([files_ count] != 0) {
5777 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5778 [files_ removeObjectAtIndex:0];
5779 [files_ sortUsingSelector:@selector(compareByPath:)];
5781 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5782 [stack addObject:@"/"];
5784 for (int i(0), e([files_ count]); i != e; ++i) {
5785 NSString *file = [files_ objectAtIndex:i];
5786 while (![file hasPrefix:[stack lastObject]])
5787 [stack removeLastObject];
5788 NSString *directory = [stack lastObject];
5789 [stack addObject:[file stringByAppendingString:@"/"]];
5790 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5791 int(([stack count] - 2) * 3), "",
5792 [file substringFromIndex:[directory length]]
5801 - (void) reloadData {
5804 [self setPackage:[database_ packageWithName:name_]];
5809 /* Package Controller {{{ */
5810 @interface CYPackageController : CydiaWebViewController <
5811 UIActionSheetDelegate
5813 _transient Database *database_;
5814 _H<Package> package_;
5817 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
5818 _H<UIActionSheet> sheet_;
5819 _H<UIBarButtonItem> button_;
5820 _H<NSArray> versions_;
5823 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5827 @implementation CYPackageController
5829 - (NSURL *) navigationURL {
5830 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5833 - (void) _clickButtonWithPackage:(Package *)package {
5834 [self.delegate installPackage:package];
5837 - (void) _clickButtonWithName:(NSString *)name {
5838 if ([name isEqualToString:@"CLEAR"])
5839 return [self.delegate clearPackage:package_];
5840 else if ([name isEqualToString:@"REMOVE"])
5841 return [self.delegate removePackage:package_];
5842 else if ([name isEqualToString:@"DOWNGRADE"]) {
5843 sheet_ = [[[UIActionSheet alloc]
5846 cancelButtonTitle:nil
5847 destructiveButtonTitle:nil
5848 otherButtonTitles:nil
5851 for (Package *version in (id) versions_)
5852 [sheet_ addButtonWithTitle:[version latest]];
5853 [sheet_ setContext:@"version"];
5855 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5859 else if ([name isEqualToString:@"INSTALL"]);
5860 else if ([name isEqualToString:@"REINSTALL"]);
5861 else if ([name isEqualToString:@"UPGRADE"]);
5862 else _assert(false);
5864 [self.delegate installPackage:package_];
5867 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5868 NSString *context([sheet context]);
5869 if (sheet_ == sheet)
5872 if ([context isEqualToString:@"modify"]) {
5873 if (button != [sheet cancelButtonIndex]) {
5875 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
5877 [self _clickButtonWithName:buttons_[button].first];
5880 [sheet dismissWithClickedButtonIndex:button animated:YES];
5881 } else if ([context isEqualToString:@"version"]) {
5882 if (button != [sheet cancelButtonIndex]) {
5883 Package *version([versions_ objectAtIndex:button]);
5885 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
5887 [self _clickButtonWithPackage:version];
5890 [sheet dismissWithClickedButtonIndex:button animated:YES];
5894 - (bool) _allowJavaScriptPanel {
5899 - (void) _customButtonClicked {
5900 if (commercial_ && self.isLoading && [package_ uninstalled])
5901 return [self reloadURLWithCache:NO];
5903 size_t count(buttons_.size());
5908 [self _clickButtonWithName:buttons_[0].first];
5910 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5911 for (const auto &button : buttons_)
5912 [buttons addObject:button.second];
5914 sheet_ = [[[UIActionSheet alloc]
5917 cancelButtonTitle:nil
5918 destructiveButtonTitle:nil
5919 otherButtonTitles:nil
5922 for (NSString *button in buttons)
5923 [sheet_ addButtonWithTitle:button];
5924 [sheet_ setContext:@"modify"];
5926 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5930 - (void) applyLoadingTitle {
5931 // Don't show "Loading" as the title. Ever.
5934 - (UIBarButtonItem *) rightButton {
5939 - (void) setPageColor:(UIColor *)color {
5940 return [super setPageColor:nil];
5943 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
5944 if ((self = [super init]) != nil) {
5945 database_ = database;
5946 name_ = name == nil ? @"" : [NSString stringWithString:name];
5947 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
5951 - (void) reloadData {
5954 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
5957 package_ = [database_ packageWithName:name_];
5958 versions_ = [package_ downgrades];
5962 if (package_ != nil) {
5963 [(Package *) package_ parse];
5965 commercial_ = [package_ isCommercial];
5967 if ([package_ mode] != nil)
5968 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
5969 if ([package_ source] == nil);
5970 else if ([package_ upgradableAndEssential:NO])
5971 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
5972 else if ([package_ uninstalled])
5973 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
5975 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
5976 if (![package_ uninstalled])
5977 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
5978 if ([versions_ count] != 0)
5979 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
5983 switch (buttons_.size()) {
5984 case 0: title = nil; break;
5985 case 1: title = buttons_[0].second; break;
5986 default: title = UCLocalize("MODIFY"); break;
5989 button_ = [[[UIBarButtonItem alloc]
5991 style:UIBarButtonItemStylePlain
5993 action:@selector(customButtonClicked)
5997 - (bool) isLoading {
5998 return commercial_ ? [super isLoading] : false;
6004 /* Package List Controller {{{ */
6005 @interface PackageListController : CyteViewController <
6006 UITableViewDataSource,
6009 _transient Database *database_;
6011 _H<NSArray> packages_;
6012 _H<NSArray> sections_;
6013 _H<UITableView, 2> list_;
6015 _H<NSArray> thumbs_;
6016 std::vector<NSInteger> offset_;
6018 _H<NSString> title_;
6019 unsigned reloading_;
6022 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6023 - (void) resetCursor;
6026 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6030 @implementation PackageListController
6032 - (NSURL *) referrerURL {
6033 return [self navigationURL];
6036 - (bool) isSummarized {
6040 - (bool) showsSections {
6044 - (void) deselectWithAnimation:(BOOL)animated {
6045 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6048 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6049 CGRect base = [[self view] bounds];
6050 base.size.height -= bounds.size.height;
6051 base.origin = [list_ frame].origin;
6053 [UIView beginAnimations:nil context:NULL];
6054 [UIView setAnimationBeginsFromCurrentState:YES];
6055 [UIView setAnimationCurve:curve];
6056 [UIView setAnimationDuration:duration];
6057 [list_ setFrame:base];
6058 [UIView commitAnimations];
6061 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6062 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6065 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6066 [self resizeForKeyboardBounds:bounds duration:0];
6069 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6070 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6071 *curve = UIViewAnimationCurveEaseInOut;
6073 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6075 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6078 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6081 - (void) keyboardWillShow:(NSNotification *)notification {
6084 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6085 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6087 NSTimeInterval duration;
6088 UIViewAnimationCurve curve;
6089 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6091 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6092 UIViewController *base([self rootViewController]);
6093 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6094 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6096 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6097 intersection.size.height += CYStatusBarHeight();
6099 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6102 - (void) keyboardWillHide:(NSNotification *)notification {
6103 NSTimeInterval duration;
6104 UIViewAnimationCurve curve;
6105 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6107 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6110 - (void) viewWillAppear:(BOOL)animated {
6111 [super viewWillAppear:animated];
6113 [self resizeForKeyboardBounds:CGRectZero];
6114 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6115 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6118 - (void) viewWillDisappear:(BOOL)animated {
6119 [super viewWillDisappear:animated];
6121 [self resizeForKeyboardBounds:CGRectZero];
6122 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6123 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6126 - (void) viewDidAppear:(BOOL)animated {
6127 [super viewDidAppear:animated];
6128 [self deselectWithAnimation:animated];
6131 - (void) didSelectPackage:(Package *)package {
6132 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6133 [view setDelegate:self.delegate];
6134 [[self navigationController] pushViewController:view animated:YES];
6137 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6138 NSInteger count([sections_ count]);
6139 return count == 0 ? 1 : count;
6142 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6143 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6145 return [[sections_ objectAtIndex:section] name];
6148 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6149 if ([sections_ count] == 0)
6151 return [[sections_ objectAtIndex:section] count];
6154 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6155 @synchronized (database_) {
6156 if ([database_ era] != era_)
6159 Section *section([sections_ objectAtIndex:[path section]]);
6160 NSInteger row([path row]);
6161 Package *package([packages_ objectAtIndex:([section row] + row)]);
6162 return [[package retain] autorelease];
6165 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6166 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6168 cell = [[[PackageCell alloc] init] autorelease];
6170 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6171 [cell setPackage:package asSummary:[self isSummarized]];
6175 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6176 Package *package([self packageAtIndexPath:path]);
6177 package = [database_ packageWithName:[package id]];
6178 [self didSelectPackage:package];
6181 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6185 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6186 return offset_[index];
6189 - (void) updateHeight {
6190 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6193 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6194 if ((self = [super init]) != nil) {
6195 database_ = database;
6196 title_ = [title copy];
6197 [[self navigationItem] setTitle:title_];
6202 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6203 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6204 [self setView:view];
6206 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6207 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6208 [view addSubview:list_];
6210 // XXX: is 20 the most optimal number here?
6211 [list_ setSectionIndexMinimumDisplayRowCount:20];
6213 [(UITableView *) list_ setDataSource:self];
6214 [list_ setDelegate:self];
6216 [self updateHeight];
6219 - (void) releaseSubviews {
6228 [super releaseSubviews];
6231 - (bool) shouldYield {
6235 - (bool) shouldBlock {
6239 - (NSMutableArray *) _reloadPackages {
6240 @synchronized (database_) {
6241 era_ = [database_ era];
6242 NSArray *packages([database_ packages]);
6244 return [NSMutableArray arrayWithArray:packages];
6247 - (void) _reloadData {
6248 if (reloading_ != 0) {
6253 NSMutableArray *packages;
6256 if ([self shouldYield]) {
6260 if (![self shouldBlock])
6263 hud = [self.delegate addProgressHUD];
6264 [hud setText:UCLocalize("LOADING")];
6268 packages = [self yieldToSelector:@selector(_reloadPackages)];
6271 [self.delegate removeProgressHUD:hud];
6272 } while (reloading_ == 2);
6274 packages = [self _reloadPackages];
6277 @synchronized (database_) {
6278 if (era_ != [database_ era])
6285 packages_ = packages;
6287 if ([self showsSections])
6288 sections_ = [self sectionsForPackages:packages];
6290 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6291 [section setCount:[packages_ count]];
6292 sections_ = [NSArray arrayWithObject:section];
6295 [self updateHeight];
6297 _profile(PackageTable$reloadData$List)
6298 [(UITableView *) list_ setDataSource:self];
6306 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6307 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6308 size_t end([packages count]);
6310 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6311 Section *section(prefix);
6313 thumbs_ = CollationThumbs_;
6314 offset_ = CollationOffset_;
6317 size_t offsets([CollationStarts_ count]);
6319 NSString *start([CollationStarts_ objectAtIndex:offset]);
6320 size_t length([start length]);
6322 for (size_t index(0); index != end; ++index) {
6324 Package *package([packages objectAtIndex:index]);
6325 NSString *name(PackageName(package, @selector(cyname)));
6327 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6328 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6329 NSString *title([CollationTitles_ objectAtIndex:offset]);
6330 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6331 [sections addObject:section];
6333 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6336 length = [start length];
6340 [section addToCount];
6343 for (; offset != offsets; ++offset) {
6344 NSString *title([CollationTitles_ objectAtIndex:offset]);
6345 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6346 [sections addObject:section];
6349 if ([prefix count] != 0) {
6350 Section *suffix([sections lastObject]);
6351 [prefix setName:[suffix name]];
6352 [suffix setName:nil];
6353 [sections insertObject:prefix atIndex:(offsets - 1)];
6359 - (void) reloadData {
6362 if ([self shouldYield])
6363 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6368 - (void) resetCursor {
6369 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6372 - (void) clearData {
6373 [self updateHeight];
6375 [list_ setDataSource:nil];
6383 /* Filtered Package List Controller {{{ */
6384 typedef Function<bool, Package *> PackageFilter;
6385 typedef Function<void, NSMutableArray *> PackageSorter;
6386 @interface FilteredPackageListController : PackageListController {
6387 PackageFilter filter_;
6388 PackageSorter sorter_;
6391 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6393 - (void) setFilter:(PackageFilter)filter;
6394 - (void) setSorter:(PackageSorter)sorter;
6398 @implementation FilteredPackageListController
6400 - (void) setFilter:(PackageFilter)filter {
6401 @synchronized (self) {
6405 - (void) setSorter:(PackageSorter)sorter {
6406 @synchronized (self) {
6410 - (NSMutableArray *) _reloadPackages {
6411 @synchronized (database_) {
6412 era_ = [database_ era];
6414 NSArray *packages([database_ packages]);
6415 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6417 PackageFilter filter;
6418 PackageSorter sorter;
6420 @synchronized (self) {
6425 _profile(PackageTable$reloadData$Filter)
6426 for (Package *package in packages)
6427 if (filter(package))
6428 [filtered addObject:package];
6436 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6437 if ((self = [super initWithDatabase:database title:title]) != nil) {
6438 [self setFilter:filter];
6445 /* Home Controller {{{ */
6446 @interface HomeController : CydiaWebViewController {
6447 CFRunLoopRef runloop_;
6448 SCNetworkReachabilityRef reachability_;
6453 @implementation HomeController
6455 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6456 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6460 if ((self = [super init]) != nil) {
6461 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6464 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6465 if (reachability_ != NULL) {
6466 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6467 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6469 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6470 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6477 if (reachability_ != NULL && runloop_ != NULL)
6478 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6482 - (NSURL *) navigationURL {
6483 return [NSURL URLWithString:@"cydia://home"];
6486 - (void) aboutButtonClicked {
6487 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6489 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6490 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6491 [alert setCancelButtonIndex:0];
6494 @"Copyright \u00a9 2008-2015\n"
6497 "Jay Freeman (saurik)\n"
6498 "saurik@saurik.com\n"
6499 "http://www.saurik.com/"
6505 - (UIBarButtonItem *) leftButton {
6506 return [[[UIBarButtonItem alloc]
6507 initWithTitle:UCLocalize("ABOUT")
6508 style:UIBarButtonItemStylePlain
6510 action:@selector(aboutButtonClicked)
6517 /* Cydia Tab Bar Controller {{{ */
6518 @interface CydiaTabBarController : CyteTabBarController <
6519 UITabBarControllerDelegate,
6522 _transient Database *database_;
6524 _H<UIActivityIndicatorView> indicator_;
6527 // XXX: ok, "updatedelegate_"?...
6528 _transient NSObject<CydiaDelegate> *updatedelegate_;
6531 - (void) beginUpdate;
6536 @implementation CydiaTabBarController
6538 - (id) initWithDatabase:(Database *)database {
6539 if ((self = [super init]) != nil) {
6540 database_ = database;
6541 [self setDelegate:self];
6543 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6544 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6546 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6550 - (void) beginUpdate {
6554 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6555 UITabBarItem *item([controller tabBarItem]);
6557 [item setBadgeValue:@""];
6558 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6560 [indicator_ startAnimating];
6561 [badge addSubview:indicator_];
6563 [updatedelegate_ retainNetworkActivityIndicator];
6567 detachNewThreadSelector:@selector(performUpdate)
6573 - (void) performUpdate {
6574 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6576 SourceStatus status(self, database_);
6577 [database_ updateWithStatus:status];
6580 performSelectorOnMainThread:@selector(completeUpdate)
6588 - (void) stopUpdateWithSelector:(SEL)selector {
6590 [updatedelegate_ releaseNetworkActivityIndicator];
6592 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6593 [[controller tabBarItem] setBadgeValue:nil];
6595 [indicator_ removeFromSuperview];
6596 [indicator_ stopAnimating];
6598 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6601 - (void) completeUpdate {
6604 [self stopUpdateWithSelector:@selector(reloadData)];
6607 - (void) cancelUpdate {
6608 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6611 - (void) cancelPressed {
6612 [self cancelUpdate];
6619 - (bool) isSourceCancelled {
6623 - (void) startSourceFetch:(NSString *)uri {
6626 - (void) stopSourceFetch:(NSString *)uri {
6629 - (void) setUpdateDelegate:(id)delegate {
6630 updatedelegate_ = delegate;
6636 /* Cydia:// Protocol {{{ */
6637 @interface CydiaURLProtocol : NSURLProtocol {
6642 @implementation CydiaURLProtocol
6644 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6645 NSURL *url([request URL]);
6649 NSString *scheme([[url scheme] lowercaseString]);
6650 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6652 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6658 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6662 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6663 id<NSURLProtocolClient> client([self client]);
6665 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6667 NSData *data(UIImagePNGRepresentation(icon));
6669 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6670 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6671 [client URLProtocol:self didLoadData:data];
6672 [client URLProtocolDidFinishLoading:self];
6676 - (void) startLoading {
6677 id<NSURLProtocolClient> client([self client]);
6678 NSURLRequest *request([self request]);
6680 NSURL *url([request URL]);
6681 NSString *href([url absoluteString]);
6682 NSString *scheme([[url scheme] lowercaseString]);
6686 if ([scheme isEqualToString:@"cydia"])
6687 path = [href substringFromIndex:8];
6688 else if ([scheme isEqualToString:@"about"])
6689 path = [href substringFromIndex:12];
6690 else _assert(false);
6692 NSRange slash([path rangeOfString:@"/"]);
6695 if (slash.location == NSNotFound) {
6699 command = [path substringToIndex:slash.location];
6700 path = [path substringFromIndex:(slash.location + 1)];
6703 Database *database([Database sharedInstance]);
6706 else if ([command isEqualToString:@"application-icon"]) {
6709 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6713 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
6714 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
6715 icon = [UIImage imageWithData:data];
6719 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
6720 icon = [UIImage imageAtPath:file];
6723 icon = [UIImage imageNamed:@"unknown.png"];
6725 [self _returnPNGWithImage:icon forRequest:request];
6726 } else if ([command isEqualToString:@"package-icon"]) {
6729 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6730 Package *package([database packageWithName:path]);
6734 UIImage *icon([package icon]);
6735 [self _returnPNGWithImage:icon forRequest:request];
6736 } else if ([command isEqualToString:@"uikit-image"]) {
6739 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6740 UIImage *icon(_UIImageWithName(path));
6741 [self _returnPNGWithImage:icon forRequest:request];
6742 } else if ([command isEqualToString:@"section-icon"]) {
6745 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6746 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6748 icon = [UIImage imageNamed:@"unknown.png"];
6749 [self _returnPNGWithImage:icon forRequest:request];
6751 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6755 - (void) stopLoading {
6761 /* Section Controller {{{ */
6762 @interface SectionController : FilteredPackageListController {
6764 _H<NSString> section_;
6767 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
6771 @implementation SectionController
6773 - (NSURL *) referrerURL {
6774 NSString *name(section_);
6775 name = name ?: @"*";
6776 NSString *key(key_);
6778 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6781 - (NSURL *) navigationURL {
6782 NSString *name(section_);
6783 name = name ?: @"*";
6784 NSString *key(key_);
6786 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6789 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
6792 title = UCLocalize("ALL_PACKAGES");
6793 else if (![section isEqual:@""])
6794 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
6796 title = UCLocalize("NO_SECTION");
6798 if ((self = [super initWithDatabase:database title:title]) != nil) {
6799 key_ = [source key];
6804 - (void) reloadData {
6805 Source *source([database_ sourceWithKey:key_]);
6806 _H<NSString> name(section_);
6808 [self setFilter:[=](Package *package) {
6809 NSString *section([package section]);
6813 section == nil && [name length] == 0 ||
6814 [name isEqualToString:section]
6817 [package source] == source
6818 ) && [package visible];
6826 /* Sections Controller {{{ */
6827 @interface SectionsController : CyteViewController <
6828 UITableViewDataSource,
6831 _transient Database *database_;
6833 _H<NSMutableArray> sections_;
6834 _H<NSMutableArray> filtered_;
6835 _H<UITableView, 2> list_;
6838 - (id) initWithDatabase:(Database *)database source:(Source *)source;
6839 - (void) editButtonClicked;
6843 @implementation SectionsController
6845 - (NSURL *) navigationURL {
6846 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
6849 - (Source *) source {
6852 return [database_ sourceWithKey:key_];
6855 - (void) updateNavigationItem {
6856 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6857 if ([sections_ count] == 0) {
6858 [[self navigationItem] setRightBarButtonItem:nil];
6860 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6861 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6863 action:@selector(editButtonClicked)
6864 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6868 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6869 [super setEditing:editing animated:animated];
6874 [self.delegate updateData];
6876 [self updateNavigationItem];
6879 - (void) viewDidAppear:(BOOL)animated {
6880 [super viewDidAppear:animated];
6881 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6884 - (void) viewWillDisappear:(BOOL)animated {
6885 [super viewWillDisappear:animated];
6886 [self setEditing:NO];
6889 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6890 Section *section = nil;
6891 int index = [indexPath row];
6892 if (![self isEditing]) {
6895 section = [filtered_ objectAtIndex:index];
6897 section = [sections_ objectAtIndex:index];
6902 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6903 if ([self isEditing])
6904 return [sections_ count];
6906 return [filtered_ count] + 1;
6909 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6913 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6914 static NSString *reuseIdentifier = @"SectionCell";
6916 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6918 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6920 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6925 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6926 if ([self isEditing])
6929 Section *section = [self sectionAtIndexPath:indexPath];
6931 SectionController *controller = [[[SectionController alloc]
6932 initWithDatabase:database_
6933 source:[self source]
6934 section:[section name]
6936 [controller setDelegate:self.delegate];
6938 [[self navigationController] pushViewController:controller animated:YES];
6942 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6943 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6944 [list_ setRowHeight:46];
6945 [(UITableView *) list_ setDataSource:self];
6946 [list_ setDelegate:self];
6947 [self setView:list_];
6950 - (void) viewDidLoad {
6951 [super viewDidLoad];
6953 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6956 - (void) releaseSubviews {
6962 [super releaseSubviews];
6965 - (id) initWithDatabase:(Database *)database source:(Source *)source {
6966 if ((self = [super init]) != nil) {
6967 database_ = database;
6968 key_ = [source key];
6972 - (void) reloadData {
6975 NSArray *packages = [database_ packages];
6977 sections_ = [NSMutableArray arrayWithCapacity:16];
6978 filtered_ = [NSMutableArray arrayWithCapacity:16];
6980 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6982 Source *source([self source]);
6985 for (Package *package in packages) {
6986 if (source != nil && [package source] != source)
6989 NSString *name([package section]);
6990 NSString *key(name == nil ? @"" : name);
6994 _profile(SectionsView$reloadData$Section)
6995 section = [sections objectForKey:key];
6996 if (section == nil) {
6997 _profile(SectionsView$reloadData$Section$Allocate)
6998 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6999 [sections setObject:section forKey:key];
7004 [section addToCount];
7006 _profile(SectionsView$reloadData$Filter)
7007 if (![package visible])
7015 [sections_ addObjectsFromArray:[sections allValues]];
7017 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7019 for (Section *section in (id) sections_) {
7020 size_t count([section row]);
7024 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7025 [section setCount:count];
7026 [filtered_ addObject:section];
7029 [self updateNavigationItem];
7034 - (void) editButtonClicked {
7035 [self setEditing:![self isEditing] animated:YES];
7041 /* Changes Controller {{{ */
7042 @interface ChangesController : FilteredPackageListController {
7046 - (id) initWithDatabase:(Database *)database;
7050 @implementation ChangesController
7052 - (NSURL *) referrerURL {
7053 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7056 - (NSURL *) navigationURL {
7057 return [NSURL URLWithString:@"cydia://changes"];
7060 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7061 @synchronized (database_) {
7062 if ([database_ era] != era_)
7065 NSUInteger sectionIndex([path section]);
7066 if (sectionIndex >= [sections_ count])
7068 Section *section([sections_ objectAtIndex:sectionIndex]);
7069 NSInteger row([path row]);
7070 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7073 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7074 NSString *context([alert context]);
7076 if ([context isEqualToString:@"norefresh"])
7077 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7080 - (void) setLeftBarButtonItem {
7081 if ([self.delegate updating])
7082 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7083 initWithTitle:UCLocalize("CANCEL")
7084 style:UIBarButtonItemStyleDone
7086 action:@selector(cancelButtonClicked)
7087 ] autorelease] animated:YES];
7089 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7090 initWithTitle:UCLocalize("REFRESH")
7091 style:UIBarButtonItemStylePlain
7093 action:@selector(refreshButtonClicked)
7094 ] autorelease] animated:YES];
7097 - (void) refreshButtonClicked {
7098 if ([self.delegate requestUpdate])
7099 [self setLeftBarButtonItem];
7102 - (void) cancelButtonClicked {
7103 [self.delegate cancelUpdate];
7106 - (void) upgradeButtonClicked {
7107 [self.delegate distUpgrade];
7108 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7111 - (bool) shouldYield {
7115 - (bool) shouldBlock {
7119 - (void) useFilter {
7120 @synchronized (self) {
7121 [self setFilter:[](Package *package) {
7122 return [package upgradableAndEssential:YES] || [package visible];
7125 [self setSorter:[](NSMutableArray *packages) {
7126 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7130 - (id) initWithDatabase:(Database *)database {
7131 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7136 - (void) viewDidLoad {
7137 [super viewDidLoad];
7138 [self setLeftBarButtonItem];
7141 - (void) viewWillAppear:(BOOL)animated {
7142 [super viewWillAppear:animated];
7143 [self setLeftBarButtonItem];
7146 - (void) reloadData {
7147 [self setLeftBarButtonItem];
7151 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7152 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7154 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7155 Section *ignored = nil;
7156 Section *section = nil;
7160 bool unseens = false;
7162 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7164 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7165 Package *package = [packages objectAtIndex:offset];
7167 BOOL uae = [package upgradableAndEssential:YES];
7171 time_t seen([package seen]);
7173 if (section == nil || last != seen) {
7177 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7180 _profile(ChangesController$reloadData$Allocate)
7181 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7182 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7183 [sections addObject:section];
7187 [section addToCount];
7188 } else if ([package ignored]) {
7189 if (ignored == nil) {
7190 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7192 [ignored addToCount];
7195 [upgradable addToCount];
7200 CFRelease(formatter);
7203 Section *last = [sections lastObject];
7204 size_t count = [last count];
7205 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7206 [sections removeLastObject];
7209 if ([ignored count] != 0)
7210 [sections insertObject:ignored atIndex:0];
7212 [sections insertObject:upgradable atIndex:0];
7216 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7217 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7218 style:UIBarButtonItemStylePlain
7220 action:@selector(upgradeButtonClicked)
7221 ] autorelease]) animated:YES];
7228 /* Search Controller {{{ */
7229 @interface SearchController : FilteredPackageListController <
7232 _H<UISearchBar, 1> search_;
7237 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7238 - (void) reloadData;
7242 @implementation SearchController
7244 - (NSURL *) referrerURL {
7245 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7248 - (NSURL *) navigationURL {
7249 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7250 return [NSURL URLWithString:@"cydia://search"];
7252 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7255 - (NSArray *) termsForQuery:(NSString *)query {
7256 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7257 for (NSString *component in [query componentsSeparatedByString:@" "])
7258 if ([component length] != 0)
7259 [terms addObject:component];
7264 - (void) useSearch {
7265 _H<NSArray> query([self termsForQuery:[search_ text]]);
7268 @synchronized (self) {
7269 [self setFilter:[=](Package *package) {
7270 if (![package unfiltered])
7272 if (![package matches:query])
7277 [self setSorter:[](NSMutableArray *packages) {
7278 [packages radixSortUsingSelector:@selector(rank)];
7286 - (void) usePrefix:(NSString *)prefix {
7287 _H<NSString> query(prefix);
7290 @synchronized (self) {
7291 [self setFilter:[=](Package *package) {
7292 if ([query length] == 0)
7294 if (![package unfiltered])
7296 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7301 [self setSorter:nullptr];
7307 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7309 [self usePrefix:[search_ text]];
7312 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7313 [search_ resignFirstResponder];
7317 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7318 [search_ setText:@""];
7319 [self searchBarButtonClicked:searchBar];
7322 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7323 [self searchBarButtonClicked:searchBar];
7326 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7327 [self usePrefix:text];
7330 - (bool) shouldYield {
7334 - (bool) shouldBlock {
7338 - (bool) isSummarized {
7342 - (bool) showsSections {
7346 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7347 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7348 search_ = [[[UISearchBar alloc] init] autorelease];
7349 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7350 [search_ setDelegate:self];
7352 UITextField *textField;
7353 if ([search_ respondsToSelector:@selector(searchField)])
7354 textField = [search_ searchField];
7356 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7358 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7359 [textField setEnablesReturnKeyAutomatically:NO];
7360 [[self navigationItem] setTitleView:textField];
7363 [search_ setText:query];
7368 - (void) viewDidAppear:(BOOL)animated {
7369 [super viewDidAppear:animated];
7371 if (!searchloaded_) {
7372 searchloaded_ = YES;
7373 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7374 [search_ layoutSubviews];
7377 if ([self isSummarized])
7378 [search_ becomeFirstResponder];
7381 - (void) reloadData {
7386 - (void) didSelectPackage:(Package *)package {
7387 [search_ resignFirstResponder];
7388 [super didSelectPackage:package];
7393 /* Package Settings Controller {{{ */
7394 @interface PackageSettingsController : CyteViewController <
7395 UITableViewDataSource,
7398 _transient Database *database_;
7400 _H<Package> package_;
7401 _H<UITableView, 2> table_;
7402 _H<UISwitch> subscribedSwitch_;
7403 _H<UISwitch> ignoredSwitch_;
7404 _H<UITableViewCell> subscribedCell_;
7405 _H<UITableViewCell> ignoredCell_;
7408 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7412 @implementation PackageSettingsController
7414 - (NSURL *) navigationURL {
7415 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7418 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7419 if (package_ == nil)
7422 if ([package_ installed] == nil)
7428 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7429 if (package_ == nil)
7432 // both sections contain just one item right now.
7436 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7440 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7442 return UCLocalize("SHOW_ALL_CHANGES_EX");
7444 return UCLocalize("IGNORE_UPGRADES_EX");
7447 - (void) onSubscribed:(id)control {
7448 bool value([control isOn]);
7449 if (package_ == nil)
7451 if ([package_ setSubscribed:value])
7452 [self.delegate updateData];
7455 - (void) _updateIgnored {
7456 const char *package([name_ UTF8String]);
7457 bool on([ignoredSwitch_ isOn]);
7459 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7460 fwrite(package, strlen(package), 1, dpkg);
7463 fwrite(" hold\n", 6, 1, dpkg);
7465 fwrite(" install\n", 9, 1, dpkg);
7470 - (void) onIgnored:(id)control {
7471 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7472 [invocation setTarget:self];
7473 [invocation setSelector:@selector(_updateIgnored)];
7475 [self.delegate reloadDataWithInvocation:invocation];
7478 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7479 if (package_ == nil)
7482 switch ([indexPath section]) {
7483 case 0: return subscribedCell_;
7484 case 1: return ignoredCell_;
7493 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7494 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7495 [self setView:view];
7497 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7498 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7499 [(UITableView *) table_ setDataSource:self];
7500 [table_ setDelegate:self];
7501 [view addSubview:table_];
7503 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7504 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7505 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7507 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7508 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7509 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7511 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7512 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7513 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7514 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7516 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7517 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7518 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7519 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7522 - (void) viewDidLoad {
7523 [super viewDidLoad];
7525 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7528 - (void) releaseSubviews {
7530 subscribedCell_ = nil;
7532 ignoredSwitch_ = nil;
7533 subscribedSwitch_ = nil;
7535 [super releaseSubviews];
7538 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7539 if ((self = [super init]) != nil) {
7540 database_ = database;
7545 - (void) reloadData {
7548 package_ = [database_ packageWithName:name_];
7550 if (package_ != nil) {
7551 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7552 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7553 } // XXX: what now, G?
7555 [table_ reloadData];
7561 /* Installed Controller {{{ */
7562 @interface InstalledController : FilteredPackageListController {
7566 - (id) initWithDatabase:(Database *)database;
7567 - (void) queueStatusDidChange;
7571 @implementation InstalledController
7573 - (NSURL *) referrerURL {
7574 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7577 - (NSURL *) navigationURL {
7578 return [NSURL URLWithString:@"cydia://installed"];
7581 - (void) useRecent {
7584 @synchronized (self) {
7585 [self setFilter:[](Package *package) {
7586 return ![package uninstalled] && package->role_ < 7;
7589 [self setSorter:[](NSMutableArray *packages) {
7590 [packages radixSortUsingSelector:@selector(recent)];
7594 - (void) useFilter:(UISegmentedControl *)segmented {
7595 NSInteger selected([segmented selectedSegmentIndex]);
7597 return [self useRecent];
7598 bool simple(selected == 0);
7601 @synchronized (self) {
7602 [self setFilter:[=](Package *package) {
7603 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7606 [self setSorter:nullptr];
7609 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7611 return [super sectionsForPackages:packages];
7613 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
7615 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7616 Section *section(nil);
7619 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
7620 Package *package([packages objectAtIndex:offset]);
7622 time_t upgraded([package upgraded]);
7623 if (upgraded < 1168364520)
7626 upgraded -= upgraded % (60 * 60 * 24);
7628 if (section == nil || upgraded != last) {
7633 continue; // XXX: name = UCLocalize("...");
7635 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
7639 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7640 [sections addObject:section];
7643 [section addToCount];
7646 CFRelease(formatter);
7650 - (id) initWithDatabase:(Database *)database {
7651 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7652 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7653 [segmented setSelectedSegmentIndex:0];
7654 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7655 [[self navigationItem] setTitleView:segmented];
7657 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7658 [self useFilter:segmented];
7660 [self queueStatusDidChange];
7665 - (void) queueButtonClicked {
7666 [self.delegate queue];
7670 - (void) queueStatusDidChange {
7673 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7674 initWithTitle:UCLocalize("QUEUE")
7675 style:UIBarButtonItemStyleDone
7677 action:@selector(queueButtonClicked)
7680 [[self navigationItem] setRightBarButtonItem:nil];
7685 - (void) modeChanged:(UISegmentedControl *)segmented {
7686 [self useFilter:segmented];
7693 /* Source Cell {{{ */
7694 @interface SourceCell : CyteTableViewCell <
7695 CyteTableViewCellDelegate,
7698 _H<Source, 1> source_;
7701 _H<NSString> origin_;
7702 _H<NSString> label_;
7703 _H<UIActivityIndicatorView> indicator_;
7706 - (void) setSource:(Source *)source;
7707 - (void) setFetch:(NSNumber *)fetch;
7711 @implementation SourceCell
7713 - (void) _setImage:(NSArray *)data {
7714 if ([url_ isEqual:[data objectAtIndex:0]]) {
7715 icon_ = [data objectAtIndex:1];
7716 [self.content setNeedsDisplay];
7720 - (void) _setSource:(NSURL *) url {
7721 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7723 if (NSData *data = [NSURLConnection
7724 sendSynchronousRequest:[NSURLRequest
7726 cachePolicy:NSURLRequestUseProtocolCachePolicy
7730 returningResponse:NULL
7733 if (UIImage *image = [UIImage imageWithData:data])
7734 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
7739 - (void) setSource:(Source *)source {
7741 [source_ setDelegate:self];
7743 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
7745 icon_ = [UIImage imageNamed:@"unknown.png"];
7747 origin_ = [source name];
7748 label_ = [source rooturi];
7750 [self.content setNeedsDisplay];
7752 url_ = [source iconURL];
7753 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
7756 - (void) setAllSource {
7758 [indicator_ stopAnimating];
7760 icon_ = [UIImage imageNamed:@"folder.png"];
7761 origin_ = UCLocalize("ALL_SOURCES");
7762 label_ = UCLocalize("ALL_SOURCES_EX");
7763 [self.content setNeedsDisplay];
7766 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7767 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7768 UIView *content([self contentView]);
7769 CGRect bounds([content bounds]);
7771 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7772 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7773 [self.content setBackgroundColor:[UIColor whiteColor]];
7774 [content addSubview:self.content];
7776 [self.content setDelegate:self];
7777 [self.content setOpaque:YES];
7779 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
7780 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
7781 [content addSubview:indicator_];
7783 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
7787 - (void) layoutSubviews {
7788 [super layoutSubviews];
7790 UIView *content([self contentView]);
7791 CGRect bounds([content bounds]);
7793 CGRect frame([indicator_ frame]);
7794 frame.origin.x = bounds.size.width - frame.size.width;
7795 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
7797 if (kCFCoreFoundationVersionNumber < 800)
7798 frame.origin.x -= 8;
7799 [indicator_ setFrame:frame];
7802 - (NSString *) accessibilityLabel {
7806 - (void) drawContentRect:(CGRect)rect {
7807 bool highlighted(self.highlighted);
7808 float width(rect.size.width);
7812 rect.size = [(UIImage *) icon_ size];
7814 while (rect.size.width > 32 || rect.size.height > 32) {
7815 rect.size.width /= 2;
7816 rect.size.height /= 2;
7819 rect.origin.x = 26 - rect.size.width / 2;
7820 rect.origin.y = 26 - rect.size.height / 2;
7822 [icon_ drawInRect:Retina(rect)];
7825 if (highlighted && kCFCoreFoundationVersionNumber < 800)
7830 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
7834 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
7837 - (void) setFetch:(NSNumber *)fetch {
7838 if ([fetch boolValue])
7839 [indicator_ startAnimating];
7841 [indicator_ stopAnimating];
7846 /* Sources Controller {{{ */
7847 @interface SourcesController : CyteViewController <
7848 UITableViewDataSource,
7851 _transient Database *database_;
7854 _H<UITableView, 2> list_;
7855 _H<NSMutableArray> sources_;
7859 _H<UIProgressHUD> hud_;
7862 NSURLConnection *trivial_bz2_;
7863 NSURLConnection *trivial_gz_;
7868 - (id) initWithDatabase:(Database *)database;
7869 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
7873 @implementation SourcesController
7875 - (void) _releaseConnection:(NSURLConnection *)connection {
7876 if (connection != nil) {
7877 [connection cancel];
7878 //[connection setDelegate:nil];
7879 [connection release];
7884 [self _releaseConnection:trivial_gz_];
7885 [self _releaseConnection:trivial_bz2_];
7890 - (NSURL *) navigationURL {
7891 return [NSURL URLWithString:@"cydia://sources"];
7894 - (void) viewDidAppear:(BOOL)animated {
7895 [super viewDidAppear:animated];
7896 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7899 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7903 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7905 return UCLocalize("INDIVIDUAL_SOURCES");
7909 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7912 case 1: return [sources_ count];
7917 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7918 @synchronized (database_) {
7919 if ([database_ era] != era_)
7921 if ([indexPath section] != 1)
7923 NSUInteger index([indexPath row]);
7924 if (index >= [sources_ count])
7926 return [sources_ objectAtIndex:index];
7929 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7930 static NSString *cellIdentifier = @"SourceCell";
7932 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7933 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7934 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7936 Source *source([self sourceAtIndexPath:indexPath]);
7938 [cell setAllSource];
7940 [cell setSource:source];
7945 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7946 SectionsController *controller([[[SectionsController alloc]
7947 initWithDatabase:database_
7948 source:[self sourceAtIndexPath:indexPath]
7951 [controller setDelegate:self.delegate];
7952 [[self navigationController] pushViewController:controller animated:YES];
7955 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7956 if ([indexPath section] != 1)
7958 Source *source = [self sourceAtIndexPath:indexPath];
7959 return [source record] != nil;
7962 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7963 _assert([indexPath section] == 1);
7964 if (editingStyle == UITableViewCellEditingStyleDelete) {
7965 Source *source = [self sourceAtIndexPath:indexPath];
7966 if (source == nil) return;
7968 [Sources_ removeObjectForKey:[source key]];
7970 [self.delegate syncData];
7974 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
7975 [self updateButtonsForEditingStatusAnimated:YES];
7979 [self.delegate addTrivialSource:href_];
7982 [self.delegate syncData];
7985 - (NSString *) getWarning {
7986 NSString *href(href_);
7987 NSRange colon([href rangeOfString:@"://"]);
7988 if (colon.location != NSNotFound)
7989 href = [href substringFromIndex:(colon.location + 3)];
7990 href = [href stringByAddingPercentEscapes];
7991 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7993 NSURL *url([NSURL URLWithString:href]);
7995 NSStringEncoding encoding;
7996 NSError *error(nil);
7998 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7999 return [warning length] == 0 ? nil : warning;
8003 - (void) _endConnection:(NSURLConnection *)connection {
8004 // XXX: the memory management in this method is horribly awkward
8006 NSURLConnection **field = NULL;
8007 if (connection == trivial_bz2_)
8008 field = &trivial_bz2_;
8009 else if (connection == trivial_gz_)
8010 field = &trivial_gz_;
8011 _assert(field != NULL);
8012 [connection release];
8016 trivial_bz2_ == nil &&
8019 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8021 [self.delegate releaseNetworkActivityIndicator];
8023 [self.delegate removeProgressHUD:hud_];
8027 if (warning != nil) {
8028 UIAlertView *alert = [[[UIAlertView alloc]
8029 initWithTitle:UCLocalize("SOURCE_WARNING")
8032 cancelButtonTitle:UCLocalize("CANCEL")
8034 UCLocalize("ADD_ANYWAY"),
8038 [alert setContext:@"warning"];
8039 [alert setNumberOfRows:1];
8042 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8048 } else if (error_ != nil) {
8049 UIAlertView *alert = [[[UIAlertView alloc]
8050 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8051 message:[error_ localizedDescription]
8053 cancelButtonTitle:UCLocalize("OK")
8054 otherButtonTitles:nil
8057 [alert setContext:@"urlerror"];
8062 UIAlertView *alert = [[[UIAlertView alloc]
8063 initWithTitle:UCLocalize("NOT_REPOSITORY")
8064 message:UCLocalize("NOT_REPOSITORY_EX")
8066 cancelButtonTitle:UCLocalize("OK")
8067 otherButtonTitles:nil
8070 [alert setContext:@"trivial"];
8080 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8081 switch ([response statusCode]) {
8087 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8088 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8090 [self _endConnection:connection];
8093 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8094 [self _endConnection:connection];
8097 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8098 NSURL *url([NSURL URLWithString:href]);
8100 NSMutableURLRequest *request = [NSMutableURLRequest
8102 cachePolicy:NSURLRequestUseProtocolCachePolicy
8106 [request setHTTPMethod:method];
8108 if (Machine_ != NULL)
8109 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8111 if (UniqueID_ != nil)
8112 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8114 if ([url isCydiaSecure]) {
8115 if (UniqueID_ != nil)
8116 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8119 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8122 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8123 NSString *context([alert context]);
8125 if ([context isEqualToString:@"source"]) {
8128 NSString *href = [[alert textField] text];
8129 href = VerifySource(href);
8134 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8135 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8139 // XXX: this is stupid
8140 hud_ = [self.delegate addProgressHUD];
8141 [hud_ setText:UCLocalize("VERIFYING_URL")];
8142 [self.delegate retainNetworkActivityIndicator];
8151 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8152 } else if ([context isEqualToString:@"trivial"])
8153 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8154 else if ([context isEqualToString:@"urlerror"])
8155 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8156 else if ([context isEqualToString:@"warning"]) {
8159 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8168 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8172 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8173 BOOL editing([list_ isEditing]);
8176 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8177 initWithTitle:UCLocalize("ADD")
8178 style:UIBarButtonItemStylePlain
8180 action:@selector(addButtonClicked)
8181 ] autorelease] animated:animated];
8182 else if ([self.delegate updating])
8183 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8184 initWithTitle:UCLocalize("CANCEL")
8185 style:UIBarButtonItemStyleDone
8187 action:@selector(cancelButtonClicked)
8188 ] autorelease] animated:animated];
8190 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8191 initWithTitle:UCLocalize("REFRESH")
8192 style:UIBarButtonItemStylePlain
8194 action:@selector(refreshButtonClicked)
8195 ] autorelease] animated:animated];
8197 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8198 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8199 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8201 action:@selector(editButtonClicked)
8202 ] autorelease] animated:animated];
8206 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8207 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8208 [list_ setRowHeight:53];
8209 [(UITableView *) list_ setDataSource:self];
8210 [list_ setDelegate:self];
8211 [self setView:list_];
8214 - (void) viewDidLoad {
8215 [super viewDidLoad];
8217 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8218 [self updateButtonsForEditingStatusAnimated:NO];
8221 - (void) viewWillAppear:(BOOL)animated {
8222 [super viewWillAppear:animated];
8224 [list_ setEditing:NO];
8225 [self updateButtonsForEditingStatusAnimated:NO];
8228 - (void) releaseSubviews {
8233 [super releaseSubviews];
8236 - (id) initWithDatabase:(Database *)database {
8237 if ((self = [super init]) != nil) {
8238 database_ = database;
8242 - (void) reloadData {
8244 [self updateButtonsForEditingStatusAnimated:YES];
8246 @synchronized (database_) {
8247 era_ = [database_ era];
8249 sources_ = [NSMutableArray arrayWithCapacity:16];
8250 [sources_ addObjectsFromArray:[database_ sources]];
8252 [sources_ sortUsingSelector:@selector(compareByName:)];
8255 int count([sources_ count]);
8257 for (int i = 0; i != count; i++) {
8258 if ([[sources_ objectAtIndex:i] record] == nil)
8266 - (void) showAddSourcePrompt {
8267 UIAlertView *alert = [[[UIAlertView alloc]
8268 initWithTitle:UCLocalize("ENTER_APT_URL")
8271 cancelButtonTitle:UCLocalize("CANCEL")
8273 UCLocalize("ADD_SOURCE"),
8277 [alert setContext:@"source"];
8279 [alert setNumberOfRows:1];
8280 [alert addTextFieldWithValue:@"http://" label:@""];
8282 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8283 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8284 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8285 [traits setKeyboardType:UIKeyboardTypeURL];
8286 // XXX: UIReturnKeyDone
8287 [traits setReturnKeyType:UIReturnKeyNext];
8292 - (void) addButtonClicked {
8293 [self showAddSourcePrompt];
8296 - (void) refreshButtonClicked {
8297 if ([self.delegate requestUpdate])
8298 [self updateButtonsForEditingStatusAnimated:YES];
8301 - (void) cancelButtonClicked {
8302 [self.delegate cancelUpdate];
8305 - (void) editButtonClicked {
8306 [list_ setEditing:![list_ isEditing] animated:YES];
8307 [self updateButtonsForEditingStatusAnimated:YES];
8313 /* Stash Controller {{{ */
8314 @interface StashController : CyteViewController {
8315 _H<UIActivityIndicatorView> spinner_;
8316 _H<UILabel> status_;
8317 _H<UILabel> caption_;
8322 @implementation StashController
8325 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8326 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8327 [self setView:view];
8329 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8331 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8332 CGRect spinrect = [spinner_ frame];
8333 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8334 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8335 [spinner_ setFrame:spinrect];
8336 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8337 [view addSubview:spinner_];
8338 [spinner_ startAnimating];
8341 captrect.size.width = [[self view] frame].size.width;
8342 captrect.size.height = 40.0f;
8343 captrect.origin.x = 0;
8344 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8345 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8346 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8347 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8348 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8349 [caption_ setTextColor:[UIColor whiteColor]];
8350 [caption_ setBackgroundColor:[UIColor clearColor]];
8351 [caption_ setShadowColor:[UIColor blackColor]];
8352 [caption_ setTextAlignment:NSTextAlignmentCenter];
8353 [view addSubview:caption_];
8356 statusrect.size.width = [[self view] frame].size.width;
8357 statusrect.size.height = 30.0f;
8358 statusrect.origin.x = 0;
8359 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8360 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8361 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8362 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8363 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8364 [status_ setTextColor:[UIColor whiteColor]];
8365 [status_ setBackgroundColor:[UIColor clearColor]];
8366 [status_ setShadowColor:[UIColor blackColor]];
8367 [status_ setTextAlignment:NSTextAlignmentCenter];
8368 [view addSubview:status_];
8371 - (void) releaseSubviews {
8376 [super releaseSubviews];
8382 @interface Cydia : CyteApplication <
8383 ConfirmationControllerDelegate,
8387 _H<CyteWindow> window_;
8388 _H<CydiaTabBarController> tabbar_;
8389 _H<CyteTabBarController> emulated_;
8390 _H<AppCacheController> appcache_;
8392 _H<NSMutableArray> essential_;
8393 _H<NSMutableArray> broken_;
8395 Database *database_;
8397 _H<NSURL> starturl_;
8402 _H<StashController> stash_;
8411 @implementation Cydia
8413 - (void) lockSuspend {
8414 if (locked_++ == 0) {
8415 if ($SBSSetInterceptsMenuButtonForever != NULL)
8416 (*$SBSSetInterceptsMenuButtonForever)(true);
8418 [self setIdleTimerDisabled:YES];
8422 - (void) unlockSuspend {
8423 if (--locked_ == 0) {
8424 [self setIdleTimerDisabled:NO];
8426 if ($SBSSetInterceptsMenuButtonForever != NULL)
8427 (*$SBSSetInterceptsMenuButtonForever)(false);
8431 - (void) beginUpdate {
8432 [tabbar_ beginUpdate];
8435 - (void) cancelUpdate {
8436 [tabbar_ cancelUpdate];
8439 - (bool) requestUpdate {
8440 if (CyteIsReachable("cydia.saurik.com")) {
8444 UIAlertView *alert = [[[UIAlertView alloc]
8445 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8446 message:@"Host Unreachable" // XXX: Localize
8448 cancelButtonTitle:UCLocalize("OK")
8449 otherButtonTitles:nil
8452 [alert setContext:@"norefresh"];
8460 return [tabbar_ updating];
8464 if ([broken_ count] != 0) {
8465 int count = [broken_ count];
8467 UIAlertView *alert = [[[UIAlertView alloc]
8468 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8469 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8471 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8473 UCLocalize("TEMPORARY_IGNORE"),
8477 [alert setContext:@"fixhalf"];
8478 [alert setNumberOfRows:2];
8480 } else if (!Ignored_ && [essential_ count] != 0) {
8481 int count = [essential_ count];
8483 UIAlertView *alert = [[[UIAlertView alloc]
8484 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8485 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8487 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8489 UCLocalize("UPGRADE_ESSENTIAL"),
8490 UCLocalize("COMPLETE_UPGRADE"),
8494 [alert setContext:@"upgrade"];
8499 - (void) returnToCydia {
8503 - (void) reloadSpringBoard {
8504 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8505 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8507 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8509 system("/usr/bin/killall backboardd SpringBoard");
8512 - (void) _saveConfig {
8513 SaveConfig(database_);
8516 // Navigation controller for the queuing badge.
8517 - (UINavigationController *) queueNavigationController {
8518 NSArray *controllers = [tabbar_ viewControllers];
8519 return [controllers objectAtIndex:3];
8522 - (void) _updateData {
8524 [window_ unloadData];
8526 UINavigationController *navigation = [self queueNavigationController];
8528 id queuedelegate = nil;
8529 if ([[navigation viewControllers] count] > 0)
8530 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8532 [queuedelegate queueStatusDidChange];
8533 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8536 - (void) _refreshIfPossible {
8537 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8539 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
8541 bool recently = false;
8542 if (update != nil) {
8543 NSTimeInterval interval([update timeIntervalSinceNow]);
8544 if (interval > -(15*60))
8548 // Don't automatic refresh if:
8549 // - We already refreshed recently.
8550 // - We already auto-refreshed this launch.
8551 // - Auto-refresh is disabled.
8552 // - Cydia's server is not reachable
8553 if (recently || loaded_ || ManualRefresh || !CyteIsReachable("cydia.saurik.com")) {
8554 // If we are cancelling, we need to make sure it knows it's already loaded.
8557 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8559 // We are going to load, so remember that.
8562 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
8568 - (void) refreshIfPossible {
8569 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8572 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8573 _profile(reloadDataWithInvocation)
8574 @synchronized (self) {
8575 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8577 [hud setText:UCLocalize("RELOADING_DATA")];
8579 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8583 [essential_ removeAllObjects];
8584 [broken_ removeAllObjects];
8586 _profile(reloadDataWithInvocation$Essential)
8587 NSArray *packages([database_ packages]);
8588 for (Package *package in packages) {
8590 [broken_ addObject:package];
8591 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8592 if ([package essential] && [package installed] != nil)
8593 [essential_ addObject:package];
8599 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8602 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8603 [changesItem setBadgeValue:badge];
8604 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8605 [self setApplicationIconBadgeNumber:changes];
8608 [changesItem setBadgeValue:nil];
8609 [changesItem setAnimatedBadge:NO];
8610 [self setApplicationIconBadgeNumber:0];
8617 [self removeProgressHUD:hud];
8624 - (void) updateData {
8628 - (void) updateDataAndLoad {
8630 if ([database_ progressDelegate] == nil)
8636 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8639 - (void) disemulate {
8640 if (emulated_ == nil)
8643 [window_ setRootViewController:tabbar_];
8646 [window_ setUserInteractionEnabled:YES];
8649 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8650 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8652 UIViewController *parent;
8653 if (emulated_ == nil)
8663 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8664 [parent presentModalViewController:navigation animated:YES];
8667 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8668 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8670 if (navigation != nil)
8671 [navigation pushViewController:progress animated:YES];
8673 [self presentModalViewController:progress force:YES];
8675 [progress invoke:invocation withTitle:title];
8679 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8680 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8683 - (void) repairWithInvocation:(NSInvocation *)invocation {
8685 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8689 - (void) repairWithSelector:(SEL)selector {
8690 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8693 - (void) reloadData {
8694 [self reloadDataWithInvocation:nil];
8695 if ([database_ progressDelegate] == nil)
8701 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8704 - (void) addSource:(NSDictionary *) source {
8705 CydiaAddSource(source);
8708 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
8709 CydiaAddSource(href, distribution, sections);
8712 // XXX: this method should not return anything
8713 - (BOOL) addTrivialSource:(NSString *)href {
8714 CydiaAddSource(href, @"./");
8719 pkgProblemResolver *resolver = [database_ resolver];
8721 resolver->InstallProtect();
8722 if (!resolver->Resolve(true))
8727 // XXX: this is a really crappy way of doing this.
8728 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8729 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8730 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8731 if ([tabbar_ updating])
8732 [tabbar_ cancelUpdate];
8734 if (![database_ prepare])
8737 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8738 [page setDelegate:self];
8739 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8742 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8743 [tabbar_ presentModalViewController:confirm_ animated:YES];
8749 @synchronized (self) {
8754 - (void) clearPackage:(Package *)package {
8755 @synchronized (self) {
8762 - (void) installPackages:(NSArray *)packages {
8763 @synchronized (self) {
8764 for (Package *package in packages)
8771 - (void) installPackage:(Package *)package {
8772 @synchronized (self) {
8779 - (void) removePackage:(Package *)package {
8780 @synchronized (self) {
8787 - (void) distUpgrade {
8788 @synchronized (self) {
8789 if (![database_ upgrade])
8797 system("/usr/bin/uicache");
8802 UIProgressHUD *hud([self addProgressHUD]);
8803 [hud setText:UCLocalize("LOADING")];
8804 [self yieldToSelector:@selector(_uicache)];
8805 [self removeProgressHUD:hud];
8809 [database_ perform];
8810 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8811 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
8814 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8817 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8818 [self unlockSuspend];
8821 - (void) retainNetworkActivityIndicator {
8822 if (activity_++ == 0)
8823 [self setNetworkActivityIndicatorVisible:YES];
8826 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8830 - (void) releaseNetworkActivityIndicator {
8831 if (--activity_ == 0)
8832 [self setNetworkActivityIndicatorVisible:NO];
8835 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8840 - (void) cancelAndClear:(bool)clear {
8841 @synchronized (self) {
8853 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8854 NSString *context([alert context]);
8856 if ([context isEqualToString:@"conffile"]) {
8857 FILE *input = [database_ input];
8858 if (button == [alert cancelButtonIndex])
8859 fprintf(input, "N\n");
8860 else if (button == [alert firstOtherButtonIndex])
8861 fprintf(input, "Y\n");
8864 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8865 } else if ([context isEqualToString:@"fixhalf"]) {
8866 if (button == [alert cancelButtonIndex]) {
8867 @synchronized (self) {
8868 for (Package *broken in (id) broken_) {
8870 NSString *id(ShellEscape([broken id]));
8871 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
8872 " /var/lib/dpkg/info/%@.prerm"
8873 " /var/lib/dpkg/info/%@.postrm"
8874 " /var/lib/dpkg/info/%@.preinst"
8875 " /var/lib/dpkg/info/%@.postinst"
8876 " /var/lib/dpkg/info/%@.extrainst_"
8877 "", id, id, id, id, id] UTF8String]);
8883 } else if (button == [alert firstOtherButtonIndex]) {
8884 [broken_ removeAllObjects];
8888 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8889 } else if ([context isEqualToString:@"upgrade"]) {
8890 if (button == [alert firstOtherButtonIndex]) {
8891 @synchronized (self) {
8892 for (Package *essential in (id) essential_)
8893 [essential install];
8898 } else if (button == [alert firstOtherButtonIndex] + 1) {
8900 } else if (button == [alert cancelButtonIndex]) {
8904 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8908 - (void) system:(NSString *)command {
8909 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8912 system([command UTF8String]);
8918 - (void) applicationWillSuspend {
8920 [super applicationWillSuspend];
8923 - (BOOL) isSafeToSuspend {
8926 NSLog(@"isSafeToSuspend: locked_ != 0");
8931 if ([tabbar_ modalViewController] != nil)
8934 // Use external process status API internally.
8935 // This is probably a really bad idea.
8936 // XXX: what is the point of this? does this solve anything at all?
8937 uint64_t status = 0;
8939 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8940 notify_get_state(notify_token, &status);
8941 notify_cancel(notify_token);
8946 NSLog(@"isSafeToSuspend: status != 0");
8952 NSLog(@"isSafeToSuspend: -> true");
8957 - (void) suspendReturningToLastApp:(BOOL)returning {
8958 if ([self isSafeToSuspend])
8959 [super suspendReturningToLastApp:returning];
8963 if ([self isSafeToSuspend])
8967 - (void) applicationSuspend {
8968 if ([self isSafeToSuspend])
8969 [super applicationSuspend];
8972 - (void) applicationSuspend:(GSEventRef)event {
8973 if ([self isSafeToSuspend])
8974 [super applicationSuspend:event];
8977 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8978 if ([self isSafeToSuspend])
8979 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8982 - (void) _setSuspended:(BOOL)value {
8983 if ([self isSafeToSuspend])
8984 [super _setSuspended:value];
8987 - (UIProgressHUD *) addProgressHUD {
8988 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
8989 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8991 [window_ setUserInteractionEnabled:NO];
8993 UIViewController *target(tabbar_);
8994 if (UIViewController *modal = [target modalViewController])
8997 [hud showInView:[target view]];
9003 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9004 [self unlockSuspend];
9006 [hud removeFromSuperview];
9007 [window_ setUserInteractionEnabled:YES];
9010 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9011 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9014 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9015 NSString *scheme([[url scheme] lowercaseString]);
9016 if ([[url absoluteString] length] <= [scheme length] + 3)
9018 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9019 NSArray *components([path componentsSeparatedByString:@"/"]);
9021 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9022 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9023 if (controller != nil)
9024 [controller setDelegate:self];
9028 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9031 NSString *base([components objectAtIndex:0]);
9033 CyteViewController *controller = nil;
9035 if ([base isEqualToString:@"url"]) {
9036 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9037 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9038 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9039 } else if (!external && [components count] == 1) {
9040 if ([base isEqualToString:@"sources"]) {
9041 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9044 if ([base isEqualToString:@"home"]) {
9045 controller = [[[HomeController alloc] init] autorelease];
9048 if ([base isEqualToString:@"sections"]) {
9049 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9052 if ([base isEqualToString:@"search"]) {
9053 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9056 if ([base isEqualToString:@"changes"]) {
9057 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9060 if ([base isEqualToString:@"installed"]) {
9061 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9063 } else if ([components count] == 2) {
9064 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9066 if ([base isEqualToString:@"package"]) {
9067 controller = [self pageForPackage:argument withReferrer:referrer];
9070 if (!external && [base isEqualToString:@"search"]) {
9071 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9074 if (!external && [base isEqualToString:@"sections"]) {
9075 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9077 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9080 if ([base isEqualToString:@"sources"]) {
9081 if ([argument isEqualToString:@"add"]) {
9082 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9083 [(SourcesController *)controller showAddSourcePrompt];
9085 Source *source([database_ sourceWithKey:argument]);
9086 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9090 if (!external && [base isEqualToString:@"launch"]) {
9091 [self launchApplicationWithIdentifier:argument suspended:NO];
9094 } else if (!external && [components count] == 3) {
9095 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9096 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9098 if ([base isEqualToString:@"package"]) {
9099 if ([arg2 isEqualToString:@"settings"]) {
9100 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9101 } else if ([arg2 isEqualToString:@"files"]) {
9102 if (Package *package = [database_ packageWithName:arg1]) {
9103 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9104 [(FileTable *)controller setPackage:package];
9109 if ([base isEqualToString:@"sections"]) {
9110 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9111 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9112 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9116 [controller setDelegate:self];
9120 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9121 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9124 [tabbar_ setUnselectedViewController:page];
9129 - (void) applicationOpenURL:(NSURL *)url {
9130 [super applicationOpenURL:url];
9135 [self openCydiaURL:url forExternal:YES];
9138 - (void) applicationWillResignActive:(UIApplication *)application {
9139 // Stop refreshing if you get a phone call or lock the device.
9140 if ([tabbar_ updating])
9141 [tabbar_ cancelUpdate];
9143 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9144 [super applicationWillResignActive:application];
9147 - (void) saveState {
9148 [[NSDictionary dictionaryWithObjectsAndKeys:
9149 @"InterfaceState", [tabbar_ navigationURLCollection],
9150 @"LastClosed", [NSDate date],
9151 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9152 nil] writeToFile:@ SavedState_ atomically:YES];
9157 - (void) applicationWillTerminate:(UIApplication *)application {
9161 - (void) applicationDidEnterBackground:(UIApplication *)application {
9162 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9163 return [self terminateWithSuccess];
9164 Backgrounded_ = [NSDate date];
9168 - (void) applicationWillEnterForeground:(UIApplication *)application {
9169 if (Backgrounded_ == nil)
9172 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9174 if (interval <= -(30*60)) {
9175 [tabbar_ setSelectedIndex:0];
9176 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9179 if (interval <= -(15*60)) {
9180 if (CyteIsReachable("cydia.saurik.com")) {
9181 [tabbar_ beginUpdate];
9182 [appcache_ reloadURLWithCache:YES];
9186 if ([database_ delocked])
9190 - (void) setConfigurationData:(NSString *)data {
9191 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9193 if (!conffile_r(data)) {
9194 lprintf("E:invalid conffile\n");
9198 NSString *ofile = conffile_r[1];
9199 //NSString *nfile = conffile_r[2];
9201 UIAlertView *alert = [[[UIAlertView alloc]
9202 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9203 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9205 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9207 UCLocalize("ACCEPT_NEW_COPY"),
9208 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9212 [alert setContext:@"conffile"];
9213 [alert setNumberOfRows:2];
9217 - (void) addStashController {
9219 stash_ = [[[StashController alloc] init] autorelease];
9220 [window_ addSubview:[stash_ view]];
9223 - (void) removeStashController {
9224 [[stash_ view] removeFromSuperview];
9226 [self unlockSuspend];
9230 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9231 UpdateExternalStatus(1);
9232 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9233 UpdateExternalStatus(0);
9235 [self removeStashController];
9236 [self reloadSpringBoard];
9239 - (void) applicationDidFinishLaunching:(id)unused {
9240 [super applicationDidFinishLaunching:unused];
9243 @synchronized (BridgedHosts_) {
9244 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9247 [CyteWebViewController _initialize];
9249 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9251 // this would disallow http{,s} URLs from accessing this data
9252 //[WebView registerURLSchemeAsLocal:@"cydia"];
9254 Font12_ = [UIFont systemFontOfSize:12];
9255 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9256 Font14_ = [UIFont systemFontOfSize:14];
9257 Font18_ = [UIFont systemFontOfSize:18];
9258 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9259 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9261 essential_ = [NSMutableArray arrayWithCapacity:4];
9262 broken_ = [NSMutableArray arrayWithCapacity:4];
9264 // XXX: I really need this thing... like, seriously... I'm sorry
9265 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9266 [appcache_ reloadData];
9268 window_ = [[[CyteWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9269 [window_ orderFront:self];
9270 [window_ makeKey:self];
9271 [window_ setHidden:NO];
9273 if (access("/.cydia_no_stash", F_OK) == 0);
9277 [self addStashController];
9278 // XXX: this would be much cleaner as a yieldToSelector:
9279 // that way the removeStashController could happen right here inline
9280 // we also could no longer require the useless stash_ field anymore
9281 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9286 int error(stat("/", &root));
9287 _assert(error != -1);
9289 #define Stash_(path) do { \
9290 struct stat folder; \
9291 int error(lstat((path), &folder)); \
9292 if (error != -1 && ( \
9293 folder.st_dev == root.st_dev && \
9294 S_ISDIR(folder.st_mode) \
9295 ) || error == -1 && ( \
9296 errno == ENOENT || \
9301 Stash_("/Applications");
9302 Stash_("/Library/Ringtones");
9303 Stash_("/Library/Wallpaper");
9304 //Stash_("/usr/bin");
9305 Stash_("/usr/include");
9306 Stash_("/usr/share");
9307 //Stash_("/var/lib");
9311 database_ = [Database sharedInstance];
9312 [database_ setDelegate:self];
9314 [window_ setUserInteractionEnabled:NO];
9316 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9318 [tabbar_ addViewControllers:nil,
9319 @"Cydia", @"home.png", @"home7.png", @"home7s.png",
9320 UCLocalize("SOURCES"), @"install.png", @"install7.png", @"install7s.png",
9321 UCLocalize("CHANGES"), @"changes.png", @"changes7.png", @"changes7s.png",
9322 UCLocalize("INSTALLED"), @"manage.png", @"manage7.png", @"manage7s.png",
9323 UCLocalize("SEARCH"), @"search.png", @"search7.png", @"search7s.png",
9326 [tabbar_ setUpdateDelegate:self];
9328 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9329 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9330 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9332 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9333 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9334 [emulated_ setSelectedIndex:0];
9336 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9337 [emulated_ concealTabBarSelection];
9339 [window_ setRootViewController:emulated_];
9341 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9345 - (NSArray *) defaultStartPages {
9346 NSMutableArray *standard = [NSMutableArray array];
9347 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9348 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9349 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9350 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9351 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9357 if ([emulated_ modalViewController] != nil)
9358 [emulated_ dismissModalViewControllerAnimated:YES];
9359 [window_ setUserInteractionEnabled:NO];
9361 [self reloadDataWithInvocation:nil];
9362 [self refreshIfPossible];
9365 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9367 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9368 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9369 int standardIndex = 0;
9370 NSArray *standard = [self defaultStartPages];
9377 NSDate *closed = [state objectForKey:@"LastClosed"];
9378 if (valid && closed != nil) {
9379 NSTimeInterval interval([closed timeIntervalSinceNow]);
9380 if (interval <= -(30*60))
9384 if (valid && [saved count] != [standard count])
9388 for (unsigned int i = 0; i < [standard count]; i++) {
9389 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9390 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9391 // but it's good enough for now.
9392 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9399 NSArray *items = nil;
9401 [tabbar_ setSelectedIndex:savedIndex];
9404 [tabbar_ setSelectedIndex:standardIndex];
9408 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9409 NSArray *stack = [items objectAtIndex:tab];
9410 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9411 NSMutableArray *current = [NSMutableArray array];
9413 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9414 NSString *addr = [stack objectAtIndex:nav];
9415 NSURL *url = [NSURL URLWithString:addr];
9416 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9418 [current addObject:page];
9421 [navigation setViewControllers:current];
9424 // (Try to) show the startup URL.
9425 if (starturl_ != nil) {
9426 [self openCydiaURL:starturl_ forExternal:YES];
9431 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9433 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9434 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9437 if (item != nil && IsWildcat_) {
9438 [sheet showFromBarButtonItem:item animated:YES];
9440 [sheet showInView:window_];
9444 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9445 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9446 [progress setTitle:task];
9447 [progress addProgressEvent:event];
9450 - (void) addProgressEventForTask:(NSArray *)data {
9451 CydiaProgressEvent *event([data objectAtIndex:0]);
9452 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9453 [self addProgressEvent:event forTask:task];
9456 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9457 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9463 id Alloc_(id self, SEL selector) {
9464 id object = alloc_(self, selector);
9465 lprintf("[%s]A-%p\n", self->isa->name, object);
9470 id Dealloc_(id self, SEL selector) {
9471 id object = dealloc_(self, selector);
9472 lprintf("[%s]D-%p\n", self->isa->name, object);
9476 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9479 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9481 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9483 return [(NSMutableDictionary *) copy autorelease];
9486 int main_store(int, char *argv[]);
9488 int main(int argc, char *argv[]) {
9490 const char *argv0(argv[0]);
9491 if (const char *slash = strrchr(argv0, '/'))
9494 else if (!strcmp(argv0, "store"))
9495 return main_store(argc, argv);
9498 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9502 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9506 CyteInitialize(@"Cydia", Cydia_);
9507 UpdateExternalStatus(0);
9509 RegEx pattern("([0-9]+\\.[0-9]+).*");
9511 UIDevice *device([UIDevice currentDevice]);
9512 if (pattern([device systemVersion]))
9513 Firmware_ = pattern[1];
9515 if (pattern(Cydia_))
9516 Major_ = pattern[1];
9518 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9519 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9520 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9522 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@/%@", IsWildcat_ ? @"ipad" : @"iphone", Major_]);
9523 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9525 /* Set Locale {{{ */
9526 Locale_ = CFLocaleCopyCurrent();
9527 Languages_ = [NSLocale preferredLanguages];
9529 std::string languages;
9530 const char *translation(NULL);
9532 // XXX: this isn't really a language, but this is compatible with older Cydia builds
9533 if (Locale_ != NULL)
9534 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
9535 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
9536 if (pattern(language)) {
9537 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
9538 languages += translation;
9543 if (Languages_ != nil)
9544 for (NSString *locale : Languages_) {
9545 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
9546 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
9547 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
9548 language = [NSString stringWithFormat:@"%@-%@", language, script];
9549 languages += [language UTF8String];
9554 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
9556 /* Index Collation {{{ */
9557 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
9558 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
9559 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
9560 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
9561 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
9562 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
9564 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
9566 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
9567 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
9568 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})
9569 CollationOffset_.push_back(offset);
9570 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];
9571 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];
9574 CollationThumbs_ = [collation sectionIndexTitles];
9575 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
9576 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
9578 CollationTitles_ = [collation sectionTitles];
9579 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
9581 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
9582 if (&transform != NULL && transform != nil) {
9583 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
9584 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
9585 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
9586 UErrorCode code(U_ZERO_ERROR);
9587 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
9588 if (!U_SUCCESS(code))
9589 NSLog(@"%s", u_errorName(code));
9593 } @catch (NSException *e) {
9597 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
9599 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];
9600 for (NSInteger offset(0); offset != 28; ++offset)
9601 CollationOffset_.push_back(offset);
9603 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];
9604 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];
9608 App_ = [[NSBundle mainBundle] bundlePath];
9611 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
9612 mkdir([Cache_ UTF8String], 0755);
9614 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9615 alloc_ = alloc->method_imp;
9616 alloc->method_imp = (IMP) &Alloc_;*/
9618 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9619 dealloc_ = dealloc->method_imp;
9620 dealloc->method_imp = (IMP) &Dealloc_;*/
9622 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
9623 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
9624 UniqueID_ = UniqueIdentifier(device);
9626 /* System Information {{{ */
9630 size = sizeof(maxproc);
9631 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9632 perror("sysctlbyname(\"kern.maxproc\", ?)");
9633 else if (maxproc < 64) {
9635 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9636 perror("sysctlbyname(\"kern.maxproc\", #)");
9639 /* Load Database {{{ */
9640 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9643 mkdir("/var/mobile/Library/Cydia", 0755);
9644 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
9647 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
9648 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
9649 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
9650 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
9653 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
9656 Values_ = [metadata objectForKey:@"Values"];
9658 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
9660 if (Sections_ == nil)
9661 Sections_ = [metadata objectForKey:@"Sections"];
9662 if (Sections_ == nil)
9663 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9665 if (Sources_ == nil)
9666 Sources_ = [metadata objectForKey:@"Sources"];
9667 if (Sources_ == nil)
9668 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9670 // XXX: this wrong, but in a way that doesn't matter :/
9671 if (Version_ == nil)
9672 Version_ = [metadata objectForKey:@"Version"];
9673 if (Version_ == nil)
9674 Version_ = [NSNumber numberWithUnsignedInt:0];
9676 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
9678 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
9681 NSLog(@"unable to import package preferences... from 2010? oh well :/");
9684 if ([Version_ unsignedIntValue] == 0) {
9685 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9686 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9687 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9688 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
9690 Version_ = [NSNumber numberWithUnsignedInt:1];
9692 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
9693 [cache removeObjectForKey:@"LastUpdate"];
9694 [cache writeToFile:@ CacheState_ atomically:YES];
9698 _H<NSMutableArray> broken([NSMutableArray array]);
9699 for (NSString *key in (id) Sources_)
9700 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
9701 [broken addObject:key];
9702 if ([broken count] != 0)
9703 for (NSString *key in (id) broken)
9704 [Sources_ removeObjectForKey:key];
9708 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
9711 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9713 if (kCFCoreFoundationVersionNumber > 1000)
9714 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
9716 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9718 if (access("/User", F_OK) != 0 || version != 6) {
9720 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
9724 if (access("/tmp/cydia.chk", F_OK) == 0) {
9725 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
9726 _assert(errno == ENOENT);
9727 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
9728 _assert(errno == ENOENT);
9731 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
9733 /* APT Initialization {{{ */
9734 _assert(pkgInitConfig(*_config));
9735 _assert(pkgInitSystem(*_config, _system));
9737 _config->Set("Acquire::AllowInsecureRepositories", true);
9738 _config->Set("Acquire::Check-Valid-Until", false);
9739 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
9741 _config->Set("pkgCacheGen::ForceEssential", "");
9743 if (translation != NULL)
9744 _config->Set("APT::Acquire::Translation", translation);
9745 _config->Set("Acquire::Languages", languages);
9747 // XXX: this timeout might be important :(
9748 //_config->Set("Acquire::http::Timeout", 15);
9751 size = sizeof(usermem);
9752 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
9754 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
9756 mkdir([Cache("archives") UTF8String], 0755);
9757 mkdir([Cache("archives/partial") UTF8String], 0755);
9758 _config->Set("Dir::Cache", [Cache_ UTF8String]);
9760 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
9761 _config->Set("Dir::State", [Cache_ UTF8String]);
9763 mkdir([Cache("lists") UTF8String], 0755);
9764 mkdir([Cache("lists/partial") UTF8String], 0755);
9765 mkdir([Cache("periodic") UTF8String], 0755);
9766 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
9768 std::string logs("/var/mobile/Library/Logs/Cydia");
9769 mkdir(logs.c_str(), 0755);
9770 _config->Set("Dir::Log", logs);
9772 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
9774 /* Color Choices {{{ */
9775 space_ = CGColorSpaceCreateDeviceRGB();
9777 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9778 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9779 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9780 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
9781 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9782 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9783 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9784 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9785 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9786 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9788 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9789 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9791 /* UIKit Configuration {{{ */
9792 // XXX: I have a feeling this was important
9793 //UIKeyboardDisableAutomaticAppearance();
9796 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
9797 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
9799 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
9800 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
9801 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
9803 PulseInterval_ = fast ? 50000 : 500000;
9805 Colon_ = UCLocalize("COLON_DELIMITED");
9806 Elision_ = UCLocalize("ELISION");
9807 Error_ = UCLocalize("ERROR");
9808 Warning_ = UCLocalize("WARNING");
9811 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9813 CGColorSpaceRelease(space_);