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<NSMutableDictionary> SessionData_;
700 static _H<NSMutableSet> BridgedHosts_;
701 static _H<NSMutableSet> InsecureHosts_;
703 static NSString *kCydiaProgressEventTypeError = @"Error";
704 static NSString *kCydiaProgressEventTypeInformation = @"Information";
705 static NSString *kCydiaProgressEventTypeStatus = @"Status";
706 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
709 /* Display Helpers {{{ */
710 inline float Interpolate(float begin, float end, float fraction) {
711 return (end - begin) * fraction + begin;
714 static inline double Retina(double value) {
715 value *= ScreenScale_;
716 value = round(value);
717 value /= ScreenScale_;
721 static inline CGRect Retina(CGRect value) {
722 value.origin.x *= ScreenScale_;
723 value.origin.y *= ScreenScale_;
724 value.size.width *= ScreenScale_;
725 value.size.height *= ScreenScale_;
726 value = CGRectIntegral(value);
727 value.origin.x /= ScreenScale_;
728 value.origin.y /= ScreenScale_;
729 value.size.width /= ScreenScale_;
730 value.size.height /= ScreenScale_;
734 static _finline const char *StripVersion_(const char *version) {
735 const char *colon(strchr(version, ':'));
736 return colon == NULL ? version : colon + 1;
739 NSString *LocalizeSection(NSString *section) {
740 static RegEx title_r("(.*?) \\((.*)\\)");
741 if (title_r(section)) {
742 NSString *parent(title_r[1]);
743 NSString *child(title_r[2]);
745 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
746 LocalizeSection(parent),
747 LocalizeSection(child)
751 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
754 NSString *Simplify(NSString *title) {
755 const char *data = [title UTF8String];
756 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
758 static RegEx square_r("\\[(.*)\\]");
759 if (square_r(data, size))
760 return Simplify(square_r[1]);
762 static RegEx paren_r("\\((.*)\\)");
763 if (paren_r(data, size))
764 return Simplify(paren_r[1]);
766 static RegEx title_r("(.*?) \\((.*)\\)");
767 if (title_r(data, size))
768 return Simplify(title_r[1]);
774 bool isSectionVisible(NSString *section) {
775 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
776 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
777 return hidden == nil || ![hidden boolValue];
780 static NSString *VerifySource(NSString *href) {
781 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
783 [[[[UIAlertView alloc]
784 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
785 message:UCLocalize("INVALID_URL_EX")
787 cancelButtonTitle:UCLocalize("OK")
788 otherButtonTitles:nil
789 ] autorelease] show];
794 if (![href hasSuffix:@"/"])
795 href = [href stringByAppendingString:@"/"];
801 /* Delegate Prototypes {{{ */
804 @class CydiaProgressEvent;
806 @protocol DatabaseDelegate
807 - (void) repairWithSelector:(SEL)selector;
808 - (void) setConfigurationData:(NSString *)data;
809 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
812 @class CYPackageController;
814 @protocol SourceDelegate
815 - (void) setFetch:(NSNumber *)fetch;
818 @protocol FetchDelegate
819 - (bool) isSourceCancelled;
820 - (void) startSourceFetch:(NSString *)uri;
821 - (void) stopSourceFetch:(NSString *)uri;
824 @protocol CydiaDelegate
825 - (void) returnToCydia;
827 - (void) retainNetworkActivityIndicator;
828 - (void) releaseNetworkActivityIndicator;
829 - (void) clearPackage:(Package *)package;
830 - (void) installPackage:(Package *)package;
831 - (void) installPackages:(NSArray *)packages;
832 - (void) removePackage:(Package *)package;
833 - (void) beginUpdate;
835 - (bool) requestUpdate;
836 - (void) distUpgrade;
839 - (void) _saveConfig;
841 - (void) addSource:(NSDictionary *)source;
842 - (BOOL) addTrivialSource:(NSString *)href;
843 - (UIProgressHUD *) addProgressHUD;
844 - (void) removeProgressHUD:(UIProgressHUD *)hud;
845 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
846 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
850 /* CancelStatus {{{ */
852 public pkgAcquireStatus
863 virtual bool MediaChange(std::string media, std::string drive) {
867 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
871 virtual bool Pulse_(pkgAcquire *Owner) = 0;
873 virtual bool Pulse(pkgAcquire *Owner) {
874 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
882 _finline bool WasCancelled() const {
887 /* DelegateStatus {{{ */
892 _transient NSObject<ProgressDelegate> *delegate_;
900 void setDelegate(NSObject<ProgressDelegate> *delegate) {
901 delegate_ = delegate;
904 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
905 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
906 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
907 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
910 virtual void Done(pkgAcquire::ItemDesc &desc) {
911 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
912 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
913 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
916 virtual void Fail(pkgAcquire::ItemDesc &desc) {
918 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
919 desc.Owner->Status == pkgAcquire::Item::StatDone
923 std::string &error(desc.Owner->ErrorText);
927 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
928 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
931 virtual bool Pulse_(pkgAcquire *Owner) {
933 double(CurrentBytes + CurrentItems) /
934 double(TotalBytes + TotalItems)
937 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
938 [NSNumber numberWithDouble:percent], @"Percent",
940 [NSNumber numberWithDouble:CurrentBytes], @"Current",
941 [NSNumber numberWithDouble:TotalBytes], @"Total",
942 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
943 nil] waitUntilDone:YES];
945 return ![delegate_ isProgressCancelled];
948 virtual void Start() {
949 pkgAcquireStatus::Start();
950 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
953 virtual void Stop() {
954 pkgAcquireStatus::Stop();
955 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
956 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
960 /* Database Interface {{{ */
961 typedef std::map< unsigned long, _H<Source> > SourceMap;
963 @interface Database : NSObject {
971 pkgDepCache::Policy *policy_;
972 pkgRecords *records_;
973 pkgProblemResolver *resolver_;
974 pkgAcquire *fetcher_;
976 SPtr<pkgPackageManager> manager_;
977 pkgSourceList *list_;
979 SourceMap sourceMap_;
980 _H<NSMutableArray> sourceList_;
982 _H<NSArray> packages_;
984 _transient NSObject<DatabaseDelegate> *delegate_;
985 _transient NSObject<ProgressDelegate> *progress_;
993 std::map<const char *, _H<NSString> > sections_;
996 + (Database *) sharedInstance;
998 - (bool) hasPackages;
1000 - (void) _readCydia:(NSNumber *)fd;
1001 - (void) _readStatus:(NSNumber *)fd;
1002 - (void) _readOutput:(NSNumber *)fd;
1006 - (Package *) packageWithName:(NSString *)name;
1008 - (pkgCacheFile &) cache;
1009 - (pkgDepCache::Policy *) policy;
1010 - (pkgRecords *) records;
1011 - (pkgProblemResolver *) resolver;
1012 - (pkgAcquire &) fetcher;
1013 - (pkgSourceList &) list;
1014 - (NSArray *) packages;
1015 - (NSArray *) sources;
1016 - (Source *) sourceWithKey:(NSString *)key;
1017 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1025 - (void) updateWithStatus:(CancelStatus &)status;
1027 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1029 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1030 - (NSObject<ProgressDelegate> *) progressDelegate;
1032 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1033 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1034 - (void) resetFetch;
1036 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1040 /* SourceStatus {{{ */
1041 class SourceStatus :
1045 _transient NSObject<FetchDelegate> *delegate_;
1046 _transient Database *database_;
1047 std::set<std::string> fetches_;
1050 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1051 delegate_(delegate),
1056 void Set(bool fetch, const std::string &uri) {
1058 if (!fetches_.insert(uri).second)
1061 if (fetches_.erase(uri) == 0)
1065 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1067 auto slash(uri.rfind('/'));
1068 if (slash != std::string::npos)
1069 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1072 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1073 /*unsigned long ID(fetch ? 1 : 0);
1077 Set(fetch, item->DescURI());
1080 void Log(const char *tag, pkgAcquire::Item *item) {
1081 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1084 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1085 Log("Fetch", desc.Owner);
1086 Set(true, desc.Owner);
1089 virtual void Done(pkgAcquire::ItemDesc &desc) {
1090 Log("Done", desc.Owner);
1091 Set(false, desc.Owner);
1094 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1095 Log("Fail", desc.Owner);
1096 Set(false, desc.Owner);
1099 virtual bool Pulse_(pkgAcquire *Owner) {
1100 std::set<std::string> fetches;
1101 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1103 if ((*item)->QueueCounter == 0)
1105 else switch ((*item)->Status) {
1106 case pkgAcquire::Item::StatFetching:
1107 fetches.insert((*item)->DescURI());
1116 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1120 std::vector<std::string> stops;
1121 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1122 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1123 //printf("Stop(%s)\n", stop->c_str());
1127 return ![delegate_ isSourceCancelled];
1130 virtual void Stop() {
1131 pkgAcquireStatus::Stop();
1132 [database_ resetFetch];
1136 /* ProgressEvent Implementation {{{ */
1137 @implementation CydiaProgressEvent
1139 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1140 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1143 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1144 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1145 [event setPackage:package];
1149 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1150 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1152 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1153 NSArray *fields([description componentsSeparatedByString:@" "]);
1154 [event setItem:fields];
1156 if ([fields count] > 3) {
1157 [event setPackage:[fields objectAtIndex:2]];
1158 [event setVersion:[fields objectAtIndex:3]];
1161 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1166 + (NSArray *) _attributeKeys {
1167 return [NSArray arrayWithObjects:
1177 - (NSArray *) attributeKeys {
1178 return [[self class] _attributeKeys];
1181 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1182 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1185 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1186 if ((self = [super init]) != nil) {
1192 - (NSString *) message {
1196 - (NSString *) type {
1200 - (NSArray *) item {
1201 return (id) item_ ?: [NSNull null];
1204 - (void) setItem:(NSArray *)item {
1208 - (NSString *) package {
1209 return (id) package_ ?: [NSNull null];
1212 - (void) setPackage:(NSString *)package {
1216 - (NSString *) url {
1217 return (id) url_ ?: [NSNull null];
1220 - (void) setURL:(NSString *)url {
1224 - (void) setVersion:(NSString *)version {
1228 - (NSString *) version {
1229 return (id) version_ ?: [NSNull null];
1232 - (NSString *) compound:(NSString *)value {
1234 NSString *mode(nil); {
1235 NSString *type([self type]);
1236 if ([type isEqualToString:kCydiaProgressEventTypeError])
1237 mode = UCLocalize("ERROR");
1238 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1239 mode = UCLocalize("WARNING");
1243 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1249 - (NSString *) compoundMessage {
1250 return [self compound:[self message]];
1253 - (NSString *) compoundTitle {
1256 if (package_ == nil)
1258 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1259 title = [package name];
1263 return [self compound:title];
1269 // Cytore Definitions {{{
1270 struct PackageValue :
1273 Cytore::Offset<PackageValue> next_;
1275 uint32_t index_ : 23;
1276 uint32_t subscribed_ : 1;
1293 Cytore::Offset<PackageValue> packages_[1 << 16];
1296 static Cytore::File<MetaValue> MetaFile_;
1298 // Cytore Helper Functions {{{
1299 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1300 SplitHash nhash = { hashlittle(name, length) };
1302 PackageValue *metadata;
1304 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1305 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1306 *offset = MetaFile_.New<PackageValue>(length + 1);
1307 metadata = &MetaFile_.Get(*offset);
1309 if (metadata == NULL) {
1313 metadata = new PackageValue();
1314 memset(metadata, 0, sizeof(*metadata));
1317 memcpy(metadata->name_, name, length);
1318 metadata->name_[length] = '\0';
1319 metadata->nhash_ = nhash.u16[1];
1321 metadata = &MetaFile_.Get(*offset);
1322 if (metadata->nhash_ != nhash.u16[1])
1324 if (strncmp(metadata->name_, name, length) != 0)
1326 if (metadata->name_[length] != '\0')
1333 static void PackageImport(const void *key, const void *value, void *context) {
1334 bool &fail(*reinterpret_cast<bool *>(context));
1337 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1338 NSLog(@"failed to import package %@", key);
1342 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1343 NSDictionary *package((NSDictionary *) value);
1345 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1346 if ([subscribed boolValue] && !metadata->subscribed_)
1347 metadata->subscribed_ = true;
1349 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1350 time_t time([date timeIntervalSince1970]);
1351 if (metadata->first_ > time || metadata->first_ == 0)
1352 metadata->first_ = time;
1355 NSDate *date([package objectForKey:@"LastSeen"]);
1356 NSString *version([package objectForKey:@"LastVersion"]);
1358 if (date != nil && version != nil) {
1359 time_t time([date timeIntervalSince1970]);
1360 if (metadata->last_ < time || metadata->last_ == 0)
1361 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1362 size_t length(strlen(buffer));
1363 uint16_t vhash(hashlittle(buffer, length));
1365 size_t capped(std::min<size_t>(8, length));
1366 char *latest(buffer + length - capped);
1368 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1369 metadata->vhash_ = vhash;
1371 metadata->last_ = time;
1377 static NSDate *GetStatusDate() {
1378 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1381 static void SaveConfig(NSObject *lock) {
1382 @synchronized (lock) {
1388 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1389 Values_, @"CydiaValues",
1390 Sections_, @"CydiaSections",
1391 (id) Sources_, @"CydiaSources",
1392 Version_, @"CydiaVersion",
1393 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1395 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1396 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1398 CydiaWriteSources();
1401 /* Source Class {{{ */
1402 @interface Source : NSObject {
1404 Database *database_;
1407 CYString depiction_;
1408 CYString description_;
1414 CYString distribution_;
1420 _H<NSString> authority_;
1422 CYString defaultIcon_;
1424 _H<NSMutableDictionary> record_;
1427 std::set<std::string> fetches_;
1428 std::set<std::string> files_;
1429 _transient NSObject<SourceDelegate> *delegate_;
1432 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1434 - (NSComparisonResult) compareByName:(Source *)source;
1436 - (NSString *) depictionForPackage:(NSString *)package;
1437 - (NSString *) supportForPackage:(NSString *)package;
1439 - (metaIndex *) metaIndex;
1440 - (NSDictionary *) record;
1443 - (NSString *) rooturi;
1444 - (NSString *) distribution;
1445 - (NSString *) type;
1448 - (NSString *) host;
1450 - (NSString *) name;
1451 - (NSString *) shortDescription;
1452 - (NSString *) label;
1453 - (NSString *) origin;
1454 - (NSString *) version;
1456 - (NSString *) defaultIcon;
1457 - (NSURL *) iconURL;
1459 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1460 - (void) resetFetch;
1464 @implementation Source
1466 + (NSString *) webScriptNameForSelector:(SEL)selector {
1468 else if (selector == @selector(addSection:))
1469 return @"addSection";
1470 else if (selector == @selector(getField:))
1472 else if (selector == @selector(removeSection:))
1473 return @"removeSection";
1474 else if (selector == @selector(remove))
1480 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1481 return [self webScriptNameForSelector:selector] == nil;
1484 + (NSArray *) _attributeKeys {
1485 return [NSArray arrayWithObjects:
1496 @"shortDescription",
1503 - (NSArray *) attributeKeys {
1504 return [[self class] _attributeKeys];
1507 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1508 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1511 - (metaIndex *) metaIndex {
1515 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1516 trusted_ = index->IsTrusted();
1518 uri_.set(pool, index->GetURI());
1519 distribution_.set(pool, index->GetDist());
1520 type_.set(pool, index->GetType());
1522 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1523 if (dindex != NULL) {
1524 std::string file(dindex->MetaIndexURI(""));
1525 base_.set(pool, file);
1528 _profile(Source$setMetaIndex$GetIndexes)
1529 dindex->GetIndexes(&acquire, true);
1531 _profile(Source$setMetaIndex$DescURI)
1532 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1533 std::string file((*item)->DescURI());
1534 auto slash(file.rfind('/'));
1535 if (slash == std::string::npos)
1537 files_.insert(file.substr(0, slash));
1542 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1545 pkgTagFile tags(&fd);
1547 pkgTagSection section;
1554 {"default-icon", &defaultIcon_},
1555 {"depiction", &depiction_},
1556 {"description", &description_},
1558 {"origin", &origin_},
1559 {"support", &support_},
1560 {"version", &version_},
1563 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1564 const char *start, *end;
1566 if (section.Find(names[i].name_, start, end)) {
1567 CYString &value(*names[i].value_);
1568 value.set(pool, start, end - start);
1574 record_ = [Sources_ objectForKey:[self key]];
1576 NSURL *url([NSURL URLWithString:uri_]);
1580 host_ = [host_ lowercaseString];
1585 authority_ = [url path];
1588 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1589 if ((self = [super init]) != nil) {
1590 era_ = [database era];
1591 database_ = database;
1594 _profile(Source$initWithMetaIndex$setMetaIndex)
1595 [self setMetaIndex:index inPool:pool];
1600 - (NSString *) getField:(NSString *)name {
1601 @synchronized (database_) {
1602 if ([database_ era] != era_ || index_ == NULL)
1605 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1610 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1615 pkgTagFile tags(&fd);
1617 pkgTagSection section;
1620 const char *start, *end;
1621 if (!section.Find([name UTF8String], start, end))
1622 return (NSString *) [NSNull null];
1624 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1627 - (NSComparisonResult) compareByName:(Source *)source {
1628 NSString *lhs = [self name];
1629 NSString *rhs = [source name];
1631 if ([lhs length] != 0 && [rhs length] != 0) {
1632 unichar lhc = [lhs characterAtIndex:0];
1633 unichar rhc = [rhs characterAtIndex:0];
1635 if (isalpha(lhc) && !isalpha(rhc))
1636 return NSOrderedAscending;
1637 else if (!isalpha(lhc) && isalpha(rhc))
1638 return NSOrderedDescending;
1641 return [lhs compare:rhs options:LaxCompareOptions_];
1644 - (NSString *) depictionForPackage:(NSString *)package {
1645 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1648 - (NSString *) supportForPackage:(NSString *)package {
1649 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1652 - (NSArray *) sections {
1653 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1656 - (void) _addSection:(NSString *)section {
1659 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1660 if (![sections containsObject:section])
1661 [sections addObject:section];
1663 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1666 - (bool) addSection:(NSString *)section {
1670 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1674 - (void) _removeSection:(NSString *)section {
1678 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1679 if ([sections containsObject:section])
1680 [sections removeObject:section];
1683 - (bool) removeSection:(NSString *)section {
1687 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1692 [Sources_ removeObjectForKey:[self key]];
1696 bool value(record_ != nil);
1697 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1701 - (NSDictionary *) record {
1709 - (NSString *) rooturi {
1713 - (NSString *) distribution {
1714 return distribution_;
1717 - (NSString *) type {
1721 - (NSString *) baseuri {
1722 return base_.empty() ? nil : (id) base_;
1725 - (NSString *) iconuri {
1726 if (NSString *base = [self baseuri])
1727 return [base stringByAppendingString:@"CydiaIcon.png"];
1732 - (NSURL *) iconURL {
1733 if (NSString *uri = [self iconuri])
1734 return [NSURL URLWithString:uri];
1738 - (NSString *) key {
1739 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1742 - (NSString *) host {
1746 - (NSString *) name {
1747 return origin_.empty() ? (id) authority_ : origin_;
1750 - (NSString *) shortDescription {
1751 return description_;
1754 - (NSString *) label {
1755 return label_.empty() ? (id) authority_ : label_;
1758 - (NSString *) origin {
1762 - (NSString *) version {
1766 - (NSString *) defaultIcon {
1767 return defaultIcon_;
1770 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1771 delegate_ = delegate;
1775 return !fetches_.empty();
1778 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1780 if (fetches_.erase(uri) == 0)
1782 } else if (files_.find(uri) == files_.end())
1784 else if (!fetches_.insert(uri).second)
1787 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1790 - (void) resetFetch {
1792 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1797 /* CydiaOperation Class {{{ */
1798 @interface CydiaOperation : NSObject {
1799 _H<NSString> operator_;
1800 _H<NSString> value_;
1803 - (NSString *) operator;
1804 - (NSString *) value;
1808 @implementation CydiaOperation
1810 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1811 if ((self = [super init]) != nil) {
1812 operator_ = [NSString stringWithUTF8String:_operator];
1813 value_ = [NSString stringWithUTF8String:value];
1817 + (NSArray *) _attributeKeys {
1818 return [NSArray arrayWithObjects:
1824 - (NSArray *) attributeKeys {
1825 return [[self class] _attributeKeys];
1828 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1829 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1832 - (NSString *) operator {
1836 - (NSString *) value {
1842 /* CydiaClause Class {{{ */
1843 @interface CydiaClause : NSObject {
1844 _H<NSString> package_;
1845 _H<CydiaOperation> version_;
1848 - (NSString *) package;
1849 - (CydiaOperation *) version;
1853 @implementation CydiaClause
1855 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1856 if ((self = [super init]) != nil) {
1857 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1859 if (const char *version = dep.TargetVer())
1860 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1862 version_ = (id) [NSNull null];
1866 + (NSArray *) _attributeKeys {
1867 return [NSArray arrayWithObjects:
1873 - (NSArray *) attributeKeys {
1874 return [[self class] _attributeKeys];
1877 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1878 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1881 - (NSString *) package {
1885 - (CydiaOperation *) version {
1891 /* CydiaRelation Class {{{ */
1892 @interface CydiaRelation : NSObject {
1893 _H<NSString> relationship_;
1894 _H<NSMutableArray> clauses_;
1897 - (NSString *) relationship;
1898 - (NSArray *) clauses;
1902 @implementation CydiaRelation
1904 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1905 if ((self = [super init]) != nil) {
1906 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1907 clauses_ = [NSMutableArray arrayWithCapacity:8];
1909 pkgCache::DepIterator start;
1910 pkgCache::DepIterator end;
1911 dep.GlobOr(start, end); // ++dep
1914 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1916 // yes, seriously. (wtf?)
1924 + (NSArray *) _attributeKeys {
1925 return [NSArray arrayWithObjects:
1931 - (NSArray *) attributeKeys {
1932 return [[self class] _attributeKeys];
1935 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1936 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1939 - (NSString *) relationship {
1940 return relationship_;
1943 - (NSArray *) clauses {
1947 - (void) addClause:(CydiaClause *)clause {
1948 [clauses_ addObject:clause];
1953 /* Package Class {{{ */
1954 struct ParsedPackage {
1958 CYString architecture_;
1961 CYString depiction_;
1968 @interface Package : NSObject {
1970 @public uint32_t role_ : 3;
1971 uint32_t essential_ : 1;
1972 uint32_t obsolete_ : 1;
1973 uint32_t ignored_ : 1;
1974 uint32_t pooled_ : 1;
1980 _transient Database *database_;
1982 pkgCache::VerIterator version_;
1983 pkgCache::PkgIterator iterator_;
1984 pkgCache::VerFileIterator file_;
1988 CYString transform_;
1991 CYString installed_;
1994 const char *section_;
1995 _transient NSString *section$_;
1999 PackageValue *metadata_;
2000 ParsedPackage *parsed_;
2002 _H<NSMutableArray> tags_;
2005 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2006 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2008 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2010 - (pkgCache::PkgIterator) iterator;
2013 - (NSString *) section;
2014 - (NSString *) simpleSection;
2016 - (NSString *) longSection;
2017 - (NSString *) shortSection;
2021 - (MIMEAddress *) maintainer;
2023 - (NSString *) longDescription;
2024 - (NSString *) shortDescription;
2027 - (PackageValue *) metadata;
2030 - (bool) subscribed;
2031 - (bool) setSubscribed:(bool)subscribed;
2035 - (NSString *) latest;
2036 - (NSString *) installed;
2037 - (BOOL) uninstalled;
2039 - (BOOL) upgradableAndEssential:(BOOL)essential;
2042 - (BOOL) unfiltered;
2046 - (BOOL) halfConfigured;
2047 - (BOOL) halfInstalled;
2049 - (NSString *) mode;
2052 - (NSString *) name;
2054 - (NSString *) homepage;
2055 - (NSString *) depiction;
2056 - (MIMEAddress *) author;
2058 - (NSString *) support;
2060 - (NSArray *) files;
2061 - (NSArray *) warnings;
2062 - (NSArray *) applications;
2064 - (Source *) source;
2067 - (BOOL) matches:(NSArray *)query;
2069 - (BOOL) hasTag:(NSString *)tag;
2070 - (NSString *) primaryPurpose;
2071 - (NSArray *) purposes;
2072 - (bool) isCommercial;
2074 - (void) setIndex:(size_t)index;
2076 - (CYString &) cyname;
2078 - (uint32_t) compareBySection:(NSArray *)sections;
2085 uint32_t PackageChangesRadix(Package *self, void *) {
2090 uint32_t timestamp : 30;
2091 uint32_t ignored : 1;
2092 uint32_t upgradable : 1;
2096 bool upgradable([self upgradableAndEssential:YES]);
2097 value.bits.upgradable = upgradable ? 1 : 0;
2100 value.bits.timestamp = 0;
2101 value.bits.ignored = [self ignored] ? 0 : 1;
2102 value.bits.upgradable = 1;
2104 value.bits.timestamp = [self seen] >> 2;
2105 value.bits.ignored = 0;
2106 value.bits.upgradable = 0;
2109 return _not(uint32_t) - value.key;
2112 CYString &(*PackageName)(Package *self, SEL sel);
2114 uint32_t PackagePrefixRadix(Package *self, void *context) {
2115 size_t offset(reinterpret_cast<size_t>(context));
2116 CYString &name(PackageName(self, @selector(cyname)));
2118 size_t size(name.size());
2121 char *text(name.data());
2124 if (!isdigit(text[0]))
2128 while (size != digits && isdigit(text[digits]))
2136 if (offset == 0 && zeros != 0) {
2137 memset(data, '0', zeros);
2138 memcpy(data + zeros, text, 4 - zeros);
2140 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2141 if (size <= offset - zeros)
2144 text += offset - zeros;
2145 size -= offset - zeros;
2148 memcpy(data, text, 4);
2150 memcpy(data, text, size);
2151 memset(data + size, 0, 4 - size);
2154 for (size_t i(0); i != 4; ++i)
2155 if (isalpha(data[i]))
2163 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2165 /* XXX: ntohl may be more honest */
2166 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2169 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2170 _profile(PackageNameCompare)
2172 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2173 else if (rhn == NULL)
2174 return kCFCompareGreaterThan;
2176 CFIndex length(CFStringGetLength(lhn));
2178 _profile(PackageNameCompare$NumbersLast)
2179 if (length != 0 && CFStringGetLength(rhn) != 0) {
2180 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2181 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2182 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2183 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2184 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2188 _profile(PackageNameCompare$Compare)
2189 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2194 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2195 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2198 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2199 CYString &lhn(PackageName(lhs, @selector(cyname)));
2200 NSString *rhn(PackageName(rhs, @selector(cyname)));
2201 return StringNameCompare(lhn, rhn, lhn.size());
2204 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2205 return PackageNameCompare(*lhs, *rhs, arg);
2208 struct PackageNameOrdering :
2209 std::binary_function<Package *, Package *, bool>
2211 _finline bool operator ()(Package *lhs, Package *rhs) const {
2212 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2216 @implementation Package
2218 - (NSString *) description {
2219 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2225 if (parsed_ != NULL)
2230 + (NSString *) webScriptNameForSelector:(SEL)selector {
2232 else if (selector == @selector(clear))
2234 else if (selector == @selector(getField:))
2236 else if (selector == @selector(getRecord))
2237 return @"getRecord";
2238 else if (selector == @selector(hasTag:))
2240 else if (selector == @selector(install))
2242 else if (selector == @selector(remove))
2248 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2249 return [self webScriptNameForSelector:selector] == nil;
2252 + (NSArray *) _attributeKeys {
2253 return [NSArray arrayWithObjects:
2274 @"shortDescription",
2287 - (NSArray *) attributeKeys {
2288 return [[self class] _attributeKeys];
2291 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2292 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2295 - (NSArray *) relations {
2296 @synchronized (database_) {
2297 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2298 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2299 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2303 - (NSString *) architecture {
2305 @synchronized (database_) {
2306 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2309 - (NSString *) getField:(NSString *)name {
2310 @synchronized (database_) {
2311 if ([database_ era] != era_ || file_.end())
2314 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2316 const char *start, *end;
2317 if (!parser.Find([name UTF8String], start, end))
2318 return (NSString *) [NSNull null];
2320 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2323 - (NSString *) getRecord {
2324 @synchronized (database_) {
2325 if ([database_ era] != era_ || file_.end())
2328 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2330 const char *start, *end;
2331 parser.GetRec(start, end);
2333 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2337 if (parsed_ != NULL)
2339 @synchronized (database_) {
2340 if ([database_ era] != era_ || file_.end())
2343 ParsedPackage *parsed(new ParsedPackage);
2346 _profile(Package$parse)
2347 pkgRecords::Parser *parser;
2349 _profile(Package$parse$Lookup)
2350 parser = &[database_ records]->Lookup(file_);
2356 _profile(Package$parse$Find)
2361 {"architecture", &parsed->architecture_},
2362 {"icon", &parsed->icon_},
2363 {"depiction", &parsed->depiction_},
2364 {"homepage", &parsed->homepage_},
2365 {"website", &website},
2367 {"support", &parsed->support_},
2368 {"author", &parsed->author_},
2369 {"md5sum", &parsed->md5sum_},
2372 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2373 const char *start, *end;
2375 if (parser->Find(names[i].name_, start, end)) {
2376 CYString &value(*names[i].value_);
2377 _profile(Package$parse$Value)
2378 value.set(pool_, start, end - start);
2384 _profile(Package$parse$Tagline)
2385 parsed->tagline_.set(pool_, parser->ShortDesc());
2388 _profile(Package$parse$Retain)
2389 if (parsed->homepage_.empty())
2390 parsed->homepage_ = website;
2391 if (parsed->homepage_ == parsed->depiction_)
2392 parsed->homepage_.clear();
2393 if (parsed->support_.empty())
2394 parsed->support_ = bugs;
2399 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2400 if ((self = [super init]) != nil) {
2401 _profile(Package$initWithVersion)
2403 pool_ = new CYPool();
2409 database_ = database;
2410 era_ = [database era];
2414 pkgCache::PkgIterator iterator(version_.ParentPkg());
2415 iterator_ = iterator;
2417 _profile(Package$initWithVersion$Version)
2418 file_ = version_.FileList();
2421 _profile(Package$initWithVersion$Cache)
2422 name_.set(NULL, version_.Display());
2424 latest_.set(NULL, StripVersion_(version_.VerStr()));
2426 pkgCache::VerIterator current(iterator.CurrentVer());
2428 installed_.set(NULL, StripVersion_(current.VerStr()));
2431 _profile(Package$initWithVersion$Transliterate) do {
2432 if (CollationTransl_ == NULL)
2437 _profile(Package$initWithVersion$Transliterate$utf8)
2438 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2439 for (size_t i(0), e(name_.size()); i != e; ++i)
2440 if (data[i] >= 0x80)
2445 UErrorCode code(U_ZERO_ERROR);
2448 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2449 CollationString_.resize(name_.size());
2450 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2451 if (!U_SUCCESS(code))
2453 CollationString_.resize(length);
2456 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2457 length = CollationString_.size();
2458 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2459 if (!U_SUCCESS(code))
2461 _assert(CollationString_.size() == length);
2464 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2465 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2466 if (code == U_BUFFER_OVERFLOW_ERROR)
2467 code = U_ZERO_ERROR;
2468 else if (!U_SUCCESS(code))
2473 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2474 transform = pool_->malloc<char>(length);
2476 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2477 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2478 if (!U_SUCCESS(code))
2482 transform_.set(NULL, transform, length);
2483 } while (false); _end
2485 _profile(Package$initWithVersion$Tags)
2487 pkgCache::TagIterator tag(version_.TagList());
2489 pkgCache::TagIterator tag(iterator.TagList());
2492 tags_ = [NSMutableArray arrayWithCapacity:8];
2494 goto tag; for (; !tag.end(); ++tag) tag: {
2495 const char *name(tag.Name());
2496 NSString *string((NSString *) CYStringCreate(name));
2500 [tags_ addObject:[string autorelease]];
2502 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2503 if (strcmp(name + 6, "enduser") == 0)
2505 else if (strcmp(name + 6, "hacker") == 0)
2507 else if (strcmp(name + 6, "developer") == 0)
2509 else if (strcmp(name + 6, "cydia") == 0)
2515 if (strncmp(name, "cydia::", 7) == 0) {
2516 if (strcmp(name + 7, "essential") == 0)
2518 else if (strcmp(name + 7, "obsolete") == 0)
2525 _profile(Package$initWithVersion$Metadata)
2526 const char *mixed(iterator.Name());
2527 size_t size(strlen(mixed));
2528 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2529 char lower[prefix + size + 5 + 1];
2531 for (size_t i(0); i != size; ++i)
2532 lower[prefix + i] = mixed[i] | 0x20;
2534 if (!installed_.empty()) {
2535 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2536 memcpy(lower + prefix + size, ".list", 6);
2538 if (stat(lower, &info) != -1)
2539 upgraded_ = info.st_birthtime;
2542 PackageValue *metadata(PackageFind(lower + prefix, size));
2543 metadata_ = metadata;
2545 id_.set(NULL, metadata->name_, size);
2547 const char *latest(version_.VerStr());
2548 size_t length(strlen(latest));
2550 uint16_t vhash(hashlittle(latest, length));
2552 size_t capped(std::min<size_t>(8, length));
2553 latest = latest + length - capped;
2555 if (metadata->first_ == 0)
2556 metadata->first_ = now_;
2558 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2559 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2560 metadata->vhash_ = vhash;
2561 metadata->last_ = now_;
2562 } else if (metadata->last_ == 0)
2563 metadata->last_ = metadata->first_;
2566 _profile(Package$initWithVersion$Section)
2567 section_ = version_.Section();
2570 _profile(Package$initWithVersion$Flags)
2571 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2572 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2577 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2578 pkgCache::VerIterator version;
2580 _profile(Package$packageWithIterator$GetCandidateVer)
2581 version = [database policy]->GetCandidateVer(iterator);
2589 _profile(Package$packageWithIterator$Allocate)
2590 package = [Package allocWithZone:zone];
2593 _profile(Package$packageWithIterator$Initialize)
2595 initWithVersion:version
2605 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2606 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2607 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2610 - (pkgCache::PkgIterator) iterator {
2614 - (NSArray *) downgrades {
2615 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2617 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2618 if (version == version_)
2620 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2621 if ([package source] == nil)
2623 [versions addObject:package];
2629 - (NSString *) section {
2630 if (section$_ == nil) {
2631 if (section_ == NULL)
2634 _profile(Package$section$mappedSectionForPointer)
2635 section$_ = [database_ mappedSectionForPointer:section_];
2640 - (NSString *) simpleSection {
2641 if (NSString *section = [self section])
2642 return Simplify(section);
2647 - (NSString *) longSection {
2648 if (NSString *section = [self section])
2649 return LocalizeSection(section);
2654 - (NSString *) shortSection {
2655 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2658 - (NSString *) uri {
2661 pkgIndexFile *index;
2662 pkgCache::PkgFileIterator file(file_.File());
2663 if (![database_ list].FindIndex(file, index))
2665 return [NSString stringWithUTF8String:iterator_->Path];
2666 //return [NSString stringWithUTF8String:file.Site()];
2667 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2671 - (MIMEAddress *) maintainer {
2672 @synchronized (database_) {
2673 if ([database_ era] != era_ || file_.end())
2676 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2677 const std::string &maintainer(parser->Maintainer());
2678 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2681 - (NSString *) md5sum {
2682 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2686 @synchronized (database_) {
2687 if ([database_ era] != era_ || version_.end())
2690 return version_->InstalledSize;
2693 - (NSString *) longDescription {
2694 @synchronized (database_) {
2695 if ([database_ era] != era_ || file_.end())
2698 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2699 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2701 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2702 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2703 if ([lines count] < 2)
2706 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2707 for (size_t i(1), e([lines count]); i != e; ++i) {
2708 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2709 [trimmed addObject:trim];
2712 return [trimmed componentsJoinedByString:@"\n"];
2715 - (NSString *) shortDescription {
2716 if (parsed_ != NULL)
2717 return static_cast<NSString *>(parsed_->tagline_);
2719 @synchronized (database_) {
2720 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2721 std::string value(parser.ShortDesc());
2724 if (value.size() > 200)
2726 return [(id) CYStringCreate(value) autorelease];
2730 _profile(Package$index)
2731 CFStringRef name((CFStringRef) [self name]);
2732 if (CFStringGetLength(name) == 0)
2734 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2735 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2737 return toupper(character);
2741 - (PackageValue *) metadata {
2746 PackageValue *metadata([self metadata]);
2747 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2750 - (bool) subscribed {
2751 return [self metadata]->subscribed_;
2754 - (bool) setSubscribed:(bool)subscribed {
2755 PackageValue *metadata([self metadata]);
2756 if (metadata->subscribed_ == subscribed)
2758 metadata->subscribed_ = subscribed;
2766 - (NSString *) latest {
2770 - (NSString *) installed {
2774 - (BOOL) uninstalled {
2775 return installed_.empty();
2778 - (BOOL) upgradableAndEssential:(BOOL)essential {
2779 _profile(Package$upgradableAndEssential)
2780 pkgCache::VerIterator current(iterator_.CurrentVer());
2782 return essential && essential_;
2784 return version_ != current;
2788 - (BOOL) essential {
2793 return [database_ cache][iterator_].InstBroken();
2796 - (BOOL) unfiltered {
2797 _profile(Package$unfiltered$obsolete)
2798 if (_unlikely(obsolete_))
2802 _profile(Package$unfiltered$role)
2803 if (_unlikely(role_ > 3))
2811 if (![self unfiltered])
2816 _profile(Package$visible$section)
2817 section = [self section];
2820 _profile(Package$visible$isSectionVisible)
2821 if (!isSectionVisible(section))
2829 unsigned char current(iterator_->CurrentState);
2830 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2833 - (BOOL) halfConfigured {
2834 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2837 - (BOOL) halfInstalled {
2838 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2842 @synchronized (database_) {
2843 if ([database_ era] != era_ || iterator_.end())
2846 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2847 return state.Mode != pkgDepCache::ModeKeep;
2850 - (NSString *) mode {
2851 @synchronized (database_) {
2852 if ([database_ era] != era_ || iterator_.end())
2855 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2857 switch (state.Mode) {
2858 case pkgDepCache::ModeDelete:
2859 if ((state.iFlags & pkgDepCache::Purge) != 0)
2863 case pkgDepCache::ModeKeep:
2864 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2865 return @"REINSTALL";
2866 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2870 case pkgDepCache::ModeInstall:
2871 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2872 return @"REINSTALL";
2873 else*/ switch (state.Status) {
2875 return @"DOWNGRADE";
2881 return @"NEW_INSTALL";
2892 - (NSString *) name {
2893 return name_.empty() ? id_ : name_;
2896 - (UIImage *) icon {
2897 NSString *section = [self simpleSection];
2900 if (parsed_ != NULL)
2901 if (NSString *href = parsed_->icon_)
2902 if ([href hasPrefix:@"file:///"])
2903 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2904 if (icon == nil) if (section != nil)
2905 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2906 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2907 if ([dicon hasPrefix:@"file:///"])
2908 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2910 icon = [UIImage imageNamed:@"unknown.png"];
2914 - (NSString *) homepage {
2915 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2918 - (NSString *) depiction {
2919 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2922 - (MIMEAddress *) author {
2923 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2926 - (NSString *) support {
2927 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2930 - (NSArray *) files {
2931 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2932 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2935 fin.open([path UTF8String]);
2940 while (std::getline(fin, line))
2941 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2946 - (NSString *) state {
2947 @synchronized (database_) {
2948 if ([database_ era] != era_ || file_.end())
2951 switch (iterator_->CurrentState) {
2952 case pkgCache::State::NotInstalled:
2953 return @"NotInstalled";
2954 case pkgCache::State::UnPacked:
2956 case pkgCache::State::HalfConfigured:
2957 return @"HalfConfigured";
2958 case pkgCache::State::HalfInstalled:
2959 return @"HalfInstalled";
2960 case pkgCache::State::ConfigFiles:
2961 return @"ConfigFiles";
2962 case pkgCache::State::Installed:
2963 return @"Installed";
2964 case pkgCache::State::TriggersAwaited:
2965 return @"TriggersAwaited";
2966 case pkgCache::State::TriggersPending:
2967 return @"TriggersPending";
2970 return (NSString *) [NSNull null];
2973 - (NSString *) selection {
2974 @synchronized (database_) {
2975 if ([database_ era] != era_ || file_.end())
2978 switch (iterator_->SelectedState) {
2979 case pkgCache::State::Unknown:
2981 case pkgCache::State::Install:
2983 case pkgCache::State::Hold:
2985 case pkgCache::State::DeInstall:
2986 return @"DeInstall";
2987 case pkgCache::State::Purge:
2991 return (NSString *) [NSNull null];
2994 - (NSArray *) warnings {
2995 @synchronized (database_) {
2996 if ([database_ era] != era_ || file_.end())
2999 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3000 const char *name(iterator_.Name());
3002 size_t length(strlen(name));
3003 if (length < 2) invalid:
3004 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3005 else for (size_t i(0); i != length; ++i)
3007 /* XXX: technically this is not allowed */
3008 (name[i] < 'A' || name[i] > 'Z') &&
3009 (name[i] < 'a' || name[i] > 'z') &&
3010 (name[i] < '0' || name[i] > '9') &&
3011 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3014 if (strcmp(name, "cydia") != 0) {
3017 bool _private = false;
3019 bool dbstash = false;
3020 bool dsstore = false;
3022 bool repository = [[self section] isEqualToString:@"Repositories"];
3024 if (NSArray *files = [self files])
3025 for (NSString *file in files)
3026 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3028 else if (!user && [file isEqualToString:@"/User"])
3030 else if (!_private && [file isEqualToString:@"/private"])
3032 else if (!stash && [file isEqualToString:@"/var/stash"])
3034 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3036 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3039 /* XXX: this is not sensitive enough. only some folders are valid. */
3040 if (cydia && !repository)
3041 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3043 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3045 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3047 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3049 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3051 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3054 return [warnings count] == 0 ? nil : warnings;
3057 - (NSArray *) applications {
3058 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3060 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3062 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3063 if (NSArray *files = [self files])
3064 for (NSString *file in files)
3065 if (application_r(file)) {
3066 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3069 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3070 if (id == nil || [id isEqualToString:me])
3073 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3075 display = application_r[1];
3077 NSString *bundle([file stringByDeletingLastPathComponent]);
3078 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3079 // XXX: maybe this should check if this is really a string, not just for length
3080 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3082 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3084 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3085 [applications addObject:application];
3087 [application addObject:id];
3088 [application addObject:display];
3089 [application addObject:url];
3092 return [applications count] == 0 ? nil : applications;
3095 - (Source *) source {
3096 if (source_ == nil) {
3097 @synchronized (database_) {
3098 if ([database_ era] != era_ || file_.end())
3099 source_ = (Source *) [NSNull null];
3101 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3105 return source_ == (Source *) [NSNull null] ? nil : source_;
3108 - (time_t) upgraded {
3112 - (uint32_t) recent {
3113 return std::numeric_limits<uint32_t>::max() - upgraded_;
3120 - (BOOL) matches:(NSArray *)query {
3121 if (query == nil || [query count] == 0)
3130 string = [self name];
3131 length = [string length];
3134 for (NSString *term in query) {
3135 range = [string rangeOfString:term options:MatchCompareOptions_];
3136 if (range.location != NSNotFound)
3137 rank_ -= 6 * 1000000 / length;
3142 length = [string length];
3145 for (NSString *term in query) {
3146 range = [string rangeOfString:term options:MatchCompareOptions_];
3147 if (range.location != NSNotFound)
3148 rank_ -= 6 * 1000000 / length;
3152 string = [self shortDescription];
3153 length = [string length];
3154 NSUInteger stop(std::min<NSUInteger>(length, 200));
3157 for (NSString *term in query) {
3158 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3159 if (range.location != NSNotFound)
3160 rank_ -= 2 * 100000;
3166 - (NSArray *) tags {
3170 - (BOOL) hasTag:(NSString *)tag {
3171 return tags_ == nil ? NO : [tags_ containsObject:tag];
3174 - (NSString *) primaryPurpose {
3175 for (NSString *tag in (NSArray *) tags_)
3176 if ([tag hasPrefix:@"purpose::"])
3177 return [tag substringFromIndex:9];
3181 - (NSArray *) purposes {
3182 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3183 for (NSString *tag in (NSArray *) tags_)
3184 if ([tag hasPrefix:@"purpose::"])
3185 [purposes addObject:[tag substringFromIndex:9]];
3186 return [purposes count] == 0 ? nil : purposes;
3189 - (bool) isCommercial {
3190 return [self hasTag:@"cydia::commercial"];
3193 - (void) setIndex:(size_t)index {
3194 if (metadata_->index_ != index + 1)
3195 metadata_->index_ = index + 1;
3198 - (CYString &) cyname {
3199 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3202 - (uint32_t) compareBySection:(NSArray *)sections {
3203 NSString *section([self section]);
3204 for (size_t i(0), e([sections count]); i != e; ++i) {
3205 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3209 return _not(uint32_t);
3213 @synchronized (database_) {
3214 if ([database_ era] != era_ || file_.end())
3217 pkgProblemResolver *resolver = [database_ resolver];
3218 resolver->Clear(iterator_);
3220 pkgCacheFile &cache([database_ cache]);
3221 cache->SetReInstall(iterator_, false);
3222 cache->MarkKeep(iterator_, false);
3226 @synchronized (database_) {
3227 if ([database_ era] != era_ || file_.end())
3230 pkgProblemResolver *resolver = [database_ resolver];
3231 resolver->Clear(iterator_);
3232 resolver->Protect(iterator_);
3234 pkgCacheFile &cache([database_ cache]);
3235 cache->SetCandidateVersion(version_);
3236 cache->SetReInstall(iterator_, false);
3237 cache->MarkInstall(iterator_, false);
3239 pkgDepCache::StateCache &state((*cache)[iterator_]);
3240 if (!state.Install())
3241 cache->SetReInstall(iterator_, true);
3245 @synchronized (database_) {
3246 if ([database_ era] != era_ || file_.end())
3249 pkgProblemResolver *resolver = [database_ resolver];
3250 resolver->Clear(iterator_);
3251 resolver->Remove(iterator_);
3252 resolver->Protect(iterator_);
3254 pkgCacheFile &cache([database_ cache]);
3255 cache->SetReInstall(iterator_, false);
3256 cache->MarkDelete(iterator_, true);
3261 /* Section Class {{{ */
3262 @interface Section : NSObject {
3266 _H<NSString> localized_;
3269 - (NSComparisonResult) compareByLocalized:(Section *)section;
3270 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3271 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3272 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3274 - (NSString *) name;
3275 - (void) setName:(NSString *)name;
3281 - (void) addToCount;
3283 - (void) setCount:(size_t)count;
3284 - (NSString *) localized;
3288 @implementation Section
3290 - (NSComparisonResult) compareByLocalized:(Section *)section {
3291 NSString *lhs(localized_);
3292 NSString *rhs([section localized]);
3294 /*if ([lhs length] != 0 && [rhs length] != 0) {
3295 unichar lhc = [lhs characterAtIndex:0];
3296 unichar rhc = [rhs characterAtIndex:0];
3298 if (isalpha(lhc) && !isalpha(rhc))
3299 return NSOrderedAscending;
3300 else if (!isalpha(lhc) && isalpha(rhc))
3301 return NSOrderedDescending;
3304 return [lhs compare:rhs options:LaxCompareOptions_];
3307 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3308 if ((self = [self initWithName:name localize:NO]) != nil) {
3309 if (localized != nil)
3310 localized_ = localized;
3314 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3315 return [self initWithName:name row:0 localize:localize];
3318 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3319 if ((self = [super init]) != nil) {
3323 localized_ = LocalizeSection(name_);
3327 - (NSString *) name {
3331 - (void) setName:(NSString *)name {
3347 - (void) addToCount {
3351 - (void) setCount:(size_t)count {
3355 - (NSString *) localized {
3362 class CydiaLogCleaner :
3363 public pkgArchiveCleaner
3366 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3371 /* Database Implementation {{{ */
3372 @implementation Database
3374 + (Database *) sharedInstance {
3375 static _H<Database> instance;
3376 if (instance == nil)
3377 instance = [[[Database alloc] init] autorelease];
3385 - (void) releasePackages {
3389 - (bool) hasPackages {
3390 return [packages_ count] != 0;
3394 // XXX: actually implement this thing
3396 [self releasePackages];
3397 NSRecycleZone(zone_);
3401 - (void) _readCydia:(NSNumber *)fd {
3402 boost::fdistream is([fd intValue]);
3405 static RegEx finish_r("finish:([^:]*)");
3407 while (std::getline(is, line)) {
3408 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3410 const char *data(line.c_str());
3411 size_t size = line.size();
3412 lprintf("C:%s\n", data);
3414 if (finish_r(data, size)) {
3415 NSString *finish = finish_r[1];
3416 int index = [Finishes_ indexOfObject:finish];
3417 if (index != INT_MAX && index > Finish_)
3427 - (void) _readStatus:(NSNumber *)fd {
3428 boost::fdistream is([fd intValue]);
3431 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3432 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3434 while (std::getline(is, line)) {
3435 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3437 const char *data(line.c_str());
3438 size_t size(line.size());
3439 lprintf("S:%s\n", data);
3441 if (conffile_r(data, size)) {
3442 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3443 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3444 } else if (strncmp(data, "status: ", 8) == 0) {
3445 // status: <package>: {unpacked,half-configured,installed}
3446 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3447 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3448 } else if (strncmp(data, "processing: ", 12) == 0) {
3449 // processing: configure: config-test
3450 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3451 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3452 } else if (pmstatus_r(data, size)) {
3453 std::string type([pmstatus_r[1] UTF8String]);
3455 NSString *package = pmstatus_r[2];
3456 if ([package isEqualToString:@"dpkg-exec"])
3459 float percent([pmstatus_r[3] floatValue]);
3460 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3462 NSString *string = pmstatus_r[4];
3464 if (type == "pmerror") {
3465 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3466 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3467 } else if (type == "pmstatus") {
3468 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3469 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3470 } else if (type == "pmconffile")
3471 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3473 lprintf("E:unknown pmstatus\n");
3475 lprintf("E:unknown status\n");
3483 - (void) _readOutput:(NSNumber *)fd {
3484 boost::fdistream is([fd intValue]);
3487 while (std::getline(is, line)) {
3488 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3490 lprintf("O:%s\n", line.c_str());
3492 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3493 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3505 - (Package *) packageWithName:(NSString *)name {
3508 @synchronized (self) {
3509 if (static_cast<pkgDepCache *>(cache_) == NULL)
3511 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3516 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3520 if ((self = [super init]) != nil) {
3527 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3529 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3533 _assert(pipe(fds) != -1);
3536 _config->Set("APT::Keep-Fds::", cydiafd_);
3537 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3540 detachNewThreadSelector:@selector(_readCydia:)
3542 withObject:[NSNumber numberWithInt:fds[0]]
3545 _assert(pipe(fds) != -1);
3549 detachNewThreadSelector:@selector(_readStatus:)
3551 withObject:[NSNumber numberWithInt:fds[0]]
3554 _assert(pipe(fds) != -1);
3555 _assert(dup2(fds[0], 0) != -1);
3556 _assert(close(fds[0]) != -1);
3558 input_ = fdopen(fds[1], "a");
3560 _assert(pipe(fds) != -1);
3561 _assert(dup2(fds[1], 1) != -1);
3562 _assert(close(fds[1]) != -1);
3565 detachNewThreadSelector:@selector(_readOutput:)
3567 withObject:[NSNumber numberWithInt:fds[0]]
3572 - (pkgCacheFile &) cache {
3576 - (pkgDepCache::Policy *) policy {
3580 - (pkgRecords *) records {
3584 - (pkgProblemResolver *) resolver {
3588 - (pkgAcquire &) fetcher {
3592 - (pkgSourceList &) list {
3596 - (NSArray *) packages {
3600 - (NSArray *) sources {
3604 - (Source *) sourceWithKey:(NSString *)key {
3605 for (Source *source in [self sources]) {
3606 if ([[source key] isEqualToString:key])
3611 - (bool) popErrorWithTitle:(NSString *)title {
3614 while (!_error->empty()) {
3616 bool warning(!_error->PopMessage(error));
3621 size_t size(error.size());
3622 if (size == 0 || error[size - 1] != '\n')
3624 error.resize(size - 1);
3627 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3629 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3630 if (warning && no_pubkey(error.c_str()))
3633 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3639 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3640 return [self popErrorWithTitle:title] || !success;
3643 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3644 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3652 if (access("/etc/apt/sources.list", F_OK) == 0)
3653 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3655 std::string base("/etc/apt/sources.list.d");
3656 if (DIR *sources = opendir(base.c_str())) {
3657 while (dirent *source = readdir(sources))
3658 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)
3659 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3663 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3668 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3669 @synchronized (self) {
3672 [self releasePackages];
3675 [sourceList_ removeAllObjects];
3696 new (&pool_) CYPool();
3698 NSRecycleZone(zone_);
3699 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3701 int chk(creat("/tmp/cydia.chk", 0644));
3705 if (invocation != nil)
3706 [invocation invoke];
3708 NSString *title(UCLocalize("DATABASE"));
3710 list_ = new pkgSourceList();
3711 _profile(reloadDataWithInvocation$ReadMainList)
3712 if ([self popErrorWithTitle:title forReadList:*list_])
3716 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3717 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3718 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3719 [sourceList_ addObject:object];
3724 OpProgress progress;
3727 delock_ = GetStatusDate();
3728 _profile(reloadDataWithInvocation$pkgCacheFile)
3729 opened = cache_.Open(progress, false);
3732 // XXX: this block should probably be merged with popError: in some way
3733 while (!_error->empty()) {
3735 bool warning(!_error->PopMessage(error));
3737 lprintf("cache_.Open():[%s]\n", error.c_str());
3739 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3743 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3744 repair = @selector(configure);
3745 //else if (error == "The package lists or status file could not be parsed or opened.")
3746 // repair = @selector(update);
3747 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3748 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3749 // else if (error == "Malformed Status line")
3750 // else if (error == "The list of sources could not be read.")
3752 if (repair != NULL) {
3754 [delegate_ repairWithSelector:repair];
3760 } else if ([self popErrorWithTitle:title forOperation:true])
3764 unlink("/tmp/cydia.chk");
3766 now_ = [[NSDate date] timeIntervalSince1970];
3768 policy_ = new pkgDepCache::Policy();
3769 records_ = new pkgRecords(cache_);
3770 resolver_ = new pkgProblemResolver(cache_);
3771 fetcher_ = new pkgAcquire(&status_);
3774 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3775 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3779 _profile(reloadDataWithInvocation$pkgApplyStatus)
3780 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3784 if (cache_->BrokenCount() != 0) {
3785 _profile(pkgApplyStatus$pkgFixBroken)
3786 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3790 if (cache_->BrokenCount() != 0) {
3791 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3795 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3796 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3801 for (Source *object in (id) sourceList_) {
3802 metaIndex *source([object metaIndex]);
3803 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3804 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3805 // XXX: this could be more intelligent
3806 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3807 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3809 sourceMap_[cached->ID] = object;
3814 size_t capacity(MetaFile_->active_);
3816 capacity = 128*1024;
3820 std::vector<Package *> packages;
3821 packages.reserve(capacity);
3825 _profile(reloadDataWithInvocation$packageWithIterator)
3826 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3827 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3828 if (unsigned index = package.metadata->index_) {
3830 if (packages.size() == index) {
3831 packages.push_back(package);
3832 } else if (packages.size() <= index) {
3833 packages.resize(index + 1, nil);
3834 packages[index] = package;
3837 std::swap(package, packages[index]);
3838 if (package != nil) {
3839 if (package.metadata->index_ == index + 1)
3848 lost: if (last == packages.size())
3849 packages.push_back(package);
3851 packages[last] = package;
3855 for (; last != packages.size(); ++last)
3856 if (packages[last] == nil)
3861 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3863 if (next == packages.size())
3865 if (packages[next] != nil)
3870 std::swap(packages[last], packages[next]);
3873 packages.resize(last);
3876 NSLog(@"lost = %zu", lost);
3878 _profile(reloadDataWithInvocation$radix$8)
3879 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3882 _profile(reloadDataWithInvocation$radix$4)
3883 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3886 _profile(reloadDataWithInvocation$radix$0)
3887 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3891 _profile(reloadDataWithInvocation$insertion)
3892 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3895 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3897 /*_profile(reloadDataWithInvocation$CFQSortArray)
3898 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3901 /*_profile(reloadDataWithInvocation$stdsort)
3902 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3905 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3906 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3909 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3910 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3913 MetaFile_->active_ = packages.size();
3914 for (size_t index(0), count(packages.size()); index != count; ++index) {
3915 auto package(packages[index]);
3916 [package setIndex:index];
3923 @synchronized (self) {
3925 resolver_ = new pkgProblemResolver(cache_);
3927 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3928 if (!cache_[iterator].Keep())
3929 cache_->MarkKeep(iterator, false);
3930 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3931 cache_->SetReInstall(iterator, false);
3934 - (void) configure {
3935 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3937 system([dpkg UTF8String]);
3942 @synchronized (self) {
3943 // XXX: I don't remember this condition
3948 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3950 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3952 if ([self popErrorWithTitle:title])
3956 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3958 CydiaLogCleaner cleaner;
3959 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3966 fetcher_->Shutdown();
3968 pkgRecords records(cache_);
3970 lock_ = new FileFd();
3971 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3973 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3975 if ([self popErrorWithTitle:title])
3979 if ([self popErrorWithTitle:title forReadList:list])
3982 manager_ = (_system->CreatePM(cache_));
3983 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3990 bool substrate(RestartSubstrate_);
3991 RestartSubstrate_ = false;
3993 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3995 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3997 if ([self popErrorWithTitle:title forReadList:list])
3999 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4000 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4003 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4005 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4007 [self popErrorWithTitle:title];
4011 bool failed = false;
4012 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4013 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4015 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4018 std::string uri = (*item)->DescURI();
4019 std::string error = (*item)->ErrorText;
4021 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4024 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4025 [delegate_ addProgressEventOnMainThread:event forTask:title];
4028 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4036 RestartSubstrate_ = true;
4038 if (![delock_ isEqual:GetStatusDate()]) {
4039 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4045 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4047 NSString *oextended(@"/var/lib/apt/extended_states");
4048 NSString *nextended(Cache("extended_states"));
4051 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4052 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4054 unlink([nextended UTF8String]);
4055 symlink([oextended UTF8String], [nextended UTF8String]);
4057 if ([self popErrorWithTitle:title])
4060 if (result == pkgPackageManager::Failed) {
4065 if (result != pkgPackageManager::Completed) {
4070 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4072 if ([self popErrorWithTitle:title forReadList:list])
4074 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4075 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4078 if (![before isEqualToArray:after])
4083 return ![delock_ isEqual:GetStatusDate()];
4087 NSString *title(UCLocalize("UPGRADE"));
4088 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4094 [self updateWithStatus:status_];
4097 - (void) updateWithStatus:(CancelStatus &)status {
4098 NSString *title(UCLocalize("REFRESHING_DATA"));
4101 if ([self popErrorWithTitle:title forReadList:list])
4105 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4106 if ([self popErrorWithTitle:title])
4109 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4111 bool success(ListUpdate(status, list, PulseInterval_));
4112 if (status.WasCancelled())
4115 [self popErrorWithTitle:title forOperation:success];
4117 [[NSDictionary dictionaryWithObjectsAndKeys:
4118 [NSDate date], @"LastUpdate",
4119 nil] writeToFile:@ CacheState_ atomically:YES];
4122 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4125 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4126 delegate_ = delegate;
4129 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4130 progress_ = delegate;
4131 status_.setDelegate(delegate);
4134 - (NSObject<ProgressDelegate> *) progressDelegate {
4138 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4139 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4140 return i == sourceMap_.end() ? nil : i->second;
4143 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4144 for (Source *source in (id) sourceList_)
4145 [source setFetch:fetch forURI:uri];
4148 - (void) resetFetch {
4149 for (Source *source in (id) sourceList_)
4150 [source resetFetch];
4153 - (NSString *) mappedSectionForPointer:(const char *)section {
4154 _H<NSString> *mapped;
4156 _profile(Database$mappedSectionForPointer$Cache)
4157 mapped = §ions_[section];
4160 if (*mapped == NULL) {
4161 size_t length(strlen(section));
4162 char spaced[length + 1];
4164 _profile(Database$mappedSectionForPointer$Replace)
4165 for (size_t index(0); index != length; ++index)
4166 spaced[index] = section[index] == '_' ? ' ' : section[index];
4167 spaced[length] = '\0';
4172 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4173 string = [NSString stringWithUTF8String:spaced];
4176 _profile(Database$mappedSectionForPointer$Map)
4177 string = [SectionMap_ objectForKey:string] ?: string;
4187 @interface CydiaObject : CyteObject {
4188 _transient id delegate_;
4193 @interface CydiaWebViewController : CyteWebViewController {
4194 _H<CydiaObject> cydia_;
4197 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4198 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4199 - (void) setDelegate:(id)delegate;
4203 /* Web Scripting {{{ */
4204 @implementation CydiaObject
4206 - (void) setDelegate:(id)delegate {
4207 delegate_ = delegate;
4210 - (NSArray *) attributeKeys {
4211 return [[NSArray arrayWithObjects:
4219 nil] arrayByAddingObjectsFromArray:[super attributeKeys]];
4222 - (NSString *) version {
4226 - (NSString *) device {
4227 return UniqueIdentifier();
4230 - (NSArray *) cells {
4231 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4232 if ($_CTServerConnectionCreate == NULL)
4235 struct CTResult { int flag; int error; };
4236 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4237 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4240 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4241 if (connection == nil)
4245 CFArrayRef cells(NULL);
4246 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4247 if (result.flag != 0)
4250 return [(NSArray *) cells autorelease];
4253 - (NSString *) mcc {
4254 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4255 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4259 - (NSString *) mnc {
4260 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4261 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4265 - (NSString *) operator {
4266 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4267 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4271 - (NSString *) role {
4272 return (id) [NSNull null];
4275 + (NSString *) webScriptNameForSelector:(SEL)selector {
4277 else if (selector == @selector(addBridgedHost:))
4278 return @"addBridgedHost";
4279 else if (selector == @selector(addInsecureHost:))
4280 return @"addInsecureHost";
4281 else if (selector == @selector(addSource:::))
4282 return @"addSource";
4283 else if (selector == @selector(addTrivialSource:))
4284 return @"addTrivialSource";
4285 else if (selector == @selector(du:))
4287 else if (selector == @selector(getAllSources))
4288 return @"getAllSources";
4289 else if (selector == @selector(getApplicationInfo:value:))
4290 return @"getApplicationInfoValue";
4291 else if (selector == @selector(getDisplayIdentifiers))
4292 return @"getDisplayIdentifiers";
4293 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4294 return @"getLocalizedNameForDisplayIdentifier";
4295 else if (selector == @selector(getInstalledPackages))
4296 return @"getInstalledPackages";
4297 else if (selector == @selector(getPackageById:))
4298 return @"getPackageById";
4299 else if (selector == @selector(getMetadataKeys))
4300 return @"getMetadataKeys";
4301 else if (selector == @selector(getMetadataValue:))
4302 return @"getMetadataValue";
4303 else if (selector == @selector(getSessionValue:))
4304 return @"getSessionValue";
4305 else if (selector == @selector(installPackages:))
4306 return @"installPackages";
4307 else if (selector == @selector(refreshSources))
4308 return @"refreshSources";
4309 else if (selector == @selector(saveConfig))
4310 return @"saveConfig";
4311 else if (selector == @selector(setMetadataValue::))
4312 return @"setMetadataValue";
4313 else if (selector == @selector(setSessionValue::))
4314 return @"setSessionValue";
4315 else if (selector == @selector(substitutePackageNames:))
4316 return @"substitutePackageNames";
4317 else if (selector == @selector(setToken:))
4323 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4324 return [self webScriptNameForSelector:selector] == nil;
4327 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4329 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4330 return (id) [NSNull null];
4331 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4333 return (id) [NSNull null];
4334 return [info objectForKey:key];
4337 - (NSArray *) getDisplayIdentifiers {
4338 return SBSCopyApplicationDisplayIdentifiers(false, false);
4341 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4342 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4345 - (NSNumber *) getKernelNumber:(NSString *)name {
4346 const char *string([name UTF8String]);
4349 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4350 return (id) [NSNull null];
4352 if (size != sizeof(int))
4353 return (id) [NSNull null];
4356 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4357 return (id) [NSNull null];
4359 return [NSNumber numberWithInt:value];
4362 - (NSArray *) getMetadataKeys {
4363 @synchronized (Values_) {
4364 return [Values_ allKeys];
4367 - (id) getMetadataValue:(NSString *)key {
4368 @synchronized (Values_) {
4369 return [Values_ objectForKey:key];
4372 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4373 @synchronized (Values_) {
4374 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4375 [Values_ removeObjectForKey:key];
4377 [Values_ setObject:value forKey:key];
4380 - (id) getSessionValue:(NSString *)key {
4381 @synchronized (SessionData_) {
4382 return [SessionData_ objectForKey:key];
4385 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4386 @synchronized (SessionData_) {
4387 if (value == (id) [WebUndefined undefined])
4388 [SessionData_ removeObjectForKey:key];
4390 [SessionData_ setObject:value forKey:key];
4393 - (void) addBridgedHost:(NSString *)host {
4394 @synchronized (BridgedHosts_) {
4395 [BridgedHosts_ addObject:host];
4398 - (void) addInsecureHost:(NSString *)host {
4399 @synchronized (InsecureHosts_) {
4400 [InsecureHosts_ addObject:host];
4403 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4404 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4406 for (NSString *section in sections)
4407 [array addObject:section];
4409 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4412 distribution, @"Distribution",
4414 nil] waitUntilDone:NO];
4417 - (BOOL) addTrivialSource:(NSString *)href {
4418 href = VerifySource(href);
4421 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4425 - (void) refreshSources {
4426 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4429 - (void) saveConfig {
4430 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4433 - (NSArray *) getAllSources {
4434 return [[Database sharedInstance] sources];
4437 - (NSArray *) getInstalledPackages {
4438 Database *database([Database sharedInstance]);
4439 @synchronized (database) {
4440 NSArray *packages([database packages]);
4441 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4442 for (Package *package in packages)
4443 if (![package uninstalled])
4444 [installed addObject:package];
4448 - (Package *) getPackageById:(NSString *)id {
4449 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4453 return (Package *) [NSNull null];
4456 - (NSNumber *) du:(NSString *)path {
4457 NSNumber *value(nil);
4459 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4462 while (fgets(line, sizeof(line), du) != NULL) {
4463 size_t length(strlen(line));
4464 while (length != 0 && line[length - 1] == '\n')
4465 line[--length] = '\0';
4466 if (char *tab = strchr(line, '\t')) {
4468 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4477 - (void) installPackages:(NSArray *)packages {
4478 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4481 - (NSString *) substitutePackageNames:(NSString *)message {
4482 auto database([Database sharedInstance]);
4484 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4485 if (![database hasPackages])
4488 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4489 for (size_t i(0), e([words count]); i != e; ++i) {
4490 NSString *word([words objectAtIndex:i]);
4491 if (Package *package = [database packageWithName:word])
4492 [words replaceObjectAtIndex:i withObject:[package name]];
4495 return [words componentsJoinedByString:@" "];
4498 - (void) setToken:(NSString *)token {
4499 // XXX: the website expects this :/
4505 @interface NSURL (CydiaSecure)
4508 @implementation NSURL (CydiaSecure)
4510 - (bool) isCydiaSecure {
4511 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4514 @synchronized (InsecureHosts_) {
4515 if ([InsecureHosts_ containsObject:[self host]])
4524 /* Cydia Browser Controller {{{ */
4525 @implementation CydiaWebViewController
4527 - (NSURL *) navigationURL {
4528 if (NSURLRequest *request = self.request)
4529 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4534 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4535 [super webView:view didClearWindowObject:window forFrame:frame];
4536 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4539 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4540 WebDataSource *source([frame dataSource]);
4541 NSURLResponse *response([source response]);
4542 NSURL *url([response URL]);
4543 NSString *scheme([[url scheme] lowercaseString]);
4545 bool bridged(false);
4547 @synchronized (BridgedHosts_) {
4548 if ([scheme isEqualToString:@"file"])
4550 else if ([scheme isEqualToString:@"https"])
4551 if ([BridgedHosts_ containsObject:[url host]])
4556 [window setValue:cydia forKey:@"cydia"];
4559 - (void) _setupMail:(MFMailComposeViewController *)controller {
4560 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4562 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4563 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4566 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4567 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4570 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4571 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4574 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4575 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4577 NSURL *url([copy URL]);
4578 NSString *href([url absoluteString]);
4579 NSString *host([url host]);
4581 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4582 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4583 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4584 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4587 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4588 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4590 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4594 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4595 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4596 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4597 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4599 bool bridged; @synchronized (BridgedHosts_) {
4600 bridged = [BridgedHosts_ containsObject:host];
4603 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4604 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4609 - (void) setDelegate:(id)delegate {
4610 [super setDelegate:delegate];
4611 [cydia_ setDelegate:delegate];
4615 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4616 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
4622 @interface AppCacheController : CydiaWebViewController {
4627 @implementation AppCacheController
4629 - (void) didReceiveMemoryWarning {
4630 // XXX: this doesn't work
4633 - (bool) retainsNetworkActivityIndicator {
4640 /* Confirmation Controller {{{ */
4641 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4642 if (!iterator.end())
4643 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4644 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4646 pkgCache::PkgIterator package(dep.TargetPkg());
4649 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4656 @protocol ConfirmationControllerDelegate
4657 - (void) cancelAndClear:(bool)clear;
4658 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4662 @interface ConfirmationController : CydiaWebViewController {
4663 _transient Database *database_;
4665 _H<UIAlertView> essential_;
4667 _H<NSDictionary> changes_;
4668 _H<NSMutableArray> issues_;
4669 _H<NSDictionary> sizes_;
4674 - (id) initWithDatabase:(Database *)database;
4678 @implementation ConfirmationController
4682 RestartSubstrate_ = true;
4683 [self.delegate confirmWithNavigationController:[self navigationController]];
4686 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4687 NSString *context([alert context]);
4689 if ([context isEqualToString:@"remove"]) {
4690 if (button == [alert cancelButtonIndex])
4692 else if (button == [alert firstOtherButtonIndex]) {
4693 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
4696 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4697 } else if ([context isEqualToString:@"unable"]) {
4698 [self dismissModalViewControllerAnimated:YES];
4699 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4701 [super alertView:alert clickedButtonAtIndex:button];
4705 - (void) _doContinue {
4706 [self.delegate cancelAndClear:NO];
4707 [self dismissModalViewControllerAnimated:YES];
4710 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4711 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4715 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4716 [super webView:view didClearWindowObject:window forFrame:frame];
4718 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4719 (id) changes_, @"changes",
4720 (id) issues_, @"issues",
4721 (id) sizes_, @"sizes",
4723 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4726 - (id) initWithDatabase:(Database *)database {
4727 if ((self = [super init]) != nil) {
4728 database_ = database;
4730 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4731 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4732 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4733 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4734 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4738 pkgCacheFile &cache([database_ cache]);
4739 NSArray *packages([database_ packages]);
4740 pkgDepCache::Policy *policy([database_ policy]);
4742 issues_ = [NSMutableArray arrayWithCapacity:4];
4744 for (Package *package in packages) {
4745 pkgCache::PkgIterator iterator([package iterator]);
4746 NSString *name([package id]);
4748 if ([package broken]) {
4749 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4751 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4753 reasons, @"reasons",
4756 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4760 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4761 pkgCache::DepIterator start;
4762 pkgCache::DepIterator end;
4763 dep.GlobOr(start, end); // ++dep
4765 if (!cache->IsImportantDep(end))
4767 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4770 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4772 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4773 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4774 clauses, @"clauses",
4778 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4780 pkgCache::PkgIterator target(start.TargetPkg());
4781 if (target->ProvidesList != 0)
4782 reason = @"missing";
4784 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4786 reason = @"installed";
4787 installed = [NSString stringWithUTF8String:ver.VerStr()];
4788 } else if (!cache[target].CandidateVerIter(cache).end())
4789 reason = @"uninstalled";
4790 else if (target->ProvidesList == 0)
4791 reason = @"uninstallable";
4793 reason = @"virtual";
4796 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4797 [NSString stringWithUTF8String:start.CompType()], @"operator",
4798 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4801 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4802 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4803 version, @"version",
4805 installed, @"installed",
4808 // yes, seriously. (wtf?)
4816 pkgDepCache::StateCache &state(cache[iterator]);
4818 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
4820 if (state.NewInstall())
4821 [installs addObject:name];
4822 // XXX: else if (state.Install())
4823 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4824 [reinstalls addObject:name];
4825 // XXX: move before previous if
4826 else if (state.Upgrade())
4827 [upgrades addObject:name];
4828 else if (state.Downgrade())
4829 [downgrades addObject:name];
4830 else if (!state.Delete())
4831 // XXX: _assert(state.Keep());
4833 else if (special_r(name))
4834 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4835 [NSNull null], @"package",
4836 [NSArray arrayWithObjects:
4837 [NSDictionary dictionaryWithObjectsAndKeys:
4838 @"Conflicts", @"relationship",
4839 [NSArray arrayWithObjects:
4840 [NSDictionary dictionaryWithObjectsAndKeys:
4842 [NSNull null], @"version",
4843 @"installed", @"reason",
4850 if ([package essential])
4852 [removes addObject:name];
4855 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4856 substrate_ |= DepSubstrate(iterator.CurrentVer());
4861 else if (Advanced_) {
4862 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4864 essential_ = [[[UIAlertView alloc]
4865 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4866 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4868 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4870 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4874 [essential_ setContext:@"remove"];
4875 [essential_ setNumberOfRows:2];
4877 essential_ = [[[UIAlertView alloc]
4878 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4879 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4881 cancelButtonTitle:UCLocalize("OKAY")
4882 otherButtonTitles:nil
4885 [essential_ setContext:@"unable"];
4888 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4889 installs, @"installs",
4890 reinstalls, @"reinstalls",
4891 upgrades, @"upgrades",
4892 downgrades, @"downgrades",
4893 removes, @"removes",
4896 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4897 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4898 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4901 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4905 - (UIBarButtonItem *) leftButton {
4906 return [[[UIBarButtonItem alloc]
4907 initWithTitle:UCLocalize("CANCEL")
4908 style:UIBarButtonItemStylePlain
4910 action:@selector(cancelButtonClicked)
4915 - (void) applyRightButton {
4916 if ([issues_ count] == 0 && ![self isLoading])
4917 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4918 initWithTitle:UCLocalize("CONFIRM")
4919 style:UIBarButtonItemStyleDone
4921 action:@selector(confirmButtonClicked)
4924 [[self navigationItem] setRightBarButtonItem:nil];
4928 - (void) cancelButtonClicked {
4929 [self.delegate cancelAndClear:YES];
4930 [self dismissModalViewControllerAnimated:YES];
4934 - (void) confirmButtonClicked {
4935 if (essential_ != nil)
4945 /* Progress Data {{{ */
4946 @interface CydiaProgressData : NSObject {
4947 _transient id delegate_;
4956 _H<NSMutableArray> events_;
4957 _H<NSString> title_;
4959 _H<NSString> status_;
4960 _H<NSString> finish_;
4965 @implementation CydiaProgressData
4967 + (NSArray *) _attributeKeys {
4968 return [NSArray arrayWithObjects:
4980 - (NSArray *) attributeKeys {
4981 return [[self class] _attributeKeys];
4984 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4985 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4989 if ((self = [super init]) != nil) {
4990 events_ = [NSMutableArray arrayWithCapacity:32];
4998 - (void) setDelegate:(id)delegate {
4999 delegate_ = delegate;
5002 - (void) setPercent:(float)value {
5006 - (NSNumber *) percent {
5007 return [NSNumber numberWithFloat:percent_];
5010 - (void) setCurrent:(float)value {
5014 - (NSNumber *) current {
5015 return [NSNumber numberWithFloat:current_];
5018 - (void) setTotal:(float)value {
5022 - (NSNumber *) total {
5023 return [NSNumber numberWithFloat:total_];
5026 - (void) setSpeed:(float)value {
5030 - (NSNumber *) speed {
5031 return [NSNumber numberWithFloat:speed_];
5034 - (NSArray *) events {
5038 - (void) removeAllEvents {
5039 [events_ removeAllObjects];
5042 - (void) addEvent:(CydiaProgressEvent *)event {
5043 [events_ addObject:event];
5046 - (void) setTitle:(NSString *)text {
5050 - (NSString *) title {
5054 - (void) setFinish:(NSString *)text {
5058 - (NSString *) finish {
5059 return (id) finish_ ?: [NSNull null];
5062 - (void) setRunning:(bool)running {
5066 - (NSNumber *) running {
5067 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5072 /* Progress Controller {{{ */
5073 @interface ProgressController : CydiaWebViewController <
5076 _transient Database *database_;
5077 _H<CydiaProgressData, 1> progress_;
5081 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5083 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5085 - (void) setTitle:(NSString *)title;
5086 - (void) setCancellable:(bool)cancellable;
5090 @implementation ProgressController
5093 [database_ setProgressDelegate:nil];
5097 - (UIBarButtonItem *) leftButton {
5098 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5099 initWithTitle:UCLocalize("CANCEL")
5100 style:UIBarButtonItemStylePlain
5102 action:@selector(cancel)
5103 ] autorelease] : nil;
5106 - (void) updateCancel {
5107 [super applyLeftButton];
5110 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5111 if ((self = [super init]) != nil) {
5112 database_ = database;
5113 self.delegate = delegate;
5115 [database_ setProgressDelegate:self];
5117 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5118 [progress_ setDelegate:self];
5120 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5122 [self setPageColor:[UIColor blackColor]];
5124 [[self navigationItem] setHidesBackButton:YES];
5126 [self updateCancel];
5130 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5131 [super webView:view didClearWindowObject:window forFrame:frame];
5132 [window setValue:progress_ forKey:@"cydiaProgress"];
5135 - (void) updateProgress {
5136 [self dispatchEvent:@"CydiaProgressUpdate"];
5139 - (void) viewWillAppear:(BOOL)animated {
5140 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5141 [super viewWillAppear:animated];
5145 UpdateExternalStatus(0);
5148 [self.delegate saveState];
5152 [self.delegate returnToCydia];
5156 [self.delegate terminateWithSuccess];
5157 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5158 [self.delegate suspendWithAnimation:YES];
5160 [self.delegate suspend];*/
5172 UIProgressHUD *hud([self.delegate addProgressHUD]);
5173 [hud setText:UCLocalize("LOADING")];
5174 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5180 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5181 SBReboot(SBSSpringBoardServerPort());
5183 reboot2(RB_AUTOBOOT);
5190 - (void) setTitle:(NSString *)title {
5191 [progress_ setTitle:title];
5192 [self updateProgress];
5195 - (UIBarButtonItem *) rightButton {
5196 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5197 initWithTitle:UCLocalize("CLOSE")
5198 style:UIBarButtonItemStylePlain
5200 action:@selector(close)
5204 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5205 UpdateExternalStatus(1);
5207 [progress_ setRunning:true];
5208 [self setTitle:title];
5209 // implicit updateProgress
5211 SHA1SumValue notifyconf; {
5213 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5216 MMap mmap(file, MMap::ReadOnly);
5218 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5219 notifyconf = sha1.Result();
5223 SHA1SumValue springlist; {
5225 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5228 MMap mmap(file, MMap::ReadOnly);
5230 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5231 springlist = sha1.Result();
5235 if (invocation != nil) {
5236 [invocation yieldToSelector:@selector(invoke)];
5237 [self setTitle:@"COMPLETE"];
5242 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5245 MMap mmap(file, MMap::ReadOnly);
5247 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5248 if (!(notifyconf == sha1.Result()))
5255 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5258 MMap mmap(file, MMap::ReadOnly);
5260 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5261 if (!(springlist == sha1.Result()))
5267 if (RestartSubstrate_)
5271 RestartSubstrate_ = false;
5274 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5275 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5276 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5277 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5278 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5281 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5283 [progress_ setRunning:false];
5284 [self updateProgress];
5286 [self applyRightButton];
5289 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5290 [progress_ addEvent:event];
5291 [self updateProgress];
5294 - (bool) isProgressCancelled {
5295 return cancel_ == 2;
5300 [self updateCancel];
5303 - (void) setCancellable:(bool)cancellable {
5304 unsigned cancel(cancel_);
5308 else if (cancel_ == 0)
5311 if (cancel != cancel_)
5312 [self updateCancel];
5315 - (void) setProgressCancellable:(NSNumber *)cancellable {
5316 [self setCancellable:[cancellable boolValue]];
5319 - (void) setProgressPercent:(NSNumber *)percent {
5320 [progress_ setPercent:[percent floatValue]];
5321 [self updateProgress];
5324 - (void) setProgressStatus:(NSDictionary *)status {
5325 if (status == nil) {
5326 [progress_ setCurrent:0];
5327 [progress_ setTotal:0];
5328 [progress_ setSpeed:0];
5330 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5332 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5333 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5334 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5337 [self updateProgress];
5343 /* Package Cell {{{ */
5344 @interface PackageCell : CyteTableViewCell <
5345 CyteTableViewCellDelegate
5349 _H<NSString> description_;
5351 _H<NSString> source_;
5353 _H<UIImage> placard_;
5357 - (PackageCell *) init;
5358 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5360 - (void) drawContentRect:(CGRect)rect;
5364 @implementation PackageCell
5366 - (PackageCell *) init {
5367 CGRect frame(CGRectMake(0, 0, 320, 74));
5368 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5369 UIView *content([self contentView]);
5370 CGRect bounds([content bounds]);
5372 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5373 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5374 [content addSubview:self.content];
5376 [self.content setDelegate:self];
5377 [self.content setOpaque:YES];
5381 - (NSString *) accessibilityLabel {
5385 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5386 summarized_ = summary;
5396 [self.content setBackgroundColor:[UIColor whiteColor]];
5400 Source *source = [package source];
5402 icon_ = [package icon];
5404 if (NSString *name = [package name])
5405 name_ = [NSString stringWithString:name];
5407 if (NSString *description = [package shortDescription])
5408 description_ = [NSString stringWithString:description];
5410 commercial_ = [package isCommercial];
5412 NSString *label = nil;
5413 bool trusted = false;
5415 if (source != nil) {
5416 label = [source label];
5417 trusted = [source trusted];
5418 } else if ([[package id] isEqualToString:@"firmware"])
5419 label = UCLocalize("APPLE");
5421 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5423 NSString *from(label);
5425 NSString *section = [package simpleSection];
5426 if (section != nil && ![section isEqualToString:label]) {
5427 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5428 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5431 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5433 if (NSString *purpose = [package primaryPurpose])
5434 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5439 if (NSString *mode = [package mode]) {
5440 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5441 color = RemovingColor_;
5442 placard = @"removing";
5444 color = InstallingColor_;
5445 placard = @"installing";
5448 color = [UIColor whiteColor];
5450 if ([package installed] != nil)
5451 placard = @"installed";
5456 [self.content setBackgroundColor:color];
5459 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5462 [self setNeedsDisplay];
5463 [self.content setNeedsDisplay];
5466 - (void) drawSummaryContentRect:(CGRect)rect {
5467 bool highlighted(self.highlighted);
5468 float width([self bounds].size.width);
5472 rect.size = [(UIImage *) icon_ size];
5474 while (rect.size.width > 16 || rect.size.height > 16) {
5475 rect.size.width /= 2;
5476 rect.size.height /= 2;
5479 rect.origin.x = 19 - rect.size.width / 2;
5480 rect.origin.y = 19 - rect.size.height / 2;
5482 [icon_ drawInRect:Retina(rect)];
5485 if (badge_ != nil) {
5487 rect.size = [(UIImage *) badge_ size];
5489 rect.size.width /= 4;
5490 rect.size.height /= 4;
5492 rect.origin.x = 25 - rect.size.width / 2;
5493 rect.origin.y = 25 - rect.size.height / 2;
5495 [badge_ drawInRect:Retina(rect)];
5498 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5502 UISetColor(commercial_ ? Purple_ : Black_);
5503 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5505 if (placard_ != nil)
5506 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5509 - (void) drawNormalContentRect:(CGRect)rect {
5510 bool highlighted(self.highlighted);
5511 float width([self bounds].size.width);
5515 rect.size = [(UIImage *) icon_ size];
5517 while (rect.size.width > 32 || rect.size.height > 32) {
5518 rect.size.width /= 2;
5519 rect.size.height /= 2;
5522 rect.origin.x = 25 - rect.size.width / 2;
5523 rect.origin.y = 25 - rect.size.height / 2;
5525 [icon_ drawInRect:Retina(rect)];
5528 if (badge_ != nil) {
5530 rect.size = [(UIImage *) badge_ size];
5532 rect.size.width /= 2;
5533 rect.size.height /= 2;
5535 rect.origin.x = 36 - rect.size.width / 2;
5536 rect.origin.y = 36 - rect.size.height / 2;
5538 [badge_ drawInRect:Retina(rect)];
5541 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5545 UISetColor(commercial_ ? Purple_ : Black_);
5546 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5547 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5550 UISetColor(commercial_ ? Purplish_ : Gray_);
5551 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5553 if (placard_ != nil)
5554 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5557 - (void) drawContentRect:(CGRect)rect {
5559 [self drawSummaryContentRect:rect];
5561 [self drawNormalContentRect:rect];
5566 /* Section Cell {{{ */
5567 @interface SectionCell : CyteTableViewCell <
5568 CyteTableViewCellDelegate
5570 _H<NSString> basic_;
5571 _H<NSString> section_;
5573 _H<NSString> count_;
5575 _H<UISwitch> switch_;
5579 - (void) setSection:(Section *)section editing:(BOOL)editing;
5583 @implementation SectionCell
5585 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5586 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5587 icon_ = [UIImage imageNamed:@"folder.png"];
5588 // XXX: this initial frame is wrong, but is fixed later
5589 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5590 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5592 UIView *content([self contentView]);
5593 CGRect bounds([content bounds]);
5595 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5596 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5597 [content addSubview:self.content];
5598 [self.content setBackgroundColor:[UIColor whiteColor]];
5600 [self.content setDelegate:self];
5604 - (void) onSwitch:(id)sender {
5605 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5606 if (metadata == nil) {
5607 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5608 [Sections_ setObject:metadata forKey:basic_];
5611 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5614 - (void) setSection:(Section *)section editing:(BOOL)editing {
5615 if (editing != editing_) {
5617 [switch_ removeFromSuperview];
5619 [self addSubview:switch_];
5628 if (section == nil) {
5629 name_ = UCLocalize("ALL_PACKAGES");
5632 basic_ = [section name];
5633 section_ = [section localized];
5635 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5636 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5639 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5642 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5643 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5645 [self.content setNeedsDisplay];
5648 - (void) setFrame:(CGRect)frame {
5649 [super setFrame:frame];
5651 CGRect rect([switch_ frame]);
5652 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5655 - (NSString *) accessibilityLabel {
5659 - (void) drawContentRect:(CGRect)rect {
5660 bool highlighted(self.highlighted && !editing_);
5662 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
5664 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5667 float width(rect.size.width);
5669 width -= 9 + [switch_ frame].size.width;
5673 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
5675 CGSize size = [count_ sizeWithFont:Font14_];
5677 UISetColor(Folder_);
5679 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
5685 /* File Table {{{ */
5686 @interface FileTable : CyteViewController <
5687 UITableViewDataSource,
5690 _transient Database *database_;
5691 _H<Package> package_;
5693 _H<NSMutableArray> files_;
5694 _H<UITableView, 2> list_;
5697 - (id) initWithDatabase:(Database *)database;
5698 - (void) setPackage:(Package *)package;
5702 @implementation FileTable
5704 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5705 return files_ == nil ? 0 : [files_ count];
5708 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5712 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5713 static NSString *reuseIdentifier = @"Cell";
5715 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5717 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5718 [cell setFont:[UIFont systemFontOfSize:16]];
5720 [cell setText:[files_ objectAtIndex:indexPath.row]];
5721 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5726 - (NSURL *) navigationURL {
5727 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5731 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
5732 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5733 [list_ setRowHeight:24.0f];
5734 [(UITableView *) list_ setDataSource:self];
5735 [list_ setDelegate:self];
5736 [self setView:list_];
5739 - (void) viewDidLoad {
5740 [super viewDidLoad];
5742 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5745 - (void) releaseSubviews {
5751 [super releaseSubviews];
5754 - (id) initWithDatabase:(Database *)database {
5755 if ((self = [super init]) != nil) {
5756 database_ = database;
5760 - (void) setPackage:(Package *)package {
5764 files_ = [NSMutableArray arrayWithCapacity:32];
5766 if (package != nil) {
5768 name_ = [package id];
5770 if (NSArray *files = [package files])
5771 [files_ addObjectsFromArray:files];
5773 if ([files_ count] != 0) {
5774 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5775 [files_ removeObjectAtIndex:0];
5776 [files_ sortUsingSelector:@selector(compareByPath:)];
5778 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5779 [stack addObject:@"/"];
5781 for (int i(0), e([files_ count]); i != e; ++i) {
5782 NSString *file = [files_ objectAtIndex:i];
5783 while (![file hasPrefix:[stack lastObject]])
5784 [stack removeLastObject];
5785 NSString *directory = [stack lastObject];
5786 [stack addObject:[file stringByAppendingString:@"/"]];
5787 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5788 int(([stack count] - 2) * 3), "",
5789 [file substringFromIndex:[directory length]]
5798 - (void) reloadData {
5801 [self setPackage:[database_ packageWithName:name_]];
5806 /* Package Controller {{{ */
5807 @interface CYPackageController : CydiaWebViewController <
5808 UIActionSheetDelegate
5810 _transient Database *database_;
5811 _H<Package> package_;
5814 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
5815 _H<UIActionSheet> sheet_;
5816 _H<UIBarButtonItem> button_;
5817 _H<NSArray> versions_;
5820 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
5824 @implementation CYPackageController
5826 - (NSURL *) navigationURL {
5827 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5830 - (void) _clickButtonWithPackage:(Package *)package {
5831 [self.delegate installPackage:package];
5834 - (void) _clickButtonWithName:(NSString *)name {
5835 if ([name isEqualToString:@"CLEAR"])
5836 return [self.delegate clearPackage:package_];
5837 else if ([name isEqualToString:@"REMOVE"])
5838 return [self.delegate removePackage:package_];
5839 else if ([name isEqualToString:@"DOWNGRADE"]) {
5840 sheet_ = [[[UIActionSheet alloc]
5843 cancelButtonTitle:nil
5844 destructiveButtonTitle:nil
5845 otherButtonTitles:nil
5848 for (Package *version in (id) versions_)
5849 [sheet_ addButtonWithTitle:[version latest]];
5850 [sheet_ setContext:@"version"];
5852 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5856 else if ([name isEqualToString:@"INSTALL"]);
5857 else if ([name isEqualToString:@"REINSTALL"]);
5858 else if ([name isEqualToString:@"UPGRADE"]);
5859 else _assert(false);
5861 [self.delegate installPackage:package_];
5864 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5865 NSString *context([sheet context]);
5866 if (sheet_ == sheet)
5869 if ([context isEqualToString:@"modify"]) {
5870 if (button != [sheet cancelButtonIndex]) {
5872 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
5874 [self _clickButtonWithName:buttons_[button].first];
5877 [sheet dismissWithClickedButtonIndex:button animated:YES];
5878 } else if ([context isEqualToString:@"version"]) {
5879 if (button != [sheet cancelButtonIndex]) {
5880 Package *version([versions_ objectAtIndex:button]);
5882 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
5884 [self _clickButtonWithPackage:version];
5887 [sheet dismissWithClickedButtonIndex:button animated:YES];
5891 - (bool) _allowJavaScriptPanel {
5896 - (void) _customButtonClicked {
5897 if (commercial_ && self.isLoading && [package_ uninstalled])
5898 return [self reloadURLWithCache:NO];
5900 size_t count(buttons_.size());
5905 [self _clickButtonWithName:buttons_[0].first];
5907 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5908 for (const auto &button : buttons_)
5909 [buttons addObject:button.second];
5911 sheet_ = [[[UIActionSheet alloc]
5914 cancelButtonTitle:nil
5915 destructiveButtonTitle:nil
5916 otherButtonTitles:nil
5919 for (NSString *button in buttons)
5920 [sheet_ addButtonWithTitle:button];
5921 [sheet_ setContext:@"modify"];
5923 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
5927 - (void) applyLoadingTitle {
5928 // Don't show "Loading" as the title. Ever.
5931 - (UIBarButtonItem *) rightButton {
5936 - (void) setPageColor:(UIColor *)color {
5937 return [super setPageColor:nil];
5940 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
5941 if ((self = [super init]) != nil) {
5942 database_ = database;
5943 name_ = name == nil ? @"" : [NSString stringWithString:name];
5944 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
5948 - (void) reloadData {
5951 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
5954 package_ = [database_ packageWithName:name_];
5955 versions_ = [package_ downgrades];
5959 if (package_ != nil) {
5960 [(Package *) package_ parse];
5962 commercial_ = [package_ isCommercial];
5964 if ([package_ mode] != nil)
5965 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
5966 if ([package_ source] == nil);
5967 else if ([package_ upgradableAndEssential:NO])
5968 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
5969 else if ([package_ uninstalled])
5970 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
5972 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
5973 if (![package_ uninstalled])
5974 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
5975 if ([versions_ count] != 0)
5976 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
5980 switch (buttons_.size()) {
5981 case 0: title = nil; break;
5982 case 1: title = buttons_[0].second; break;
5983 default: title = UCLocalize("MODIFY"); break;
5986 button_ = [[[UIBarButtonItem alloc]
5988 style:UIBarButtonItemStylePlain
5990 action:@selector(customButtonClicked)
5994 - (bool) isLoading {
5995 return commercial_ ? [super isLoading] : false;
6001 /* Package List Controller {{{ */
6002 @interface PackageListController : CyteViewController <
6003 UITableViewDataSource,
6006 _transient Database *database_;
6008 _H<NSArray> packages_;
6009 _H<NSArray> sections_;
6010 _H<UITableView, 2> list_;
6012 _H<NSArray> thumbs_;
6013 std::vector<NSInteger> offset_;
6015 _H<NSString> title_;
6016 unsigned reloading_;
6019 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6020 - (void) resetCursor;
6023 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6027 @implementation PackageListController
6029 - (NSURL *) referrerURL {
6030 return [self navigationURL];
6033 - (bool) isSummarized {
6037 - (bool) showsSections {
6041 - (void) deselectWithAnimation:(BOOL)animated {
6042 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6045 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6046 CGRect base = [[self view] bounds];
6047 base.size.height -= bounds.size.height;
6048 base.origin = [list_ frame].origin;
6050 [UIView beginAnimations:nil context:NULL];
6051 [UIView setAnimationBeginsFromCurrentState:YES];
6052 [UIView setAnimationCurve:curve];
6053 [UIView setAnimationDuration:duration];
6054 [list_ setFrame:base];
6055 [UIView commitAnimations];
6058 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6059 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6062 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6063 [self resizeForKeyboardBounds:bounds duration:0];
6066 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6067 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6068 *curve = UIViewAnimationCurveEaseInOut;
6070 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6072 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6075 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6078 - (void) keyboardWillShow:(NSNotification *)notification {
6081 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6082 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6084 NSTimeInterval duration;
6085 UIViewAnimationCurve curve;
6086 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6088 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6089 UIViewController *base([self rootViewController]);
6090 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6091 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6093 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6094 intersection.size.height += CYStatusBarHeight();
6096 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6099 - (void) keyboardWillHide:(NSNotification *)notification {
6100 NSTimeInterval duration;
6101 UIViewAnimationCurve curve;
6102 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6104 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6107 - (void) viewWillAppear:(BOOL)animated {
6108 [super viewWillAppear:animated];
6110 [self resizeForKeyboardBounds:CGRectZero];
6111 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6112 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6115 - (void) viewWillDisappear:(BOOL)animated {
6116 [super viewWillDisappear:animated];
6118 [self resizeForKeyboardBounds:CGRectZero];
6119 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6120 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6123 - (void) viewDidAppear:(BOOL)animated {
6124 [super viewDidAppear:animated];
6125 [self deselectWithAnimation:animated];
6128 - (void) didSelectPackage:(Package *)package {
6129 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6130 [view setDelegate:self.delegate];
6131 [[self navigationController] pushViewController:view animated:YES];
6134 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6135 NSInteger count([sections_ count]);
6136 return count == 0 ? 1 : count;
6139 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6140 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6142 return [[sections_ objectAtIndex:section] name];
6145 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6146 if ([sections_ count] == 0)
6148 return [[sections_ objectAtIndex:section] count];
6151 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6152 @synchronized (database_) {
6153 if ([database_ era] != era_)
6156 Section *section([sections_ objectAtIndex:[path section]]);
6157 NSInteger row([path row]);
6158 Package *package([packages_ objectAtIndex:([section row] + row)]);
6159 return [[package retain] autorelease];
6162 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6163 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6165 cell = [[[PackageCell alloc] init] autorelease];
6167 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6168 [cell setPackage:package asSummary:[self isSummarized]];
6172 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6173 Package *package([self packageAtIndexPath:path]);
6174 package = [database_ packageWithName:[package id]];
6175 [self didSelectPackage:package];
6178 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6182 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6183 return offset_[index];
6186 - (void) updateHeight {
6187 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6190 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6191 if ((self = [super init]) != nil) {
6192 database_ = database;
6193 title_ = [title copy];
6194 [[self navigationItem] setTitle:title_];
6199 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6200 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6201 [self setView:view];
6203 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6204 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6205 [view addSubview:list_];
6207 // XXX: is 20 the most optimal number here?
6208 [list_ setSectionIndexMinimumDisplayRowCount:20];
6210 [(UITableView *) list_ setDataSource:self];
6211 [list_ setDelegate:self];
6213 [self updateHeight];
6216 - (void) releaseSubviews {
6225 [super releaseSubviews];
6228 - (bool) shouldYield {
6232 - (bool) shouldBlock {
6236 - (NSMutableArray *) _reloadPackages {
6237 @synchronized (database_) {
6238 era_ = [database_ era];
6239 NSArray *packages([database_ packages]);
6241 return [NSMutableArray arrayWithArray:packages];
6244 - (void) _reloadData {
6245 if (reloading_ != 0) {
6250 NSMutableArray *packages;
6253 if ([self shouldYield]) {
6257 if (![self shouldBlock])
6260 hud = [self.delegate addProgressHUD];
6261 [hud setText:UCLocalize("LOADING")];
6265 packages = [self yieldToSelector:@selector(_reloadPackages)];
6268 [self.delegate removeProgressHUD:hud];
6269 } while (reloading_ == 2);
6271 packages = [self _reloadPackages];
6274 @synchronized (database_) {
6275 if (era_ != [database_ era])
6282 packages_ = packages;
6284 if ([self showsSections])
6285 sections_ = [self sectionsForPackages:packages];
6287 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6288 [section setCount:[packages_ count]];
6289 sections_ = [NSArray arrayWithObject:section];
6292 [self updateHeight];
6294 _profile(PackageTable$reloadData$List)
6295 [(UITableView *) list_ setDataSource:self];
6303 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6304 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6305 size_t end([packages count]);
6307 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6308 Section *section(prefix);
6310 thumbs_ = CollationThumbs_;
6311 offset_ = CollationOffset_;
6314 size_t offsets([CollationStarts_ count]);
6316 NSString *start([CollationStarts_ objectAtIndex:offset]);
6317 size_t length([start length]);
6319 for (size_t index(0); index != end; ++index) {
6321 Package *package([packages objectAtIndex:index]);
6322 NSString *name(PackageName(package, @selector(cyname)));
6324 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6325 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6326 NSString *title([CollationTitles_ objectAtIndex:offset]);
6327 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6328 [sections addObject:section];
6330 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6333 length = [start length];
6337 [section addToCount];
6340 for (; offset != offsets; ++offset) {
6341 NSString *title([CollationTitles_ objectAtIndex:offset]);
6342 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6343 [sections addObject:section];
6346 if ([prefix count] != 0) {
6347 Section *suffix([sections lastObject]);
6348 [prefix setName:[suffix name]];
6349 [suffix setName:nil];
6350 [sections insertObject:prefix atIndex:(offsets - 1)];
6356 - (void) reloadData {
6359 if ([self shouldYield])
6360 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6365 - (void) resetCursor {
6366 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6369 - (void) clearData {
6370 [self updateHeight];
6372 [list_ setDataSource:nil];
6380 /* Filtered Package List Controller {{{ */
6381 typedef Function<bool, Package *> PackageFilter;
6382 typedef Function<void, NSMutableArray *> PackageSorter;
6383 @interface FilteredPackageListController : PackageListController {
6384 PackageFilter filter_;
6385 PackageSorter sorter_;
6388 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6390 - (void) setFilter:(PackageFilter)filter;
6391 - (void) setSorter:(PackageSorter)sorter;
6395 @implementation FilteredPackageListController
6397 - (void) setFilter:(PackageFilter)filter {
6398 @synchronized (self) {
6402 - (void) setSorter:(PackageSorter)sorter {
6403 @synchronized (self) {
6407 - (NSMutableArray *) _reloadPackages {
6408 @synchronized (database_) {
6409 era_ = [database_ era];
6411 NSArray *packages([database_ packages]);
6412 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6414 PackageFilter filter;
6415 PackageSorter sorter;
6417 @synchronized (self) {
6422 _profile(PackageTable$reloadData$Filter)
6423 for (Package *package in packages)
6424 if (filter(package))
6425 [filtered addObject:package];
6433 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6434 if ((self = [super initWithDatabase:database title:title]) != nil) {
6435 [self setFilter:filter];
6442 /* Home Controller {{{ */
6443 @interface HomeController : CydiaWebViewController {
6444 CFRunLoopRef runloop_;
6445 SCNetworkReachabilityRef reachability_;
6450 @implementation HomeController
6452 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6453 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6457 if ((self = [super init]) != nil) {
6458 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6461 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6462 if (reachability_ != NULL) {
6463 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6464 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6466 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6467 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6474 if (reachability_ != NULL && runloop_ != NULL)
6475 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6479 - (NSURL *) navigationURL {
6480 return [NSURL URLWithString:@"cydia://home"];
6483 - (void) aboutButtonClicked {
6484 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6486 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6487 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6488 [alert setCancelButtonIndex:0];
6491 @"Copyright \u00a9 2008-2015\n"
6494 "Jay Freeman (saurik)\n"
6495 "saurik@saurik.com\n"
6496 "http://www.saurik.com/"
6502 - (UIBarButtonItem *) leftButton {
6503 return [[[UIBarButtonItem alloc]
6504 initWithTitle:UCLocalize("ABOUT")
6505 style:UIBarButtonItemStylePlain
6507 action:@selector(aboutButtonClicked)
6514 /* Cydia Tab Bar Controller {{{ */
6515 @interface CydiaTabBarController : CyteTabBarController <
6516 UITabBarControllerDelegate,
6519 _transient Database *database_;
6521 _H<UIActivityIndicatorView> indicator_;
6524 // XXX: ok, "updatedelegate_"?...
6525 _transient NSObject<CydiaDelegate> *updatedelegate_;
6528 - (void) beginUpdate;
6533 @implementation CydiaTabBarController
6535 - (id) initWithDatabase:(Database *)database {
6536 if ((self = [super init]) != nil) {
6537 database_ = database;
6538 [self setDelegate:self];
6540 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6541 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6543 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6547 - (void) beginUpdate {
6551 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6552 UITabBarItem *item([controller tabBarItem]);
6554 [item setBadgeValue:@""];
6555 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6557 [indicator_ startAnimating];
6558 [badge addSubview:indicator_];
6560 [updatedelegate_ retainNetworkActivityIndicator];
6564 detachNewThreadSelector:@selector(performUpdate)
6570 - (void) performUpdate {
6571 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6573 SourceStatus status(self, database_);
6574 [database_ updateWithStatus:status];
6577 performSelectorOnMainThread:@selector(completeUpdate)
6585 - (void) stopUpdateWithSelector:(SEL)selector {
6587 [updatedelegate_ releaseNetworkActivityIndicator];
6589 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6590 [[controller tabBarItem] setBadgeValue:nil];
6592 [indicator_ removeFromSuperview];
6593 [indicator_ stopAnimating];
6595 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6598 - (void) completeUpdate {
6601 [self stopUpdateWithSelector:@selector(reloadData)];
6604 - (void) cancelUpdate {
6605 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6608 - (void) cancelPressed {
6609 [self cancelUpdate];
6616 - (bool) isSourceCancelled {
6620 - (void) startSourceFetch:(NSString *)uri {
6623 - (void) stopSourceFetch:(NSString *)uri {
6626 - (void) setUpdateDelegate:(id)delegate {
6627 updatedelegate_ = delegate;
6633 /* Cydia:// Protocol {{{ */
6634 @interface CydiaURLProtocol : CyteURLProtocol {
6639 @implementation CydiaURLProtocol
6641 + (NSString *) scheme {
6645 - (bool) loadForPath:(NSString *)path ofRequest:(NSURLRequest *)request {
6646 NSRange slash([path rangeOfString:@"/"]);
6649 if (slash.location == NSNotFound) {
6653 command = [path substringToIndex:slash.location];
6654 path = [path substringFromIndex:(slash.location + 1)];
6657 Database *database([Database sharedInstance]);
6660 else if ([command isEqualToString:@"application-icon"]) {
6663 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6667 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
6668 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
6669 icon = [UIImage imageWithData:data];
6673 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
6674 icon = [UIImage imageAtPath:file];
6677 icon = [UIImage imageNamed:@"unknown.png"];
6679 [self _returnPNGWithImage:icon forRequest:request];
6680 } else if ([command isEqualToString:@"package-icon"]) {
6683 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6684 Package *package([database packageWithName:path]);
6688 UIImage *icon([package icon]);
6689 [self _returnPNGWithImage:icon forRequest:request];
6690 } else if ([command isEqualToString:@"uikit-image"]) {
6693 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6694 UIImage *icon(_UIImageWithName(path));
6695 [self _returnPNGWithImage:icon forRequest:request];
6696 } else if ([command isEqualToString:@"section-icon"]) {
6699 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6700 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
6702 icon = [UIImage imageNamed:@"unknown.png"];
6703 [self _returnPNGWithImage:icon forRequest:request];
6705 return [super loadForPath:path ofRequest:request];
6714 /* Section Controller {{{ */
6715 @interface SectionController : FilteredPackageListController {
6717 _H<NSString> section_;
6720 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
6724 @implementation SectionController
6726 - (NSURL *) referrerURL {
6727 NSString *name(section_);
6728 name = name ?: @"*";
6729 NSString *key(key_);
6731 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6734 - (NSURL *) navigationURL {
6735 NSString *name(section_);
6736 name = name ?: @"*";
6737 NSString *key(key_);
6739 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
6742 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
6745 title = UCLocalize("ALL_PACKAGES");
6746 else if (![section isEqual:@""])
6747 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
6749 title = UCLocalize("NO_SECTION");
6751 if ((self = [super initWithDatabase:database title:title]) != nil) {
6752 key_ = [source key];
6757 - (void) reloadData {
6758 Source *source([database_ sourceWithKey:key_]);
6759 _H<NSString> name(section_);
6761 [self setFilter:[=](Package *package) {
6762 NSString *section([package section]);
6766 section == nil && [name length] == 0 ||
6767 [name isEqualToString:section]
6770 [package source] == source
6771 ) && [package visible];
6779 /* Sections Controller {{{ */
6780 @interface SectionsController : CyteViewController <
6781 UITableViewDataSource,
6784 _transient Database *database_;
6786 _H<NSMutableArray> sections_;
6787 _H<NSMutableArray> filtered_;
6788 _H<UITableView, 2> list_;
6791 - (id) initWithDatabase:(Database *)database source:(Source *)source;
6792 - (void) editButtonClicked;
6796 @implementation SectionsController
6798 - (NSURL *) navigationURL {
6799 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
6802 - (Source *) source {
6805 return [database_ sourceWithKey:key_];
6808 - (void) updateNavigationItem {
6809 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6810 if ([sections_ count] == 0) {
6811 [[self navigationItem] setRightBarButtonItem:nil];
6813 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6814 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6816 action:@selector(editButtonClicked)
6817 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6821 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
6822 [super setEditing:editing animated:animated];
6827 [self.delegate updateData];
6829 [self updateNavigationItem];
6832 - (void) viewDidAppear:(BOOL)animated {
6833 [super viewDidAppear:animated];
6834 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6837 - (void) viewWillDisappear:(BOOL)animated {
6838 [super viewWillDisappear:animated];
6839 [self setEditing:NO];
6842 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6843 Section *section = nil;
6844 int index = [indexPath row];
6845 if (![self isEditing]) {
6848 section = [filtered_ objectAtIndex:index];
6850 section = [sections_ objectAtIndex:index];
6855 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6856 if ([self isEditing])
6857 return [sections_ count];
6859 return [filtered_ count] + 1;
6862 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6866 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6867 static NSString *reuseIdentifier = @"SectionCell";
6869 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6871 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6873 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
6878 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6879 if ([self isEditing])
6882 Section *section = [self sectionAtIndexPath:indexPath];
6884 SectionController *controller = [[[SectionController alloc]
6885 initWithDatabase:database_
6886 source:[self source]
6887 section:[section name]
6889 [controller setDelegate:self.delegate];
6891 [[self navigationController] pushViewController:controller animated:YES];
6895 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6896 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6897 [list_ setRowHeight:46];
6898 [(UITableView *) list_ setDataSource:self];
6899 [list_ setDelegate:self];
6900 [self setView:list_];
6903 - (void) viewDidLoad {
6904 [super viewDidLoad];
6906 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6909 - (void) releaseSubviews {
6915 [super releaseSubviews];
6918 - (id) initWithDatabase:(Database *)database source:(Source *)source {
6919 if ((self = [super init]) != nil) {
6920 database_ = database;
6921 key_ = [source key];
6925 - (void) reloadData {
6928 NSArray *packages = [database_ packages];
6930 sections_ = [NSMutableArray arrayWithCapacity:16];
6931 filtered_ = [NSMutableArray arrayWithCapacity:16];
6933 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6935 Source *source([self source]);
6938 for (Package *package in packages) {
6939 if (source != nil && [package source] != source)
6942 NSString *name([package section]);
6943 NSString *key(name == nil ? @"" : name);
6947 _profile(SectionsView$reloadData$Section)
6948 section = [sections objectForKey:key];
6949 if (section == nil) {
6950 _profile(SectionsView$reloadData$Section$Allocate)
6951 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
6952 [sections setObject:section forKey:key];
6957 [section addToCount];
6959 _profile(SectionsView$reloadData$Filter)
6960 if (![package visible])
6968 [sections_ addObjectsFromArray:[sections allValues]];
6970 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6972 for (Section *section in (id) sections_) {
6973 size_t count([section row]);
6977 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6978 [section setCount:count];
6979 [filtered_ addObject:section];
6982 [self updateNavigationItem];
6987 - (void) editButtonClicked {
6988 [self setEditing:![self isEditing] animated:YES];
6994 /* Changes Controller {{{ */
6995 @interface ChangesController : FilteredPackageListController {
6999 - (id) initWithDatabase:(Database *)database;
7003 @implementation ChangesController
7005 - (NSURL *) referrerURL {
7006 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7009 - (NSURL *) navigationURL {
7010 return [NSURL URLWithString:@"cydia://changes"];
7013 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7014 @synchronized (database_) {
7015 if ([database_ era] != era_)
7018 NSUInteger sectionIndex([path section]);
7019 if (sectionIndex >= [sections_ count])
7021 Section *section([sections_ objectAtIndex:sectionIndex]);
7022 NSInteger row([path row]);
7023 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7026 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7027 NSString *context([alert context]);
7029 if ([context isEqualToString:@"norefresh"])
7030 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7033 - (void) setLeftBarButtonItem {
7034 if ([self.delegate updating])
7035 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7036 initWithTitle:UCLocalize("CANCEL")
7037 style:UIBarButtonItemStyleDone
7039 action:@selector(cancelButtonClicked)
7040 ] autorelease] animated:YES];
7042 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7043 initWithTitle:UCLocalize("REFRESH")
7044 style:UIBarButtonItemStylePlain
7046 action:@selector(refreshButtonClicked)
7047 ] autorelease] animated:YES];
7050 - (void) refreshButtonClicked {
7051 if ([self.delegate requestUpdate])
7052 [self setLeftBarButtonItem];
7055 - (void) cancelButtonClicked {
7056 [self.delegate cancelUpdate];
7059 - (void) upgradeButtonClicked {
7060 [self.delegate distUpgrade];
7061 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7064 - (bool) shouldYield {
7068 - (bool) shouldBlock {
7072 - (void) useFilter {
7073 @synchronized (self) {
7074 [self setFilter:[](Package *package) {
7075 return [package upgradableAndEssential:YES] || [package visible];
7078 [self setSorter:[](NSMutableArray *packages) {
7079 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7083 - (id) initWithDatabase:(Database *)database {
7084 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7089 - (void) viewDidLoad {
7090 [super viewDidLoad];
7091 [self setLeftBarButtonItem];
7094 - (void) viewWillAppear:(BOOL)animated {
7095 [super viewWillAppear:animated];
7096 [self setLeftBarButtonItem];
7099 - (void) reloadData {
7100 [self setLeftBarButtonItem];
7104 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7105 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7107 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7108 Section *ignored = nil;
7109 Section *section = nil;
7113 bool unseens = false;
7115 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7117 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7118 Package *package = [packages objectAtIndex:offset];
7120 BOOL uae = [package upgradableAndEssential:YES];
7124 time_t seen([package seen]);
7126 if (section == nil || last != seen) {
7130 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7133 _profile(ChangesController$reloadData$Allocate)
7134 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7135 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7136 [sections addObject:section];
7140 [section addToCount];
7141 } else if ([package ignored]) {
7142 if (ignored == nil) {
7143 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7145 [ignored addToCount];
7148 [upgradable addToCount];
7153 CFRelease(formatter);
7156 Section *last = [sections lastObject];
7157 size_t count = [last count];
7158 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7159 [sections removeLastObject];
7162 if ([ignored count] != 0)
7163 [sections insertObject:ignored atIndex:0];
7165 [sections insertObject:upgradable atIndex:0];
7169 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7170 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7171 style:UIBarButtonItemStylePlain
7173 action:@selector(upgradeButtonClicked)
7174 ] autorelease]) animated:YES];
7181 /* Search Controller {{{ */
7182 @interface SearchController : FilteredPackageListController <
7185 _H<UISearchBar, 1> search_;
7190 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7191 - (void) reloadData;
7195 @implementation SearchController
7197 - (NSURL *) referrerURL {
7198 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7201 - (NSURL *) navigationURL {
7202 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7203 return [NSURL URLWithString:@"cydia://search"];
7205 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7208 - (NSArray *) termsForQuery:(NSString *)query {
7209 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7210 for (NSString *component in [query componentsSeparatedByString:@" "])
7211 if ([component length] != 0)
7212 [terms addObject:component];
7217 - (void) useSearch {
7218 _H<NSArray> query([self termsForQuery:[search_ text]]);
7221 @synchronized (self) {
7222 [self setFilter:[=](Package *package) {
7223 if (![package unfiltered])
7225 if (![package matches:query])
7230 [self setSorter:[](NSMutableArray *packages) {
7231 [packages radixSortUsingSelector:@selector(rank)];
7239 - (void) usePrefix:(NSString *)prefix {
7240 _H<NSString> query(prefix);
7243 @synchronized (self) {
7244 [self setFilter:[=](Package *package) {
7245 if ([query length] == 0)
7247 if (![package unfiltered])
7249 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7254 [self setSorter:nullptr];
7260 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7262 [self usePrefix:[search_ text]];
7265 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7266 [search_ resignFirstResponder];
7270 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7271 [search_ setText:@""];
7272 [self searchBarButtonClicked:searchBar];
7275 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7276 [self searchBarButtonClicked:searchBar];
7279 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7280 [self usePrefix:text];
7283 - (bool) shouldYield {
7287 - (bool) shouldBlock {
7291 - (bool) isSummarized {
7295 - (bool) showsSections {
7299 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7300 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7301 search_ = [[[UISearchBar alloc] init] autorelease];
7302 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7303 [search_ setDelegate:self];
7305 UITextField *textField;
7306 if ([search_ respondsToSelector:@selector(searchField)])
7307 textField = [search_ searchField];
7309 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7311 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7312 [textField setEnablesReturnKeyAutomatically:NO];
7313 [[self navigationItem] setTitleView:textField];
7316 [search_ setText:query];
7321 - (void) viewDidAppear:(BOOL)animated {
7322 [super viewDidAppear:animated];
7324 if (!searchloaded_) {
7325 searchloaded_ = YES;
7326 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7327 [search_ layoutSubviews];
7330 if ([self isSummarized])
7331 [search_ becomeFirstResponder];
7334 - (void) reloadData {
7339 - (void) didSelectPackage:(Package *)package {
7340 [search_ resignFirstResponder];
7341 [super didSelectPackage:package];
7346 /* Package Settings Controller {{{ */
7347 @interface PackageSettingsController : CyteViewController <
7348 UITableViewDataSource,
7351 _transient Database *database_;
7353 _H<Package> package_;
7354 _H<UITableView, 2> table_;
7355 _H<UISwitch> subscribedSwitch_;
7356 _H<UISwitch> ignoredSwitch_;
7357 _H<UITableViewCell> subscribedCell_;
7358 _H<UITableViewCell> ignoredCell_;
7361 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7365 @implementation PackageSettingsController
7367 - (NSURL *) navigationURL {
7368 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7371 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7372 if (package_ == nil)
7375 if ([package_ installed] == nil)
7381 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7382 if (package_ == nil)
7385 // both sections contain just one item right now.
7389 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7393 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7395 return UCLocalize("SHOW_ALL_CHANGES_EX");
7397 return UCLocalize("IGNORE_UPGRADES_EX");
7400 - (void) onSubscribed:(id)control {
7401 bool value([control isOn]);
7402 if (package_ == nil)
7404 if ([package_ setSubscribed:value])
7405 [self.delegate updateData];
7408 - (void) _updateIgnored {
7409 const char *package([name_ UTF8String]);
7410 bool on([ignoredSwitch_ isOn]);
7412 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7413 fwrite(package, strlen(package), 1, dpkg);
7416 fwrite(" hold\n", 6, 1, dpkg);
7418 fwrite(" install\n", 9, 1, dpkg);
7423 - (void) onIgnored:(id)control {
7424 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7425 [invocation setTarget:self];
7426 [invocation setSelector:@selector(_updateIgnored)];
7428 [self.delegate reloadDataWithInvocation:invocation];
7431 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7432 if (package_ == nil)
7435 switch ([indexPath section]) {
7436 case 0: return subscribedCell_;
7437 case 1: return ignoredCell_;
7446 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7447 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7448 [self setView:view];
7450 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7451 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7452 [(UITableView *) table_ setDataSource:self];
7453 [table_ setDelegate:self];
7454 [view addSubview:table_];
7456 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7457 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7458 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7460 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7461 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7462 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7464 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7465 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7466 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7467 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7469 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7470 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7471 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7472 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7475 - (void) viewDidLoad {
7476 [super viewDidLoad];
7478 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7481 - (void) releaseSubviews {
7483 subscribedCell_ = nil;
7485 ignoredSwitch_ = nil;
7486 subscribedSwitch_ = nil;
7488 [super releaseSubviews];
7491 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7492 if ((self = [super init]) != nil) {
7493 database_ = database;
7498 - (void) reloadData {
7501 package_ = [database_ packageWithName:name_];
7503 if (package_ != nil) {
7504 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7505 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7506 } // XXX: what now, G?
7508 [table_ reloadData];
7514 /* Installed Controller {{{ */
7515 @interface InstalledController : FilteredPackageListController {
7519 - (id) initWithDatabase:(Database *)database;
7520 - (void) queueStatusDidChange;
7524 @implementation InstalledController
7526 - (NSURL *) referrerURL {
7527 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7530 - (NSURL *) navigationURL {
7531 return [NSURL URLWithString:@"cydia://installed"];
7534 - (void) useRecent {
7537 @synchronized (self) {
7538 [self setFilter:[](Package *package) {
7539 return ![package uninstalled] && package->role_ < 7;
7542 [self setSorter:[](NSMutableArray *packages) {
7543 [packages radixSortUsingSelector:@selector(recent)];
7547 - (void) useFilter:(UISegmentedControl *)segmented {
7548 NSInteger selected([segmented selectedSegmentIndex]);
7550 return [self useRecent];
7551 bool simple(selected == 0);
7554 @synchronized (self) {
7555 [self setFilter:[=](Package *package) {
7556 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7559 [self setSorter:nullptr];
7562 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7564 return [super sectionsForPackages:packages];
7566 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
7568 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7569 Section *section(nil);
7572 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
7573 Package *package([packages objectAtIndex:offset]);
7575 time_t upgraded([package upgraded]);
7576 if (upgraded < 1168364520)
7579 upgraded -= upgraded % (60 * 60 * 24);
7581 if (section == nil || upgraded != last) {
7586 continue; // XXX: name = UCLocalize("...");
7588 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
7592 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7593 [sections addObject:section];
7596 [section addToCount];
7599 CFRelease(formatter);
7603 - (id) initWithDatabase:(Database *)database {
7604 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7605 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7606 [segmented setSelectedSegmentIndex:0];
7607 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7608 [[self navigationItem] setTitleView:segmented];
7610 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7611 [self useFilter:segmented];
7613 [self queueStatusDidChange];
7618 - (void) queueButtonClicked {
7619 [self.delegate queue];
7623 - (void) queueStatusDidChange {
7626 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7627 initWithTitle:UCLocalize("QUEUE")
7628 style:UIBarButtonItemStyleDone
7630 action:@selector(queueButtonClicked)
7633 [[self navigationItem] setRightBarButtonItem:nil];
7638 - (void) modeChanged:(UISegmentedControl *)segmented {
7639 [self useFilter:segmented];
7646 /* Source Cell {{{ */
7647 @interface SourceCell : CyteTableViewCell <
7648 CyteTableViewCellDelegate,
7651 _H<Source, 1> source_;
7654 _H<NSString> origin_;
7655 _H<NSString> label_;
7656 _H<UIActivityIndicatorView> indicator_;
7659 - (void) setSource:(Source *)source;
7660 - (void) setFetch:(NSNumber *)fetch;
7664 @implementation SourceCell
7666 - (void) _setImage:(NSArray *)data {
7667 if ([url_ isEqual:[data objectAtIndex:0]]) {
7668 icon_ = [data objectAtIndex:1];
7669 [self.content setNeedsDisplay];
7673 - (void) _setSource:(NSURL *) url {
7674 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7676 if (NSData *data = [NSURLConnection
7677 sendSynchronousRequest:[NSURLRequest
7679 cachePolicy:NSURLRequestUseProtocolCachePolicy
7683 returningResponse:NULL
7686 if (UIImage *image = [UIImage imageWithData:data])
7687 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
7692 - (void) setSource:(Source *)source {
7694 [source_ setDelegate:self];
7696 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
7698 icon_ = [UIImage imageNamed:@"unknown.png"];
7700 origin_ = [source name];
7701 label_ = [source rooturi];
7703 [self.content setNeedsDisplay];
7705 url_ = [source iconURL];
7706 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
7709 - (void) setAllSource {
7711 [indicator_ stopAnimating];
7713 icon_ = [UIImage imageNamed:@"folder.png"];
7714 origin_ = UCLocalize("ALL_SOURCES");
7715 label_ = UCLocalize("ALL_SOURCES_EX");
7716 [self.content setNeedsDisplay];
7719 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7720 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7721 UIView *content([self contentView]);
7722 CGRect bounds([content bounds]);
7724 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7725 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7726 [self.content setBackgroundColor:[UIColor whiteColor]];
7727 [content addSubview:self.content];
7729 [self.content setDelegate:self];
7730 [self.content setOpaque:YES];
7732 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
7733 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
7734 [content addSubview:indicator_];
7736 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
7740 - (void) layoutSubviews {
7741 [super layoutSubviews];
7743 UIView *content([self contentView]);
7744 CGRect bounds([content bounds]);
7746 CGRect frame([indicator_ frame]);
7747 frame.origin.x = bounds.size.width - frame.size.width;
7748 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
7750 if (kCFCoreFoundationVersionNumber < 800)
7751 frame.origin.x -= 8;
7752 [indicator_ setFrame:frame];
7755 - (NSString *) accessibilityLabel {
7759 - (void) drawContentRect:(CGRect)rect {
7760 bool highlighted(self.highlighted);
7761 float width(rect.size.width);
7765 rect.size = [(UIImage *) icon_ size];
7767 while (rect.size.width > 32 || rect.size.height > 32) {
7768 rect.size.width /= 2;
7769 rect.size.height /= 2;
7772 rect.origin.x = 26 - rect.size.width / 2;
7773 rect.origin.y = 26 - rect.size.height / 2;
7775 [icon_ drawInRect:Retina(rect)];
7778 if (highlighted && kCFCoreFoundationVersionNumber < 800)
7783 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
7787 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
7790 - (void) setFetch:(NSNumber *)fetch {
7791 if ([fetch boolValue])
7792 [indicator_ startAnimating];
7794 [indicator_ stopAnimating];
7799 /* Sources Controller {{{ */
7800 @interface SourcesController : CyteViewController <
7801 UITableViewDataSource,
7804 _transient Database *database_;
7807 _H<UITableView, 2> list_;
7808 _H<NSMutableArray> sources_;
7812 _H<UIProgressHUD> hud_;
7815 NSURLConnection *trivial_bz2_;
7816 NSURLConnection *trivial_gz_;
7821 - (id) initWithDatabase:(Database *)database;
7822 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
7826 @implementation SourcesController
7828 - (void) _releaseConnection:(NSURLConnection *)connection {
7829 if (connection != nil) {
7830 [connection cancel];
7831 //[connection setDelegate:nil];
7832 [connection release];
7837 [self _releaseConnection:trivial_gz_];
7838 [self _releaseConnection:trivial_bz2_];
7843 - (NSURL *) navigationURL {
7844 return [NSURL URLWithString:@"cydia://sources"];
7847 - (void) viewDidAppear:(BOOL)animated {
7848 [super viewDidAppear:animated];
7849 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7852 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7856 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7858 return UCLocalize("INDIVIDUAL_SOURCES");
7862 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7865 case 1: return [sources_ count];
7870 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7871 @synchronized (database_) {
7872 if ([database_ era] != era_)
7874 if ([indexPath section] != 1)
7876 NSUInteger index([indexPath row]);
7877 if (index >= [sources_ count])
7879 return [sources_ objectAtIndex:index];
7882 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7883 static NSString *cellIdentifier = @"SourceCell";
7885 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7886 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7887 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7889 Source *source([self sourceAtIndexPath:indexPath]);
7891 [cell setAllSource];
7893 [cell setSource:source];
7898 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7899 SectionsController *controller([[[SectionsController alloc]
7900 initWithDatabase:database_
7901 source:[self sourceAtIndexPath:indexPath]
7904 [controller setDelegate:self.delegate];
7905 [[self navigationController] pushViewController:controller animated:YES];
7908 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7909 if ([indexPath section] != 1)
7911 Source *source = [self sourceAtIndexPath:indexPath];
7912 return [source record] != nil;
7915 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7916 _assert([indexPath section] == 1);
7917 if (editingStyle == UITableViewCellEditingStyleDelete) {
7918 Source *source = [self sourceAtIndexPath:indexPath];
7919 if (source == nil) return;
7921 [Sources_ removeObjectForKey:[source key]];
7923 [self.delegate syncData];
7927 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
7928 [self updateButtonsForEditingStatusAnimated:YES];
7932 [self.delegate addTrivialSource:href_];
7935 [self.delegate syncData];
7938 - (NSString *) getWarning {
7939 NSString *href(href_);
7940 NSRange colon([href rangeOfString:@"://"]);
7941 if (colon.location != NSNotFound)
7942 href = [href substringFromIndex:(colon.location + 3)];
7943 href = [href stringByAddingPercentEscapes];
7944 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7946 NSURL *url([NSURL URLWithString:href]);
7948 NSStringEncoding encoding;
7949 NSError *error(nil);
7951 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7952 return [warning length] == 0 ? nil : warning;
7956 - (void) _endConnection:(NSURLConnection *)connection {
7957 // XXX: the memory management in this method is horribly awkward
7959 NSURLConnection **field = NULL;
7960 if (connection == trivial_bz2_)
7961 field = &trivial_bz2_;
7962 else if (connection == trivial_gz_)
7963 field = &trivial_gz_;
7964 _assert(field != NULL);
7965 [connection release];
7969 trivial_bz2_ == nil &&
7972 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
7974 [self.delegate releaseNetworkActivityIndicator];
7976 [self.delegate removeProgressHUD:hud_];
7980 if (warning != nil) {
7981 UIAlertView *alert = [[[UIAlertView alloc]
7982 initWithTitle:UCLocalize("SOURCE_WARNING")
7985 cancelButtonTitle:UCLocalize("CANCEL")
7987 UCLocalize("ADD_ANYWAY"),
7991 [alert setContext:@"warning"];
7992 [alert setNumberOfRows:1];
7995 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8001 } else if (error_ != nil) {
8002 UIAlertView *alert = [[[UIAlertView alloc]
8003 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8004 message:[error_ localizedDescription]
8006 cancelButtonTitle:UCLocalize("OK")
8007 otherButtonTitles:nil
8010 [alert setContext:@"urlerror"];
8015 UIAlertView *alert = [[[UIAlertView alloc]
8016 initWithTitle:UCLocalize("NOT_REPOSITORY")
8017 message:UCLocalize("NOT_REPOSITORY_EX")
8019 cancelButtonTitle:UCLocalize("OK")
8020 otherButtonTitles:nil
8023 [alert setContext:@"trivial"];
8033 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8034 switch ([response statusCode]) {
8040 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8041 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8043 [self _endConnection:connection];
8046 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8047 [self _endConnection:connection];
8050 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8051 NSURL *url([NSURL URLWithString:href]);
8053 NSMutableURLRequest *request = [NSMutableURLRequest
8055 cachePolicy:NSURLRequestUseProtocolCachePolicy
8059 [request setHTTPMethod:method];
8061 if (Machine_ != NULL)
8062 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8064 if (UniqueID_ != nil)
8065 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8067 if ([url isCydiaSecure]) {
8068 if (UniqueID_ != nil)
8069 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8072 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8075 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8076 NSString *context([alert context]);
8078 if ([context isEqualToString:@"source"]) {
8081 NSString *href = [[alert textField] text];
8082 href = VerifySource(href);
8087 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8088 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8092 // XXX: this is stupid
8093 hud_ = [self.delegate addProgressHUD];
8094 [hud_ setText:UCLocalize("VERIFYING_URL")];
8095 [self.delegate retainNetworkActivityIndicator];
8104 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8105 } else if ([context isEqualToString:@"trivial"])
8106 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8107 else if ([context isEqualToString:@"urlerror"])
8108 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8109 else if ([context isEqualToString:@"warning"]) {
8112 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8121 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8125 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8126 BOOL editing([list_ isEditing]);
8129 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8130 initWithTitle:UCLocalize("ADD")
8131 style:UIBarButtonItemStylePlain
8133 action:@selector(addButtonClicked)
8134 ] autorelease] animated:animated];
8135 else if ([self.delegate updating])
8136 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8137 initWithTitle:UCLocalize("CANCEL")
8138 style:UIBarButtonItemStyleDone
8140 action:@selector(cancelButtonClicked)
8141 ] autorelease] animated:animated];
8143 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8144 initWithTitle:UCLocalize("REFRESH")
8145 style:UIBarButtonItemStylePlain
8147 action:@selector(refreshButtonClicked)
8148 ] autorelease] animated:animated];
8150 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8151 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8152 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8154 action:@selector(editButtonClicked)
8155 ] autorelease] animated:animated];
8159 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8160 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8161 [list_ setRowHeight:53];
8162 [(UITableView *) list_ setDataSource:self];
8163 [list_ setDelegate:self];
8164 [self setView:list_];
8167 - (void) viewDidLoad {
8168 [super viewDidLoad];
8170 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8171 [self updateButtonsForEditingStatusAnimated:NO];
8174 - (void) viewWillAppear:(BOOL)animated {
8175 [super viewWillAppear:animated];
8177 [list_ setEditing:NO];
8178 [self updateButtonsForEditingStatusAnimated:NO];
8181 - (void) releaseSubviews {
8186 [super releaseSubviews];
8189 - (id) initWithDatabase:(Database *)database {
8190 if ((self = [super init]) != nil) {
8191 database_ = database;
8195 - (void) reloadData {
8197 [self updateButtonsForEditingStatusAnimated:YES];
8199 @synchronized (database_) {
8200 era_ = [database_ era];
8202 sources_ = [NSMutableArray arrayWithCapacity:16];
8203 [sources_ addObjectsFromArray:[database_ sources]];
8205 [sources_ sortUsingSelector:@selector(compareByName:)];
8208 int count([sources_ count]);
8210 for (int i = 0; i != count; i++) {
8211 if ([[sources_ objectAtIndex:i] record] == nil)
8219 - (void) showAddSourcePrompt {
8220 UIAlertView *alert = [[[UIAlertView alloc]
8221 initWithTitle:UCLocalize("ENTER_APT_URL")
8224 cancelButtonTitle:UCLocalize("CANCEL")
8226 UCLocalize("ADD_SOURCE"),
8230 [alert setContext:@"source"];
8232 [alert setNumberOfRows:1];
8233 [alert addTextFieldWithValue:@"http://" label:@""];
8235 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8236 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8237 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8238 [traits setKeyboardType:UIKeyboardTypeURL];
8239 // XXX: UIReturnKeyDone
8240 [traits setReturnKeyType:UIReturnKeyNext];
8245 - (void) addButtonClicked {
8246 [self showAddSourcePrompt];
8249 - (void) refreshButtonClicked {
8250 if ([self.delegate requestUpdate])
8251 [self updateButtonsForEditingStatusAnimated:YES];
8254 - (void) cancelButtonClicked {
8255 [self.delegate cancelUpdate];
8258 - (void) editButtonClicked {
8259 [list_ setEditing:![list_ isEditing] animated:YES];
8260 [self updateButtonsForEditingStatusAnimated:YES];
8266 /* Stash Controller {{{ */
8267 @interface StashController : CyteViewController {
8268 _H<UIActivityIndicatorView> spinner_;
8269 _H<UILabel> status_;
8270 _H<UILabel> caption_;
8275 @implementation StashController
8278 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8279 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8280 [self setView:view];
8282 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8284 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8285 CGRect spinrect = [spinner_ frame];
8286 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8287 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8288 [spinner_ setFrame:spinrect];
8289 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8290 [view addSubview:spinner_];
8291 [spinner_ startAnimating];
8294 captrect.size.width = [[self view] frame].size.width;
8295 captrect.size.height = 40.0f;
8296 captrect.origin.x = 0;
8297 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8298 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8299 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8300 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8301 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8302 [caption_ setTextColor:[UIColor whiteColor]];
8303 [caption_ setBackgroundColor:[UIColor clearColor]];
8304 [caption_ setShadowColor:[UIColor blackColor]];
8305 [caption_ setTextAlignment:NSTextAlignmentCenter];
8306 [view addSubview:caption_];
8309 statusrect.size.width = [[self view] frame].size.width;
8310 statusrect.size.height = 30.0f;
8311 statusrect.origin.x = 0;
8312 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8313 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8314 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8315 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8316 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8317 [status_ setTextColor:[UIColor whiteColor]];
8318 [status_ setBackgroundColor:[UIColor clearColor]];
8319 [status_ setShadowColor:[UIColor blackColor]];
8320 [status_ setTextAlignment:NSTextAlignmentCenter];
8321 [view addSubview:status_];
8324 - (void) releaseSubviews {
8329 [super releaseSubviews];
8335 @interface Cydia : CyteApplication <
8336 ConfirmationControllerDelegate,
8340 _H<CyteWindow> window_;
8341 _H<CydiaTabBarController> tabbar_;
8342 _H<CyteTabBarController> emulated_;
8343 _H<AppCacheController> appcache_;
8345 _H<NSMutableArray> essential_;
8346 _H<NSMutableArray> broken_;
8348 Database *database_;
8350 _H<NSURL> starturl_;
8355 _H<StashController> stash_;
8364 @implementation Cydia
8366 - (void) lockSuspend {
8367 if (locked_++ == 0) {
8368 if ($SBSSetInterceptsMenuButtonForever != NULL)
8369 (*$SBSSetInterceptsMenuButtonForever)(true);
8371 [self setIdleTimerDisabled:YES];
8375 - (void) unlockSuspend {
8376 if (--locked_ == 0) {
8377 [self setIdleTimerDisabled:NO];
8379 if ($SBSSetInterceptsMenuButtonForever != NULL)
8380 (*$SBSSetInterceptsMenuButtonForever)(false);
8384 - (void) beginUpdate {
8385 [tabbar_ beginUpdate];
8388 - (void) cancelUpdate {
8389 [tabbar_ cancelUpdate];
8392 - (bool) requestUpdate {
8393 if (CyteIsReachable("cydia.saurik.com")) {
8397 UIAlertView *alert = [[[UIAlertView alloc]
8398 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8399 message:@"Host Unreachable" // XXX: Localize
8401 cancelButtonTitle:UCLocalize("OK")
8402 otherButtonTitles:nil
8405 [alert setContext:@"norefresh"];
8413 return [tabbar_ updating];
8417 if ([broken_ count] != 0) {
8418 int count = [broken_ count];
8420 UIAlertView *alert = [[[UIAlertView alloc]
8421 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8422 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8424 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8426 UCLocalize("TEMPORARY_IGNORE"),
8430 [alert setContext:@"fixhalf"];
8431 [alert setNumberOfRows:2];
8433 } else if (!Ignored_ && [essential_ count] != 0) {
8434 int count = [essential_ count];
8436 UIAlertView *alert = [[[UIAlertView alloc]
8437 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8438 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8440 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8442 UCLocalize("UPGRADE_ESSENTIAL"),
8443 UCLocalize("COMPLETE_UPGRADE"),
8447 [alert setContext:@"upgrade"];
8452 - (void) returnToCydia {
8456 - (void) reloadSpringBoard {
8457 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8458 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8460 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8462 system("/usr/bin/killall backboardd SpringBoard");
8465 - (void) _saveConfig {
8466 SaveConfig(database_);
8469 // Navigation controller for the queuing badge.
8470 - (UINavigationController *) queueNavigationController {
8471 NSArray *controllers = [tabbar_ viewControllers];
8472 return [controllers objectAtIndex:3];
8475 - (void) _updateData {
8477 [window_ unloadData];
8479 UINavigationController *navigation = [self queueNavigationController];
8481 id queuedelegate = nil;
8482 if ([[navigation viewControllers] count] > 0)
8483 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8485 [queuedelegate queueStatusDidChange];
8486 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8489 - (void) _refreshIfPossible {
8490 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8492 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
8494 bool recently = false;
8495 if (update != nil) {
8496 NSTimeInterval interval([update timeIntervalSinceNow]);
8497 if (interval > -(15*60))
8501 // Don't automatic refresh if:
8502 // - We already refreshed recently.
8503 // - We already auto-refreshed this launch.
8504 // - Auto-refresh is disabled.
8505 // - Cydia's server is not reachable
8506 if (recently || loaded_ || ManualRefresh || !CyteIsReachable("cydia.saurik.com")) {
8507 // If we are cancelling, we need to make sure it knows it's already loaded.
8510 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8512 // We are going to load, so remember that.
8515 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
8521 - (void) refreshIfPossible {
8522 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8525 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8526 _profile(reloadDataWithInvocation)
8527 @synchronized (self) {
8528 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8530 [hud setText:UCLocalize("RELOADING_DATA")];
8532 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8536 [essential_ removeAllObjects];
8537 [broken_ removeAllObjects];
8539 _profile(reloadDataWithInvocation$Essential)
8540 NSArray *packages([database_ packages]);
8541 for (Package *package in packages) {
8543 [broken_ addObject:package];
8544 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8545 if ([package essential] && [package installed] != nil)
8546 [essential_ addObject:package];
8552 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8555 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8556 [changesItem setBadgeValue:badge];
8557 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8558 [self setApplicationIconBadgeNumber:changes];
8561 [changesItem setBadgeValue:nil];
8562 [changesItem setAnimatedBadge:NO];
8563 [self setApplicationIconBadgeNumber:0];
8570 [self removeProgressHUD:hud];
8577 - (void) updateData {
8581 - (void) updateDataAndLoad {
8583 if ([database_ progressDelegate] == nil)
8589 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8592 - (void) disemulate {
8593 if (emulated_ == nil)
8596 [window_ setRootViewController:tabbar_];
8599 [window_ setUserInteractionEnabled:YES];
8602 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8603 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8605 UIViewController *parent;
8606 if (emulated_ == nil)
8616 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8617 [parent presentModalViewController:navigation animated:YES];
8620 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8621 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8623 if (navigation != nil)
8624 [navigation pushViewController:progress animated:YES];
8626 [self presentModalViewController:progress force:YES];
8628 [progress invoke:invocation withTitle:title];
8632 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8633 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8636 - (void) repairWithInvocation:(NSInvocation *)invocation {
8638 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
8642 - (void) repairWithSelector:(SEL)selector {
8643 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8646 - (void) reloadData {
8647 [self reloadDataWithInvocation:nil];
8648 if ([database_ progressDelegate] == nil)
8654 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
8657 - (void) addSource:(NSDictionary *) source {
8658 CydiaAddSource(source);
8661 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
8662 CydiaAddSource(href, distribution, sections);
8665 // XXX: this method should not return anything
8666 - (BOOL) addTrivialSource:(NSString *)href {
8667 CydiaAddSource(href, @"./");
8672 pkgProblemResolver *resolver = [database_ resolver];
8674 resolver->InstallProtect();
8675 if (!resolver->Resolve(true))
8680 // XXX: this is a really crappy way of doing this.
8681 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8682 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8683 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8684 if ([tabbar_ updating])
8685 [tabbar_ cancelUpdate];
8687 if (![database_ prepare])
8690 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8691 [page setDelegate:self];
8692 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
8695 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8696 [tabbar_ presentModalViewController:confirm_ animated:YES];
8702 @synchronized (self) {
8707 - (void) clearPackage:(Package *)package {
8708 @synchronized (self) {
8715 - (void) installPackages:(NSArray *)packages {
8716 @synchronized (self) {
8717 for (Package *package in packages)
8724 - (void) installPackage:(Package *)package {
8725 @synchronized (self) {
8732 - (void) removePackage:(Package *)package {
8733 @synchronized (self) {
8740 - (void) distUpgrade {
8741 @synchronized (self) {
8742 if (![database_ upgrade])
8750 system("/usr/bin/uicache");
8755 UIProgressHUD *hud([self addProgressHUD]);
8756 [hud setText:UCLocalize("LOADING")];
8757 [self yieldToSelector:@selector(_uicache)];
8758 [self removeProgressHUD:hud];
8762 [database_ perform];
8763 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8764 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
8767 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8770 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
8771 [self unlockSuspend];
8774 - (void) retainNetworkActivityIndicator {
8775 if (activity_++ == 0)
8776 [self setNetworkActivityIndicatorVisible:YES];
8779 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
8783 - (void) releaseNetworkActivityIndicator {
8784 if (--activity_ == 0)
8785 [self setNetworkActivityIndicatorVisible:NO];
8788 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
8793 - (void) cancelAndClear:(bool)clear {
8794 @synchronized (self) {
8806 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8807 NSString *context([alert context]);
8809 if ([context isEqualToString:@"conffile"]) {
8810 FILE *input = [database_ input];
8811 if (button == [alert cancelButtonIndex])
8812 fprintf(input, "N\n");
8813 else if (button == [alert firstOtherButtonIndex])
8814 fprintf(input, "Y\n");
8817 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8818 } else if ([context isEqualToString:@"fixhalf"]) {
8819 if (button == [alert cancelButtonIndex]) {
8820 @synchronized (self) {
8821 for (Package *broken in (id) broken_) {
8823 NSString *id(ShellEscape([broken id]));
8824 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
8825 " /var/lib/dpkg/info/%@.prerm"
8826 " /var/lib/dpkg/info/%@.postrm"
8827 " /var/lib/dpkg/info/%@.preinst"
8828 " /var/lib/dpkg/info/%@.postinst"
8829 " /var/lib/dpkg/info/%@.extrainst_"
8830 "", id, id, id, id, id] UTF8String]);
8836 } else if (button == [alert firstOtherButtonIndex]) {
8837 [broken_ removeAllObjects];
8841 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8842 } else if ([context isEqualToString:@"upgrade"]) {
8843 if (button == [alert firstOtherButtonIndex]) {
8844 @synchronized (self) {
8845 for (Package *essential in (id) essential_)
8846 [essential install];
8851 } else if (button == [alert firstOtherButtonIndex] + 1) {
8853 } else if (button == [alert cancelButtonIndex]) {
8857 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8861 - (void) system:(NSString *)command {
8862 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8865 system([command UTF8String]);
8871 - (void) applicationWillSuspend {
8873 [super applicationWillSuspend];
8876 - (BOOL) isSafeToSuspend {
8879 NSLog(@"isSafeToSuspend: locked_ != 0");
8884 if ([tabbar_ modalViewController] != nil)
8887 // Use external process status API internally.
8888 // This is probably a really bad idea.
8889 // XXX: what is the point of this? does this solve anything at all?
8890 uint64_t status = 0;
8892 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8893 notify_get_state(notify_token, &status);
8894 notify_cancel(notify_token);
8899 NSLog(@"isSafeToSuspend: status != 0");
8905 NSLog(@"isSafeToSuspend: -> true");
8910 - (void) suspendReturningToLastApp:(BOOL)returning {
8911 if ([self isSafeToSuspend])
8912 [super suspendReturningToLastApp:returning];
8916 if ([self isSafeToSuspend])
8920 - (void) applicationSuspend {
8921 if ([self isSafeToSuspend])
8922 [super applicationSuspend];
8925 - (void) applicationSuspend:(GSEventRef)event {
8926 if ([self isSafeToSuspend])
8927 [super applicationSuspend:event];
8930 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8931 if ([self isSafeToSuspend])
8932 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8935 - (void) _setSuspended:(BOOL)value {
8936 if ([self isSafeToSuspend])
8937 [super _setSuspended:value];
8940 - (UIProgressHUD *) addProgressHUD {
8941 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
8942 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8944 [window_ setUserInteractionEnabled:NO];
8946 UIViewController *target(tabbar_);
8947 if (UIViewController *modal = [target modalViewController])
8950 [hud showInView:[target view]];
8956 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8957 [self unlockSuspend];
8959 [hud removeFromSuperview];
8960 [window_ setUserInteractionEnabled:YES];
8963 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
8964 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
8967 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
8968 NSString *scheme([[url scheme] lowercaseString]);
8969 if ([[url absoluteString] length] <= [scheme length] + 3)
8971 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8972 NSArray *components([path componentsSeparatedByString:@"/"]);
8974 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
8975 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
8976 if (controller != nil)
8977 [controller setDelegate:self];
8981 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8984 NSString *base([components objectAtIndex:0]);
8986 CyteViewController *controller = nil;
8988 if ([base isEqualToString:@"url"]) {
8989 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8990 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8991 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
8992 } else if (!external && [components count] == 1) {
8993 if ([base isEqualToString:@"sources"]) {
8994 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8997 if ([base isEqualToString:@"home"]) {
8998 controller = [[[HomeController alloc] init] autorelease];
9001 if ([base isEqualToString:@"sections"]) {
9002 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9005 if ([base isEqualToString:@"search"]) {
9006 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9009 if ([base isEqualToString:@"changes"]) {
9010 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9013 if ([base isEqualToString:@"installed"]) {
9014 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9016 } else if ([components count] == 2) {
9017 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9019 if ([base isEqualToString:@"package"]) {
9020 controller = [self pageForPackage:argument withReferrer:referrer];
9023 if (!external && [base isEqualToString:@"search"]) {
9024 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9027 if (!external && [base isEqualToString:@"sections"]) {
9028 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9030 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9033 if ([base isEqualToString:@"sources"]) {
9034 if ([argument isEqualToString:@"add"]) {
9035 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9036 [(SourcesController *)controller showAddSourcePrompt];
9038 Source *source([database_ sourceWithKey:argument]);
9039 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9043 if (!external && [base isEqualToString:@"launch"]) {
9044 [self launchApplicationWithIdentifier:argument suspended:NO];
9047 } else if (!external && [components count] == 3) {
9048 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9049 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9051 if ([base isEqualToString:@"package"]) {
9052 if ([arg2 isEqualToString:@"settings"]) {
9053 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9054 } else if ([arg2 isEqualToString:@"files"]) {
9055 if (Package *package = [database_ packageWithName:arg1]) {
9056 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9057 [(FileTable *)controller setPackage:package];
9062 if ([base isEqualToString:@"sections"]) {
9063 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9064 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9065 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9069 [controller setDelegate:self];
9073 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9074 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9077 [tabbar_ setUnselectedViewController:page];
9082 - (void) applicationOpenURL:(NSURL *)url {
9083 [super applicationOpenURL:url];
9088 [self openCydiaURL:url forExternal:YES];
9091 - (void) applicationWillResignActive:(UIApplication *)application {
9092 // Stop refreshing if you get a phone call or lock the device.
9093 if ([tabbar_ updating])
9094 [tabbar_ cancelUpdate];
9096 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9097 [super applicationWillResignActive:application];
9100 - (void) saveState {
9101 [[NSDictionary dictionaryWithObjectsAndKeys:
9102 @"InterfaceState", [tabbar_ navigationURLCollection],
9103 @"LastClosed", [NSDate date],
9104 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9105 nil] writeToFile:@ SavedState_ atomically:YES];
9110 - (void) applicationWillTerminate:(UIApplication *)application {
9114 - (void) applicationDidEnterBackground:(UIApplication *)application {
9115 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9116 return [self terminateWithSuccess];
9117 Backgrounded_ = [NSDate date];
9121 - (void) applicationWillEnterForeground:(UIApplication *)application {
9122 if (Backgrounded_ == nil)
9125 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9127 if (interval <= -(30*60)) {
9128 [tabbar_ setSelectedIndex:0];
9129 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9132 if (interval <= -(15*60)) {
9133 if (CyteIsReachable("cydia.saurik.com")) {
9134 [tabbar_ beginUpdate];
9135 [appcache_ reloadURLWithCache:YES];
9139 if ([database_ delocked])
9143 - (void) setConfigurationData:(NSString *)data {
9144 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9146 if (!conffile_r(data)) {
9147 lprintf("E:invalid conffile\n");
9151 NSString *ofile = conffile_r[1];
9152 //NSString *nfile = conffile_r[2];
9154 UIAlertView *alert = [[[UIAlertView alloc]
9155 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9156 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9158 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9160 UCLocalize("ACCEPT_NEW_COPY"),
9161 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9165 [alert setContext:@"conffile"];
9166 [alert setNumberOfRows:2];
9170 - (void) addStashController {
9172 stash_ = [[[StashController alloc] init] autorelease];
9173 [window_ addSubview:[stash_ view]];
9176 - (void) removeStashController {
9177 [[stash_ view] removeFromSuperview];
9179 [self unlockSuspend];
9183 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9184 UpdateExternalStatus(1);
9185 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9186 UpdateExternalStatus(0);
9188 [self removeStashController];
9189 [self reloadSpringBoard];
9192 - (void) applicationDidFinishLaunching:(id)unused {
9193 [super applicationDidFinishLaunching:unused];
9194 [CyteWebViewController _initialize];
9196 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9198 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9200 // this would disallow http{,s} URLs from accessing this data
9201 //[WebView registerURLSchemeAsLocal:@"cydia"];
9203 Font12_ = [UIFont systemFontOfSize:12];
9204 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9205 Font14_ = [UIFont systemFontOfSize:14];
9206 Font18_ = [UIFont systemFontOfSize:18];
9207 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9208 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9210 essential_ = [NSMutableArray arrayWithCapacity:4];
9211 broken_ = [NSMutableArray arrayWithCapacity:4];
9213 // XXX: I really need this thing... like, seriously... I'm sorry
9214 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9215 [appcache_ reloadData];
9217 window_ = [[[CyteWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9218 [window_ orderFront:self];
9219 [window_ makeKey:self];
9220 [window_ setHidden:NO];
9222 if (access("/.cydia_no_stash", F_OK) == 0);
9226 [self addStashController];
9227 // XXX: this would be much cleaner as a yieldToSelector:
9228 // that way the removeStashController could happen right here inline
9229 // we also could no longer require the useless stash_ field anymore
9230 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9235 int error(stat("/", &root));
9236 _assert(error != -1);
9238 #define Stash_(path) do { \
9239 struct stat folder; \
9240 int error(lstat((path), &folder)); \
9241 if (error != -1 && ( \
9242 folder.st_dev == root.st_dev && \
9243 S_ISDIR(folder.st_mode) \
9244 ) || error == -1 && ( \
9245 errno == ENOENT || \
9250 Stash_("/Applications");
9251 Stash_("/Library/Ringtones");
9252 Stash_("/Library/Wallpaper");
9253 //Stash_("/usr/bin");
9254 Stash_("/usr/include");
9255 Stash_("/usr/share");
9256 //Stash_("/var/lib");
9260 database_ = [Database sharedInstance];
9261 [database_ setDelegate:self];
9263 [window_ setUserInteractionEnabled:NO];
9265 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9267 [tabbar_ addViewControllers:nil,
9268 @"Cydia", @"home.png", @"home7.png", @"home7s.png",
9269 UCLocalize("SOURCES"), @"install.png", @"install7.png", @"install7s.png",
9270 UCLocalize("CHANGES"), @"changes.png", @"changes7.png", @"changes7s.png",
9271 UCLocalize("INSTALLED"), @"manage.png", @"manage7.png", @"manage7s.png",
9272 UCLocalize("SEARCH"), @"search.png", @"search7.png", @"search7s.png",
9275 [tabbar_ setUpdateDelegate:self];
9277 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9278 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9279 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9281 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9282 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9283 [emulated_ setSelectedIndex:0];
9285 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9286 [emulated_ concealTabBarSelection];
9288 [window_ setRootViewController:emulated_];
9290 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9294 - (NSArray *) defaultStartPages {
9295 NSMutableArray *standard = [NSMutableArray array];
9296 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9297 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9298 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9299 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9300 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9306 if ([emulated_ modalViewController] != nil)
9307 [emulated_ dismissModalViewControllerAnimated:YES];
9308 [window_ setUserInteractionEnabled:NO];
9310 [self reloadDataWithInvocation:nil];
9311 [self refreshIfPossible];
9314 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9316 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9317 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9318 int standardIndex = 0;
9319 NSArray *standard = [self defaultStartPages];
9326 NSDate *closed = [state objectForKey:@"LastClosed"];
9327 if (valid && closed != nil) {
9328 NSTimeInterval interval([closed timeIntervalSinceNow]);
9329 if (interval <= -(30*60))
9333 if (valid && [saved count] != [standard count])
9337 for (unsigned int i = 0; i < [standard count]; i++) {
9338 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9339 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9340 // but it's good enough for now.
9341 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9348 NSArray *items = nil;
9350 [tabbar_ setSelectedIndex:savedIndex];
9353 [tabbar_ setSelectedIndex:standardIndex];
9357 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9358 NSArray *stack = [items objectAtIndex:tab];
9359 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9360 NSMutableArray *current = [NSMutableArray array];
9362 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9363 NSString *addr = [stack objectAtIndex:nav];
9364 NSURL *url = [NSURL URLWithString:addr];
9365 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9367 [current addObject:page];
9370 [navigation setViewControllers:current];
9373 // (Try to) show the startup URL.
9374 if (starturl_ != nil) {
9375 [self openCydiaURL:starturl_ forExternal:YES];
9380 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9382 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9383 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9386 if (item != nil && IsWildcat_) {
9387 [sheet showFromBarButtonItem:item animated:YES];
9389 [sheet showInView:window_];
9393 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9394 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9395 [progress setTitle:task];
9396 [progress addProgressEvent:event];
9399 - (void) addProgressEventForTask:(NSArray *)data {
9400 CydiaProgressEvent *event([data objectAtIndex:0]);
9401 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9402 [self addProgressEvent:event forTask:task];
9405 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9406 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9412 id Alloc_(id self, SEL selector) {
9413 id object = alloc_(self, selector);
9414 lprintf("[%s]A-%p\n", self->isa->name, object);
9419 id Dealloc_(id self, SEL selector) {
9420 id object = dealloc_(self, selector);
9421 lprintf("[%s]D-%p\n", self->isa->name, object);
9425 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9428 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9430 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9432 return [(NSMutableDictionary *) copy autorelease];
9435 int main_store(int, char *argv[]);
9437 int main(int argc, char *argv[]) {
9439 const char *argv0(argv[0]);
9440 if (const char *slash = strrchr(argv0, '/'))
9443 else if (!strcmp(argv0, "store"))
9444 return main_store(argc, argv);
9447 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9451 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9455 CyteInitialize(@"Cydia", Cydia_);
9456 UpdateExternalStatus(0);
9458 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9459 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9460 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9462 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@/1.1", IsWildcat_ ? @"ipad" : @"iphone"]);
9463 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9465 /* Set Locale {{{ */
9466 Locale_ = CFLocaleCopyCurrent();
9467 Languages_ = [NSLocale preferredLanguages];
9469 std::string languages;
9470 const char *translation(NULL);
9472 // XXX: this isn't really a language, but this is compatible with older Cydia builds
9473 if (Locale_ != NULL)
9474 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
9475 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
9476 if (pattern(language)) {
9477 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
9478 languages += translation;
9483 if (Languages_ != nil)
9484 for (NSString *locale : Languages_) {
9485 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
9486 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
9487 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
9488 language = [NSString stringWithFormat:@"%@-%@", language, script];
9489 languages += [language UTF8String];
9494 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
9496 /* Index Collation {{{ */
9497 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
9498 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
9499 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
9500 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
9501 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
9502 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
9504 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
9506 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
9507 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
9508 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})
9509 CollationOffset_.push_back(offset);
9510 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];
9511 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];
9514 CollationThumbs_ = [collation sectionIndexTitles];
9515 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
9516 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
9518 CollationTitles_ = [collation sectionTitles];
9519 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
9521 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
9522 if (&transform != NULL && transform != nil) {
9523 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
9524 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
9525 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
9526 UErrorCode code(U_ZERO_ERROR);
9527 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
9528 if (!U_SUCCESS(code))
9529 NSLog(@"%s", u_errorName(code));
9533 } @catch (NSException *e) {
9537 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
9539 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];
9540 for (NSInteger offset(0); offset != 28; ++offset)
9541 CollationOffset_.push_back(offset);
9543 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];
9544 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];
9548 App_ = [[NSBundle mainBundle] bundlePath];
9551 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
9552 mkdir([Cache_ UTF8String], 0755);
9554 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9555 alloc_ = alloc->method_imp;
9556 alloc->method_imp = (IMP) &Alloc_;*/
9558 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9559 dealloc_ = dealloc->method_imp;
9560 dealloc->method_imp = (IMP) &Dealloc_;*/
9562 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
9563 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
9564 UniqueID_ = UniqueIdentifier([UIDevice currentDevice]);
9566 /* System Information {{{ */
9570 size = sizeof(maxproc);
9571 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9572 perror("sysctlbyname(\"kern.maxproc\", ?)");
9573 else if (maxproc < 64) {
9575 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9576 perror("sysctlbyname(\"kern.maxproc\", #)");
9579 /* Load Database {{{ */
9580 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9583 mkdir("/var/mobile/Library/Cydia", 0755);
9584 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
9587 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
9588 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
9589 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
9590 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
9593 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
9596 Values_ = [metadata objectForKey:@"Values"];
9598 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
9600 if (Sections_ == nil)
9601 Sections_ = [metadata objectForKey:@"Sections"];
9602 if (Sections_ == nil)
9603 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9605 if (Sources_ == nil)
9606 Sources_ = [metadata objectForKey:@"Sources"];
9607 if (Sources_ == nil)
9608 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9610 // XXX: this wrong, but in a way that doesn't matter :/
9611 if (Version_ == nil)
9612 Version_ = [metadata objectForKey:@"Version"];
9613 if (Version_ == nil)
9614 Version_ = [NSNumber numberWithUnsignedInt:0];
9616 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
9618 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
9621 NSLog(@"unable to import package preferences... from 2010? oh well :/");
9624 if ([Version_ unsignedIntValue] == 0) {
9625 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9626 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9627 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
9628 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
9630 Version_ = [NSNumber numberWithUnsignedInt:1];
9632 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
9633 [cache removeObjectForKey:@"LastUpdate"];
9634 [cache writeToFile:@ CacheState_ atomically:YES];
9638 _H<NSMutableArray> broken([NSMutableArray array]);
9639 for (NSString *key in (id) Sources_)
9640 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
9641 [broken addObject:key];
9642 if ([broken count] != 0)
9643 for (NSString *key in (id) broken)
9644 [Sources_ removeObjectForKey:key];
9648 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
9651 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9653 if (kCFCoreFoundationVersionNumber > 1000)
9654 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
9656 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9658 if (access("/User", F_OK) != 0 || version != 6) {
9660 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
9664 if (access("/tmp/cydia.chk", F_OK) == 0) {
9665 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
9666 _assert(errno == ENOENT);
9667 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
9668 _assert(errno == ENOENT);
9671 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
9673 /* APT Initialization {{{ */
9674 _assert(pkgInitConfig(*_config));
9675 _assert(pkgInitSystem(*_config, _system));
9677 _config->Set("Acquire::AllowInsecureRepositories", true);
9678 _config->Set("Acquire::Check-Valid-Until", false);
9679 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
9681 _config->Set("pkgCacheGen::ForceEssential", "");
9683 if (translation != NULL)
9684 _config->Set("APT::Acquire::Translation", translation);
9685 _config->Set("Acquire::Languages", languages);
9687 // XXX: this timeout might be important :(
9688 //_config->Set("Acquire::http::Timeout", 15);
9691 size = sizeof(usermem);
9692 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
9694 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
9696 mkdir([Cache("archives") UTF8String], 0755);
9697 mkdir([Cache("archives/partial") UTF8String], 0755);
9698 _config->Set("Dir::Cache", [Cache_ UTF8String]);
9700 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
9701 _config->Set("Dir::State", [Cache_ UTF8String]);
9703 mkdir([Cache("lists") UTF8String], 0755);
9704 mkdir([Cache("lists/partial") UTF8String], 0755);
9705 mkdir([Cache("periodic") UTF8String], 0755);
9706 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
9708 std::string logs("/var/mobile/Library/Logs/Cydia");
9709 mkdir(logs.c_str(), 0755);
9710 _config->Set("Dir::Log", logs);
9712 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
9714 /* Color Choices {{{ */
9715 space_ = CGColorSpaceCreateDeviceRGB();
9717 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9718 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9719 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9720 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
9721 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9722 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9723 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9724 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9725 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9726 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9728 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9729 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9731 /* UIKit Configuration {{{ */
9732 // XXX: I have a feeling this was important
9733 //UIKeyboardDisableAutomaticAppearance();
9736 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
9737 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
9739 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
9740 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
9741 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
9743 PulseInterval_ = fast ? 50000 : 500000;
9745 Colon_ = UCLocalize("COLON_DELIMITED");
9746 Elision_ = UCLocalize("ELISION");
9747 Error_ = UCLocalize("ERROR");
9748 Warning_ = UCLocalize("WARNING");
9751 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9753 CGColorSpaceRelease(space_);