1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2014 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 <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
64 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
84 #include <apt-pkg/tagfile.h>
86 #include <apr-1/apr_pools.h>
88 #include <sys/types.h>
90 #include <sys/sysctl.h>
91 #include <sys/param.h>
92 #include <sys/mount.h>
93 #include <sys/reboot.h>
100 #include <mach-o/nlist.h>
109 #include <Cytore.hpp>
112 #include <CydiaSubstrate/CydiaSubstrate.h>
113 #include "Menes/Menes.h"
115 #include "CyteKit/IndirectDelegate.h"
116 #include "CyteKit/PerlCompatibleRegEx.hpp"
117 #include "CyteKit/TableViewCell.h"
118 #include "CyteKit/TabBarController.h"
119 #include "CyteKit/WebScriptObject-Cyte.h"
120 #include "CyteKit/WebViewController.h"
121 #include "CyteKit/WebViewTableViewCell.h"
122 #include "CyteKit/stringWithUTF8Bytes.h"
124 #include "Cydia/MIMEAddress.h"
125 #include "Cydia/LoadingViewController.h"
126 #include "Cydia/ProgressEvent.h"
128 #include "SDURLCache/SDURLCache.h"
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
201 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
202 #define synchronized(lock) \
203 synchronized(static_cast<NSObject *>(lock))
205 extern NSString *Cydia_;
207 #define lprintf(args...) fprintf(stderr, args)
210 #define TraceLogging (1 && !ForRelease)
211 #define HistogramInsertionSort (0 && !ForRelease)
212 #define ProfileTimes (0 && !ForRelease)
213 #define ForSaurik (0 && !ForRelease)
214 #define LogBrowser (0 && !ForRelease)
215 #define TrackResize (0 && !ForRelease)
216 #define ManualRefresh (1 && !ForRelease)
217 #define ShowInternals (0 && !ForRelease)
218 #define AlwaysReload (0 && !ForRelease)
222 #define _trace(args...)
227 #define _profile(name) {
230 #define PrintTimes() do {} while (false)
233 // Hash Functions/Structures {{{
234 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
249 _assert(setreuid(real ? 0 : 501, 0) != -1);
255 _assert(setreuid(501, 501) != -1);
258 operator bool() const {
265 #define _root(real) \
266 if (__attribute__((__unused__)) const Root &root = Root(real))
268 static NSString *Colon_;
270 static NSString *Error_;
271 static NSString *Warning_;
273 static NSString *Cache_;
274 #define Cache(file) \
275 [NSString stringWithFormat:@"%@/%s", Cache_, file]
277 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
279 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
281 static NSString *UniqueIdentifier(UIDevice *device = nil) {
282 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
283 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
285 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
288 static bool IsReachable(const char *name) {
289 SCNetworkReachabilityFlags flags; {
290 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
291 SCNetworkReachabilityGetFlags(reachability, &flags);
292 CFRelease(reachability);
295 // XXX: this elaborate mess is what Apple is using to determine this? :(
296 // XXX: do we care if the user has to intervene? maybe that's ok?
298 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
299 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
300 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
301 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
302 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
303 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
308 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
310 static _finline NSString *CydiaURL(NSString *path) {
312 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
313 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
314 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
315 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
316 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
318 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
321 static void ReapZombie(pid_t pid) {
324 if (waitpid(pid, &status, 0) == -1)
330 static _finline void UpdateExternalStatus(uint64_t newStatus) {
332 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
333 notify_set_state(notify_token, newStatus);
334 notify_cancel(notify_token);
336 notify_post("com.saurik.Cydia.status");
339 static CGFloat CYStatusBarHeight() {
340 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
341 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
344 /* NSForcedOrderingSearch doesn't work on the iPhone */
345 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
346 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
347 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
349 /* Insertion Sort {{{ */
351 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
352 const char *ptr = (const char *)list;
354 CFIndex half = count / 2;
355 const char *probe = ptr + elementSize * half;
356 CFComparisonResult cr = comparator(element, probe, context);
357 if (0 == cr) return (probe - (const char *)list) / elementSize;
358 ptr = (cr < 0) ? ptr : probe + elementSize;
359 count = (cr < 0) ? half : (half + (count & 1) - 1);
361 return (ptr - (const char *)list) / elementSize;
364 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
365 const char *ptr = (const char *)list;
367 CFIndex half = count / 2;
368 const char *probe = ptr + elementSize * half;
369 CFComparisonResult cr = comparator(element, probe, context);
370 if (0 == cr) return (probe - (const char *)list) / elementSize;
371 ptr = (cr < 0) ? ptr : probe + elementSize;
372 count = (cr < 0) ? half : (half + (count & 1) - 1);
374 return (ptr - (const char *)list) / elementSize;
377 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
378 if (range.length == 0)
380 const void **values(new const void *[range.length]);
381 CFArrayGetValues(array, range, values);
383 #if HistogramInsertionSort > 0
384 uint32_t total(0), *offsets(new uint32_t[range.length]);
387 for (CFIndex index(1); index != range.length; ++index) {
388 const void *value(values[index]);
389 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
390 CFIndex correct(index);
391 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
392 #if HistogramInsertionSort > 1
393 NSLog(@"%@ < %@", value, values[correct - 1]);
398 if (correct != index) {
399 size_t offset(index - correct);
400 #if HistogramInsertionSort
404 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
406 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
407 values[correct] = value;
411 CFArrayReplaceValues(array, range, values, range.length);
414 #if HistogramInsertionSort > 0
415 for (CFIndex index(0); index != range.length; ++index)
416 if (offsets[index] != 0)
417 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
418 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
425 /* Apple Bug Fixes {{{ */
426 @implementation UIWebDocumentView (Cydia)
428 - (void) _setScrollerOffset:(CGPoint)offset {
429 UIScroller *scroller([self _scroller]);
431 CGSize size([scroller contentSize]);
432 CGSize bounds([scroller bounds].size);
435 max.x = size.width - bounds.width;
436 max.y = size.height - bounds.height;
444 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
445 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
447 [scroller setOffset:offset];
453 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
454 size_t length([self length] - state->state);
457 else if (length > count)
459 for (size_t i(0); i != length; ++i)
460 objects[i] = [self item:state->state++];
461 state->itemsPtr = objects;
462 state->mutationsPtr = (unsigned long *) self;
466 /* Cydia NSString Additions {{{ */
467 @interface NSString (Cydia)
468 - (NSComparisonResult) compareByPath:(NSString *)other;
469 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
472 @implementation NSString (Cydia)
474 - (NSComparisonResult) compareByPath:(NSString *)other {
475 NSString *prefix = [self commonPrefixWithString:other options:0];
476 size_t length = [prefix length];
478 NSRange lrange = NSMakeRange(length, [self length] - length);
479 NSRange rrange = NSMakeRange(length, [other length] - length);
481 lrange = [self rangeOfString:@"/" options:0 range:lrange];
482 rrange = [other rangeOfString:@"/" options:0 range:rrange];
484 NSComparisonResult value;
486 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
487 value = NSOrderedSame;
488 else if (lrange.location == NSNotFound)
489 value = NSOrderedAscending;
490 else if (rrange.location == NSNotFound)
491 value = NSOrderedDescending;
493 value = NSOrderedSame;
495 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
496 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
497 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
498 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
500 NSComparisonResult result = [lpath compare:rpath];
501 return result == NSOrderedSame ? value : result;
504 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
505 return [(id)CFURLCreateStringByAddingPercentEscapes(
510 kCFStringEncodingUTF8
517 /* C++ NSString Wrapper Cache {{{ */
518 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
519 return size == 0 ? NULL :
520 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
521 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
524 static _finline CFStringRef CYStringCreate(const char *data) {
525 return CYStringCreate(data, strlen(data));
534 _finline void clear_() {
535 if (cache_ != NULL) {
542 _finline bool empty() const {
546 _finline size_t size() const {
550 _finline char *data() const {
554 _finline void clear() {
559 _finline CYString() :
566 _finline ~CYString() {
570 void operator =(const CYString &rhs) {
574 if (rhs.cache_ == nil)
577 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
580 void copy(apr_pool_t *pool) {
581 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
582 memcpy(temp, data_, size_);
587 void set(apr_pool_t *pool, const char *data, size_t size) {
593 data_ = const_cast<char *>(data);
601 _finline void set(apr_pool_t *pool, const char *data) {
602 set(pool, data, data == NULL ? 0 : strlen(data));
605 _finline void set(apr_pool_t *pool, const std::string &rhs) {
606 set(pool, rhs.data(), rhs.size());
609 bool operator ==(const CYString &rhs) const {
610 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
613 _finline operator CFStringRef() {
615 cache_ = CYStringCreate(data_, size_);
619 _finline operator id() {
620 return (NSString *) static_cast<CFStringRef>(*this);
623 _finline operator const char *() {
624 return reinterpret_cast<const char *>(data_);
628 /* C++ NSString Algorithm Adapters {{{ */
630 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
633 struct NSStringMapHash :
634 std::unary_function<NSString *, size_t>
636 _finline size_t operator ()(NSString *value) const {
637 return CFStringHashNSString((CFStringRef) value);
641 struct NSStringMapLess :
642 std::binary_function<NSString *, NSString *, bool>
644 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
645 return [lhs compare:rhs] == NSOrderedAscending;
649 struct NSStringMapEqual :
650 std::binary_function<NSString *, NSString *, bool>
652 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
653 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
654 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
655 //[lhs isEqualToString:rhs];
660 /* CoreGraphics Primitives {{{ */
665 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
666 CGFloat color[] = {red, green, blue, alpha};
667 return CGColorCreate(space, color);
676 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
677 color_(Create_(space, red, green, blue, alpha))
679 Set(space, red, green, blue, alpha);
684 CGColorRelease(color_);
691 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
693 color_ = Create_(space, red, green, blue, alpha);
696 operator CGColorRef() {
702 /* Random Global Variables {{{ */
703 static int PulseInterval_ = 500000;
705 static const NSString *UI_;
708 static bool RestartSubstrate_;
709 static NSArray *Finishes_;
711 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
712 #define NotifyConfig_ "/etc/notify.conf"
714 static bool Queuing_;
716 static CYColor Blue_;
717 static CYColor Blueish_;
718 static CYColor Black_;
719 static CYColor Folder_;
721 static CYColor White_;
722 static CYColor Gray_;
723 static CYColor Green_;
724 static CYColor Purple_;
725 static CYColor Purplish_;
727 static UIColor *InstallingColor_;
728 static UIColor *RemovingColor_;
730 static NSString *App_;
732 static BOOL Advanced_;
733 static BOOL Ignored_;
735 static _H<UIFont> Font12_;
736 static _H<UIFont> Font12Bold_;
737 static _H<UIFont> Font14_;
738 static _H<UIFont> Font18_;
739 static _H<UIFont> Font18Bold_;
740 static _H<UIFont> Font22Bold_;
742 static const char *Machine_ = NULL;
743 static _H<NSString> System_;
744 static NSString *SerialNumber_ = nil;
745 static NSString *ChipID_ = nil;
746 static NSString *BBSNum_ = nil;
747 static _H<NSString> Token_;
748 static _H<NSString> UniqueID_;
749 static _H<NSString> UserAgent_;
750 static _H<NSString> Product_;
751 static _H<NSString> Safari_;
753 static _H<NSLocale> CollationLocale_;
754 static _H<NSArray> CollationThumbs_;
755 static std::vector<NSInteger> CollationOffset_;
756 static _H<NSArray> CollationTitles_;
757 static _H<NSArray> CollationStarts_;
758 static UTransliterator *CollationTransl_;
759 //static Function<NSString *, NSString *> CollationModify_;
761 typedef std::basic_string<UChar> ustring;
762 static ustring CollationString_;
764 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
765 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
766 static struct UReplaceableCallbacks CollationUCalls_ = {
767 .length = [](const UReplaceable *rep) -> int32_t { CUC;
771 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
772 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
773 if (offset >= str.size())
778 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
779 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
780 if (offset >= str.size())
783 U16_GET(str.data(), 0, offset, str.size(), c);
787 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
788 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
789 str.replace(start, limit - start, text, length);
792 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
793 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
794 str.copy(dst, limit - start, start);
797 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
798 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
799 str.replace(dest, 0, str, start, limit - start);
803 static CFLocaleRef Locale_;
804 static NSArray *Languages_;
805 static CGColorSpaceRef space_;
807 static NSDictionary *SectionMap_;
808 static NSMutableDictionary *Metadata_;
809 static _transient NSMutableDictionary *Settings_;
810 static _transient NSMutableDictionary *Packages_;
811 static _transient NSMutableDictionary *Values_;
812 static _transient NSMutableDictionary *Sections_;
813 _H<NSMutableDictionary> Sources_;
814 static _transient NSNumber *Version_;
819 static CGFloat ScreenScale_;
820 static NSString *Idiom_;
821 static _H<NSString> Firmware_;
822 static NSString *Major_;
824 static _H<NSMutableDictionary> SessionData_;
825 static _H<NSObject> HostConfig_;
826 static _H<NSMutableSet> BridgedHosts_;
827 static _H<NSMutableSet> TokenHosts_;
828 static _H<NSMutableSet> InsecureHosts_;
829 static _H<NSMutableSet> PipelinedHosts_;
830 static _H<NSMutableSet> CachedURLs_;
832 static NSString *kCydiaProgressEventTypeError = @"Error";
833 static NSString *kCydiaProgressEventTypeInformation = @"Information";
834 static NSString *kCydiaProgressEventTypeStatus = @"Status";
835 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
838 /* Display Helpers {{{ */
839 inline float Interpolate(float begin, float end, float fraction) {
840 return (end - begin) * fraction + begin;
843 static inline double Retina(double value) {
844 value *= ScreenScale_;
845 value = round(value);
846 value /= ScreenScale_;
850 static inline CGRect Retina(CGRect value) {
851 value.origin.x *= ScreenScale_;
852 value.origin.y *= ScreenScale_;
853 value.size.width *= ScreenScale_;
854 value.size.height *= ScreenScale_;
855 value = CGRectIntegral(value);
856 value.origin.x /= ScreenScale_;
857 value.origin.y /= ScreenScale_;
858 value.size.width /= ScreenScale_;
859 value.size.height /= ScreenScale_;
863 static _finline const char *StripVersion_(const char *version) {
864 const char *colon(strchr(version, ':'));
865 return colon == NULL ? version : colon + 1;
868 NSString *LocalizeSection(NSString *section) {
869 static Pcre title_r("^(.*?) \\((.*)\\)$");
870 if (title_r(section)) {
871 NSString *parent(title_r[1]);
872 NSString *child(title_r[2]);
874 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
875 LocalizeSection(parent),
876 LocalizeSection(child)
880 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
883 NSString *Simplify(NSString *title) {
884 const char *data = [title UTF8String];
885 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
887 static Pcre square_r("^\\[(.*)\\]$");
888 if (square_r(data, size))
889 return Simplify(square_r[1]);
891 static Pcre paren_r("^\\((.*)\\)$");
892 if (paren_r(data, size))
893 return Simplify(paren_r[1]);
895 static Pcre title_r("^(.*?) \\((.*)\\)$");
896 if (title_r(data, size))
897 return Simplify(title_r[1]);
903 NSString *GetLastUpdate() {
904 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
907 return UCLocalize("NEVER_OR_UNKNOWN");
909 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
910 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
912 CFRelease(formatter);
914 return [(NSString *) formatted autorelease];
917 bool isSectionVisible(NSString *section) {
918 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
919 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
920 return hidden == nil || ![hidden boolValue];
923 static NSObject *CYIOGetValue(const char *path, NSString *property) {
924 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
925 if (entry == MACH_PORT_NULL)
928 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
929 IOObjectRelease(entry);
933 return [(id) value autorelease];
936 static NSString *CYHex(NSData *data, bool reverse = false) {
940 size_t length([data length]);
941 uint8_t bytes[length];
942 [data getBytes:bytes];
944 char string[length * 2 + 1];
945 for (size_t i(0); i != length; ++i)
946 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
948 return [NSString stringWithUTF8String:string];
953 /* Delegate Prototypes {{{ */
956 @class CydiaProgressEvent;
958 @protocol DatabaseDelegate
959 - (void) repairWithSelector:(SEL)selector;
960 - (void) setConfigurationData:(NSString *)data;
961 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
964 @class CYPackageController;
966 @protocol SourceDelegate
967 - (void) setFetch:(NSNumber *)fetch;
970 @protocol FetchDelegate
971 - (bool) isSourceCancelled;
972 - (void) startSourceFetch:(NSString *)uri;
973 - (void) stopSourceFetch:(NSString *)uri;
976 @protocol CydiaDelegate
977 - (void) returnToCydia;
979 - (void) retainNetworkActivityIndicator;
980 - (void) releaseNetworkActivityIndicator;
981 - (void) clearPackage:(Package *)package;
982 - (void) installPackage:(Package *)package;
983 - (void) installPackages:(NSArray *)packages;
984 - (void) removePackage:(Package *)package;
985 - (void) beginUpdate;
987 - (bool) requestUpdate;
988 - (void) distUpgrade;
991 - (void) _saveConfig;
993 - (void) addSource:(NSDictionary *)source;
994 - (void) addTrivialSource:(NSString *)href;
995 - (UIProgressHUD *) addProgressHUD;
996 - (void) removeProgressHUD:(UIProgressHUD *)hud;
997 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
998 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1002 /* CancelStatus {{{ */
1003 class CancelStatus :
1004 public pkgAcquireStatus
1015 virtual bool MediaChange(std::string media, std::string drive) {
1019 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1023 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1025 virtual bool Pulse(pkgAcquire *Owner) {
1026 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1034 _finline bool WasCancelled() const {
1039 /* DelegateStatus {{{ */
1044 _transient NSObject<ProgressDelegate> *delegate_;
1052 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1053 delegate_ = delegate;
1056 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1057 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1058 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1059 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1062 virtual void Done(pkgAcquire::ItemDesc &desc) {
1063 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1064 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1065 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1068 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1070 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1071 desc.Owner->Status == pkgAcquire::Item::StatDone
1075 std::string &error(desc.Owner->ErrorText);
1079 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1080 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1083 virtual bool Pulse_(pkgAcquire *Owner) {
1085 double(CurrentBytes + CurrentItems) /
1086 double(TotalBytes + TotalItems)
1089 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1090 [NSNumber numberWithDouble:percent], @"Percent",
1092 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1093 [NSNumber numberWithDouble:TotalBytes], @"Total",
1094 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1095 nil] waitUntilDone:YES];
1097 return ![delegate_ isProgressCancelled];
1100 virtual void Start() {
1101 pkgAcquireStatus::Start();
1102 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1105 virtual void Stop() {
1106 pkgAcquireStatus::Stop();
1107 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1108 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1112 /* Database Interface {{{ */
1113 typedef std::map< unsigned long, _H<Source> > SourceMap;
1115 @interface Database : NSObject {
1121 pkgCacheFile cache_;
1122 pkgDepCache::Policy *policy_;
1123 pkgRecords *records_;
1124 pkgProblemResolver *resolver_;
1125 pkgAcquire *fetcher_;
1127 SPtr<pkgPackageManager> manager_;
1128 pkgSourceList *list_;
1130 SourceMap sourceMap_;
1131 _H<NSMutableArray> sourceList_;
1133 CFMutableArrayRef packages_;
1135 _transient NSObject<DatabaseDelegate> *delegate_;
1136 _transient NSObject<ProgressDelegate> *progress_;
1138 CydiaStatus status_;
1144 std::map<const char *, _H<NSString> > sections_;
1147 + (Database *) sharedInstance;
1150 - (void) _readCydia:(NSNumber *)fd;
1151 - (void) _readStatus:(NSNumber *)fd;
1152 - (void) _readOutput:(NSNumber *)fd;
1156 - (Package *) packageWithName:(NSString *)name;
1158 - (pkgCacheFile &) cache;
1159 - (pkgDepCache::Policy *) policy;
1160 - (pkgRecords *) records;
1161 - (pkgProblemResolver *) resolver;
1162 - (pkgAcquire &) fetcher;
1163 - (pkgSourceList &) list;
1164 - (NSArray *) packages;
1165 - (NSArray *) sources;
1166 - (Source *) sourceWithKey:(NSString *)key;
1167 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1175 - (void) updateWithStatus:(CancelStatus &)status;
1177 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1179 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1180 - (NSObject<ProgressDelegate> *) progressDelegate;
1182 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1183 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1184 - (void) resetFetch;
1186 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1190 /* SourceStatus {{{ */
1191 class SourceStatus :
1195 _transient NSObject<FetchDelegate> *delegate_;
1196 _transient Database *database_;
1197 std::set<std::string> fetches_;
1200 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1201 delegate_(delegate),
1206 void Set(bool fetch, const std::string &uri) {
1208 if (!fetches_.insert(uri).second)
1211 if (fetches_.erase(uri) == 0)
1215 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1216 [database_ setFetch:fetch forURI:uri.c_str()];
1219 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1220 /*unsigned long ID(fetch ? 1 : 0);
1224 Set(fetch, item->DescURI());
1227 void Log(const char *tag, pkgAcquire::Item *item) {
1228 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1231 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1232 Log("Fetch", desc.Owner);
1233 Set(true, desc.Owner);
1236 virtual void Done(pkgAcquire::ItemDesc &desc) {
1237 Log("Done", desc.Owner);
1238 Set(false, desc.Owner);
1241 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1242 Log("Fail", desc.Owner);
1243 Set(false, desc.Owner);
1246 virtual bool Pulse_(pkgAcquire *Owner) {
1247 std::set<std::string> fetches;
1248 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1250 if ((*item)->QueueCounter == 0)
1252 else switch ((*item)->Status) {
1253 case pkgAcquire::Item::StatFetching:
1254 fetches.insert((*item)->DescURI());
1263 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1267 std::vector<std::string> stops;
1268 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1269 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1270 //printf("Stop(%s)\n", stop->c_str());
1274 return ![delegate_ isSourceCancelled];
1277 virtual void Stop() {
1278 pkgAcquireStatus::Stop();
1279 [database_ resetFetch];
1283 /* ProgressEvent Implementation {{{ */
1284 @implementation CydiaProgressEvent
1286 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1287 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1290 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1291 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1292 [event setPackage:package];
1296 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1297 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1299 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1300 NSArray *fields([description componentsSeparatedByString:@" "]);
1301 [event setItem:fields];
1303 if ([fields count] > 3) {
1304 [event setPackage:[fields objectAtIndex:2]];
1305 [event setVersion:[fields objectAtIndex:3]];
1308 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1313 + (NSArray *) _attributeKeys {
1314 return [NSArray arrayWithObjects:
1324 - (NSArray *) attributeKeys {
1325 return [[self class] _attributeKeys];
1328 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1329 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1332 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1333 if ((self = [super init]) != nil) {
1339 - (NSString *) message {
1343 - (NSString *) type {
1347 - (NSArray *) item {
1348 return (id) item_ ?: [NSNull null];
1351 - (void) setItem:(NSArray *)item {
1355 - (NSString *) package {
1356 return (id) package_ ?: [NSNull null];
1359 - (void) setPackage:(NSString *)package {
1363 - (NSString *) url {
1364 return (id) url_ ?: [NSNull null];
1367 - (void) setURL:(NSString *)url {
1371 - (void) setVersion:(NSString *)version {
1375 - (NSString *) version {
1376 return (id) version_ ?: [NSNull null];
1379 - (NSString *) compound:(NSString *)value {
1381 NSString *mode(nil); {
1382 NSString *type([self type]);
1383 if ([type isEqualToString:kCydiaProgressEventTypeError])
1384 mode = UCLocalize("ERROR");
1385 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1386 mode = UCLocalize("WARNING");
1390 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1396 - (NSString *) compoundMessage {
1397 return [self compound:[self message]];
1400 - (NSString *) compoundTitle {
1403 if (package_ == nil)
1405 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1406 title = [package name];
1410 return [self compound:title];
1416 // Cytore Definitions {{{
1417 struct PackageValue :
1420 Cytore::Offset<PackageValue> next_;
1422 uint32_t index_ : 23;
1423 uint32_t subscribed_ : 1;
1440 Cytore::Offset<PackageValue> packages_[1 << 16];
1443 static Cytore::File<MetaValue> MetaFile_;
1445 // Cytore Helper Functions {{{
1446 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1447 SplitHash nhash = { hashlittle(name, length) };
1449 PackageValue *metadata;
1451 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1452 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1453 *offset = MetaFile_.New<PackageValue>(length + 1);
1454 metadata = &MetaFile_.Get(*offset);
1456 if (metadata == NULL) {
1460 metadata = new PackageValue();
1461 memset(metadata, 0, sizeof(*metadata));
1464 memcpy(metadata->name_, name, length);
1465 metadata->name_[length] = '\0';
1466 metadata->nhash_ = nhash.u16[1];
1468 metadata = &MetaFile_.Get(*offset);
1469 if (metadata->nhash_ != nhash.u16[1])
1471 if (strncmp(metadata->name_, name, length) != 0)
1473 if (metadata->name_[length] != '\0')
1480 static void PackageImport(const void *key, const void *value, void *context) {
1481 bool &fail(*reinterpret_cast<bool *>(context));
1484 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1485 NSLog(@"failed to import package %@", key);
1489 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1490 NSDictionary *package((NSDictionary *) value);
1492 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1493 if ([subscribed boolValue] && !metadata->subscribed_)
1494 metadata->subscribed_ = true;
1496 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1497 time_t time([date timeIntervalSince1970]);
1498 if (metadata->first_ > time || metadata->first_ == 0)
1499 metadata->first_ = time;
1502 NSDate *date([package objectForKey:@"LastSeen"]);
1503 NSString *version([package objectForKey:@"LastVersion"]);
1505 if (date != nil && version != nil) {
1506 time_t time([date timeIntervalSince1970]);
1507 if (metadata->last_ < time || metadata->last_ == 0)
1508 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1509 size_t length(strlen(buffer));
1510 uint16_t vhash(hashlittle(buffer, length));
1512 size_t capped(std::min<size_t>(8, length));
1513 char *latest(buffer + length - capped);
1515 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1516 metadata->vhash_ = vhash;
1518 metadata->last_ = time;
1524 /* Source Class {{{ */
1525 @interface Source : NSObject {
1527 Database *database_;
1530 CYString depiction_;
1531 CYString description_;
1537 CYString distribution_;
1543 _H<NSString> authority_;
1545 CYString defaultIcon_;
1547 _H<NSMutableDictionary> record_;
1550 std::set<std::string> fetches_;
1551 std::set<std::string> files_;
1552 _transient NSObject<SourceDelegate> *delegate_;
1555 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1557 - (NSComparisonResult) compareByName:(Source *)source;
1559 - (NSString *) depictionForPackage:(NSString *)package;
1560 - (NSString *) supportForPackage:(NSString *)package;
1562 - (metaIndex *) metaIndex;
1563 - (NSDictionary *) record;
1566 - (NSString *) rooturi;
1567 - (NSString *) distribution;
1568 - (NSString *) type;
1571 - (NSString *) host;
1573 - (NSString *) name;
1574 - (NSString *) shortDescription;
1575 - (NSString *) label;
1576 - (NSString *) origin;
1577 - (NSString *) version;
1579 - (NSString *) defaultIcon;
1580 - (NSURL *) iconURL;
1582 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1583 - (void) resetFetch;
1587 @implementation Source
1589 + (NSString *) webScriptNameForSelector:(SEL)selector {
1591 else if (selector == @selector(addSection:))
1592 return @"addSection";
1593 else if (selector == @selector(getField:))
1595 else if (selector == @selector(removeSection:))
1596 return @"removeSection";
1597 else if (selector == @selector(remove))
1603 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1604 return [self webScriptNameForSelector:selector] == nil;
1607 + (NSArray *) _attributeKeys {
1608 return [NSArray arrayWithObjects:
1619 @"shortDescription",
1626 - (NSArray *) attributeKeys {
1627 return [[self class] _attributeKeys];
1630 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1631 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1634 - (metaIndex *) metaIndex {
1638 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1639 trusted_ = index->IsTrusted();
1641 uri_.set(pool, index->GetURI());
1642 distribution_.set(pool, index->GetDist());
1643 type_.set(pool, index->GetType());
1645 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1646 if (dindex != NULL) {
1647 std::string file(dindex->MetaIndexURI(""));
1648 base_.set(pool, file);
1651 _profile(Source$setMetaIndex$GetIndexes)
1652 dindex->GetIndexes(&acquire, true);
1654 _profile(Source$setMetaIndex$DescURI)
1655 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1656 std::string file((*item)->DescURI());
1657 files_.insert(file);
1658 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1660 file = file.substr(0, file.length() - 4);
1661 files_.insert(file);
1662 files_.insert(file + ".gz");
1663 files_.insert(file + "Index");
1668 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1671 pkgTagFile tags(&fd);
1673 pkgTagSection section;
1680 {"default-icon", &defaultIcon_},
1681 {"depiction", &depiction_},
1682 {"description", &description_},
1684 {"origin", &origin_},
1685 {"support", &support_},
1686 {"version", &version_},
1689 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1690 const char *start, *end;
1692 if (section.Find(names[i].name_, start, end)) {
1693 CYString &value(*names[i].value_);
1694 value.set(pool, start, end - start);
1700 record_ = [Sources_ objectForKey:[self key]];
1702 NSURL *url([NSURL URLWithString:uri_]);
1706 host_ = [host_ lowercaseString];
1711 authority_ = [url path];
1714 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1715 if ((self = [super init]) != nil) {
1716 era_ = [database era];
1717 database_ = database;
1720 _profile(Source$initWithMetaIndex$setMetaIndex)
1721 [self setMetaIndex:index inPool:pool];
1726 - (NSString *) getField:(NSString *)name {
1727 @synchronized (database_) {
1728 if ([database_ era] != era_ || index_ == NULL)
1731 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1736 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1741 pkgTagFile tags(&fd);
1743 pkgTagSection section;
1746 const char *start, *end;
1747 if (!section.Find([name UTF8String], start, end))
1748 return (NSString *) [NSNull null];
1750 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1753 - (NSComparisonResult) compareByName:(Source *)source {
1754 NSString *lhs = [self name];
1755 NSString *rhs = [source name];
1757 if ([lhs length] != 0 && [rhs length] != 0) {
1758 unichar lhc = [lhs characterAtIndex:0];
1759 unichar rhc = [rhs characterAtIndex:0];
1761 if (isalpha(lhc) && !isalpha(rhc))
1762 return NSOrderedAscending;
1763 else if (!isalpha(lhc) && isalpha(rhc))
1764 return NSOrderedDescending;
1767 return [lhs compare:rhs options:LaxCompareOptions_];
1770 - (NSString *) depictionForPackage:(NSString *)package {
1771 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1774 - (NSString *) supportForPackage:(NSString *)package {
1775 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1778 - (NSArray *) sections {
1779 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1782 - (void) _addSection:(NSString *)section {
1785 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1786 if (![sections containsObject:section]) {
1787 [sections addObject:section];
1791 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1796 - (bool) addSection:(NSString *)section {
1800 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1804 - (void) _removeSection:(NSString *)section {
1808 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1809 if ([sections containsObject:section]) {
1810 [sections removeObject:section];
1815 - (bool) removeSection:(NSString *)section {
1819 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1824 [Sources_ removeObjectForKey:[self key]];
1829 bool value(record_ != nil);
1830 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1834 - (NSDictionary *) record {
1842 - (NSString *) rooturi {
1846 - (NSString *) distribution {
1847 return distribution_;
1850 - (NSString *) type {
1854 - (NSString *) baseuri {
1855 return base_.empty() ? nil : (id) base_;
1858 - (NSString *) iconuri {
1859 if (NSString *base = [self baseuri])
1860 return [base stringByAppendingString:@"CydiaIcon.png"];
1865 - (NSURL *) iconURL {
1866 if (NSString *uri = [self iconuri])
1867 return [NSURL URLWithString:uri];
1871 - (NSString *) key {
1872 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1875 - (NSString *) host {
1879 - (NSString *) name {
1880 return origin_.empty() ? (id) authority_ : origin_;
1883 - (NSString *) shortDescription {
1884 return description_;
1887 - (NSString *) label {
1888 return label_.empty() ? (id) authority_ : label_;
1891 - (NSString *) origin {
1895 - (NSString *) version {
1899 - (NSString *) defaultIcon {
1900 return defaultIcon_;
1903 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1904 delegate_ = delegate;
1908 return !fetches_.empty();
1911 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1913 if (fetches_.erase(uri) == 0)
1915 } else if (files_.find(uri) == files_.end())
1917 else if (!fetches_.insert(uri).second)
1920 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1923 - (void) resetFetch {
1925 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1930 /* CydiaOperation Class {{{ */
1931 @interface CydiaOperation : NSObject {
1932 _H<NSString> operator_;
1933 _H<NSString> value_;
1936 - (NSString *) operator;
1937 - (NSString *) value;
1941 @implementation CydiaOperation
1943 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1944 if ((self = [super init]) != nil) {
1945 operator_ = [NSString stringWithUTF8String:_operator];
1946 value_ = [NSString stringWithUTF8String:value];
1950 + (NSArray *) _attributeKeys {
1951 return [NSArray arrayWithObjects:
1957 - (NSArray *) attributeKeys {
1958 return [[self class] _attributeKeys];
1961 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1962 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1965 - (NSString *) operator {
1969 - (NSString *) value {
1975 /* CydiaClause Class {{{ */
1976 @interface CydiaClause : NSObject {
1977 _H<NSString> package_;
1978 _H<CydiaOperation> version_;
1981 - (NSString *) package;
1982 - (CydiaOperation *) version;
1986 @implementation CydiaClause
1988 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1989 if ((self = [super init]) != nil) {
1990 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1992 if (const char *version = dep.TargetVer())
1993 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1995 version_ = (id) [NSNull null];
1999 + (NSArray *) _attributeKeys {
2000 return [NSArray arrayWithObjects:
2006 - (NSArray *) attributeKeys {
2007 return [[self class] _attributeKeys];
2010 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2011 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2014 - (NSString *) package {
2018 - (CydiaOperation *) version {
2024 /* CydiaRelation Class {{{ */
2025 @interface CydiaRelation : NSObject {
2026 _H<NSString> relationship_;
2027 _H<NSMutableArray> clauses_;
2030 - (NSString *) relationship;
2031 - (NSArray *) clauses;
2035 @implementation CydiaRelation
2037 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2038 if ((self = [super init]) != nil) {
2039 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2040 clauses_ = [NSMutableArray arrayWithCapacity:8];
2042 pkgCache::DepIterator start;
2043 pkgCache::DepIterator end;
2044 dep.GlobOr(start, end); // ++dep
2047 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2049 // yes, seriously. (wtf?)
2057 + (NSArray *) _attributeKeys {
2058 return [NSArray arrayWithObjects:
2064 - (NSArray *) attributeKeys {
2065 return [[self class] _attributeKeys];
2068 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2069 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2072 - (NSString *) relationship {
2073 return relationship_;
2076 - (NSArray *) clauses {
2080 - (void) addClause:(CydiaClause *)clause {
2081 [clauses_ addObject:clause];
2086 /* Package Class {{{ */
2087 struct ParsedPackage {
2091 CYString architecture_;
2094 CYString depiction_;
2101 @interface Package : NSObject {
2103 @public uint32_t role_ : 3;
2104 uint32_t essential_ : 1;
2105 uint32_t obsolete_ : 1;
2106 uint32_t ignored_ : 1;
2107 uint32_t pooled_ : 1;
2113 _transient Database *database_;
2115 pkgCache::VerIterator version_;
2116 pkgCache::PkgIterator iterator_;
2117 pkgCache::VerFileIterator file_;
2121 CYString transform_;
2124 CYString installed_;
2127 const char *section_;
2128 _transient NSString *section$_;
2132 PackageValue *metadata_;
2133 ParsedPackage *parsed_;
2135 _H<NSMutableArray> tags_;
2138 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2139 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2141 - (pkgCache::PkgIterator) iterator;
2144 - (NSString *) section;
2145 - (NSString *) simpleSection;
2147 - (NSString *) longSection;
2148 - (NSString *) shortSection;
2152 - (MIMEAddress *) maintainer;
2154 - (NSString *) longDescription;
2155 - (NSString *) shortDescription;
2158 - (PackageValue *) metadata;
2161 - (bool) subscribed;
2162 - (bool) setSubscribed:(bool)subscribed;
2166 - (NSString *) latest;
2167 - (NSString *) installed;
2168 - (BOOL) uninstalled;
2171 - (BOOL) upgradableAndEssential:(BOOL)essential;
2174 - (BOOL) unfiltered;
2178 - (BOOL) halfConfigured;
2179 - (BOOL) halfInstalled;
2181 - (NSString *) mode;
2184 - (NSString *) name;
2186 - (NSString *) homepage;
2187 - (NSString *) depiction;
2188 - (MIMEAddress *) author;
2190 - (NSString *) support;
2192 - (NSArray *) files;
2193 - (NSArray *) warnings;
2194 - (NSArray *) applications;
2196 - (Source *) source;
2199 - (BOOL) matches:(NSArray *)query;
2201 - (BOOL) hasTag:(NSString *)tag;
2202 - (NSString *) primaryPurpose;
2203 - (NSArray *) purposes;
2204 - (bool) isCommercial;
2206 - (void) setIndex:(size_t)index;
2208 - (CYString &) cyname;
2210 - (uint32_t) compareBySection:(NSArray *)sections;
2217 uint32_t PackageChangesRadix(Package *self, void *) {
2222 uint32_t timestamp : 30;
2223 uint32_t ignored : 1;
2224 uint32_t upgradable : 1;
2228 bool upgradable([self upgradableAndEssential:YES]);
2229 value.bits.upgradable = upgradable ? 1 : 0;
2232 value.bits.timestamp = 0;
2233 value.bits.ignored = [self ignored] ? 0 : 1;
2234 value.bits.upgradable = 1;
2236 value.bits.timestamp = [self seen] >> 2;
2237 value.bits.ignored = 0;
2238 value.bits.upgradable = 0;
2241 return _not(uint32_t) - value.key;
2244 CYString &(*PackageName)(Package *self, SEL sel);
2246 uint32_t PackagePrefixRadix(Package *self, void *context) {
2247 size_t offset(reinterpret_cast<size_t>(context));
2248 CYString &name(PackageName(self, @selector(cyname)));
2250 size_t size(name.size());
2253 char *text(name.data());
2256 if (!isdigit(text[0]))
2260 while (size != digits && isdigit(text[digits]))
2268 if (offset == 0 && zeros != 0) {
2269 memset(data, '0', zeros);
2270 memcpy(data + zeros, text, 4 - zeros);
2272 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2273 if (size <= offset - zeros)
2276 text += offset - zeros;
2277 size -= offset - zeros;
2280 memcpy(data, text, 4);
2282 memcpy(data, text, size);
2283 memset(data + size, 0, 4 - size);
2286 for (size_t i(0); i != 4; ++i)
2287 if (isalpha(data[i]))
2295 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2297 /* XXX: ntohl may be more honest */
2298 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2301 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2302 _profile(PackageNameCompare)
2304 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2305 else if (rhn == NULL)
2306 return kCFCompareGreaterThan;
2308 CFIndex length(CFStringGetLength(lhn));
2310 _profile(PackageNameCompare$NumbersLast)
2311 if (length != 0 && CFStringGetLength(rhn) != 0) {
2312 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2313 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2314 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2315 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2316 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2320 _profile(PackageNameCompare$Compare)
2321 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2326 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2327 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2330 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2331 CYString &lhn(PackageName(lhs, @selector(cyname)));
2332 NSString *rhn(PackageName(rhs, @selector(cyname)));
2333 return StringNameCompare(lhn, rhn, lhn.size());
2336 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2337 return PackageNameCompare(*lhs, *rhs, arg);
2340 struct PackageNameOrdering :
2341 std::binary_function<Package *, Package *, bool>
2343 _finline bool operator ()(Package *lhs, Package *rhs) const {
2344 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2348 @implementation Package
2350 - (NSString *) description {
2351 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2356 apr_pool_destroy(pool_);
2357 if (parsed_ != NULL)
2362 + (NSString *) webScriptNameForSelector:(SEL)selector {
2364 else if (selector == @selector(clear))
2366 else if (selector == @selector(getField:))
2368 else if (selector == @selector(getRecord))
2369 return @"getRecord";
2370 else if (selector == @selector(hasTag:))
2372 else if (selector == @selector(install))
2374 else if (selector == @selector(remove))
2380 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2381 return [self webScriptNameForSelector:selector] == nil;
2384 + (NSArray *) _attributeKeys {
2385 return [NSArray arrayWithObjects:
2406 @"shortDescription",
2419 - (NSArray *) attributeKeys {
2420 return [[self class] _attributeKeys];
2423 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2424 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2427 - (NSArray *) relations {
2428 @synchronized (database_) {
2429 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2430 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2431 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2435 - (NSString *) architecture {
2437 @synchronized (database_) {
2438 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2441 - (NSString *) getField:(NSString *)name {
2442 @synchronized (database_) {
2443 if ([database_ era] != era_ || file_.end())
2446 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2448 const char *start, *end;
2449 if (!parser.Find([name UTF8String], start, end))
2450 return (NSString *) [NSNull null];
2452 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2455 - (NSString *) getRecord {
2456 @synchronized (database_) {
2457 if ([database_ era] != era_ || file_.end())
2460 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2462 const char *start, *end;
2463 parser.GetRec(start, end);
2465 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2469 if (parsed_ != NULL)
2471 @synchronized (database_) {
2472 if ([database_ era] != era_ || file_.end())
2475 ParsedPackage *parsed(new ParsedPackage);
2478 _profile(Package$parse)
2479 pkgRecords::Parser *parser;
2481 _profile(Package$parse$Lookup)
2482 parser = &[database_ records]->Lookup(file_);
2488 _profile(Package$parse$Find)
2493 {"architecture", &parsed->architecture_},
2494 {"icon", &parsed->icon_},
2495 {"depiction", &parsed->depiction_},
2496 {"homepage", &parsed->homepage_},
2497 {"website", &website},
2499 {"support", &parsed->support_},
2500 {"author", &parsed->author_},
2501 {"md5sum", &parsed->md5sum_},
2504 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2505 const char *start, *end;
2507 if (parser->Find(names[i].name_, start, end)) {
2508 CYString &value(*names[i].value_);
2509 _profile(Package$parse$Value)
2510 value.set(pool_, start, end - start);
2516 _profile(Package$parse$Tagline)
2517 const char *start, *end;
2518 if (parser->ShortDesc(start, end)) {
2519 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2522 while (stop != start && stop[-1] == '\r')
2524 parsed->tagline_.set(pool_, start, stop - start);
2528 _profile(Package$parse$Retain)
2529 if (parsed->homepage_.empty())
2530 parsed->homepage_ = website;
2531 if (parsed->homepage_ == parsed->depiction_)
2532 parsed->homepage_.clear();
2533 if (parsed->support_.empty())
2534 parsed->support_ = bugs;
2539 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2540 if ((self = [super init]) != nil) {
2541 _profile(Package$initWithVersion)
2543 apr_pool_create(&pool_, NULL);
2549 database_ = database;
2550 era_ = [database era];
2554 pkgCache::PkgIterator iterator(version.ParentPkg());
2555 iterator_ = iterator;
2557 _profile(Package$initWithVersion$Version)
2558 if (!version_.end())
2559 file_ = version_.FileList();
2561 pkgCache &cache([database_ cache]);
2562 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2566 _profile(Package$initWithVersion$Cache)
2567 name_.set(NULL, iterator.Display());
2569 latest_.set(NULL, StripVersion_(version_.VerStr()));
2571 pkgCache::VerIterator current(iterator.CurrentVer());
2573 installed_.set(NULL, StripVersion_(current.VerStr()));
2576 _profile(Package$initWithVersion$Transliterate) do {
2577 if (CollationTransl_ == NULL)
2582 _profile(Package$initWithVersion$Transliterate$utf8)
2583 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2584 for (size_t i(0), e(name_.size()); i != e; ++i)
2585 if (data[i] >= 0x80)
2590 UErrorCode code(U_ZERO_ERROR);
2593 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2594 CollationString_.resize(name_.size());
2595 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2596 if (!U_SUCCESS(code))
2598 CollationString_.resize(length);
2601 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2602 length = CollationString_.size();
2603 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2604 if (!U_SUCCESS(code))
2606 _assert(CollationString_.size() == length);
2609 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2610 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2611 if (code == U_BUFFER_OVERFLOW_ERROR)
2612 code = U_ZERO_ERROR;
2613 else if (!U_SUCCESS(code))
2618 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2619 transform = static_cast<char *>(apr_palloc(pool_, length));
2621 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2622 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2623 if (!U_SUCCESS(code))
2627 transform_.set(NULL, transform, length);
2628 } while (false); _end
2630 _profile(Package$initWithVersion$Tags)
2631 pkgCache::TagIterator tag(iterator.TagList());
2633 tags_ = [NSMutableArray arrayWithCapacity:8];
2635 goto tag; for (; !tag.end(); ++tag) tag: {
2636 const char *name(tag.Name());
2637 NSString *string((NSString *) CYStringCreate(name));
2641 [tags_ addObject:[string autorelease]];
2643 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2644 if (strcmp(name + 6, "enduser") == 0)
2646 else if (strcmp(name + 6, "hacker") == 0)
2648 else if (strcmp(name + 6, "developer") == 0)
2650 else if (strcmp(name + 6, "cydia") == 0)
2656 if (strncmp(name, "cydia::", 7) == 0) {
2657 if (strcmp(name + 7, "essential") == 0)
2659 else if (strcmp(name + 7, "obsolete") == 0)
2666 _profile(Package$initWithVersion$Metadata)
2667 const char *mixed(iterator.Name());
2668 size_t size(strlen(mixed));
2669 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2670 char lower[prefix + size + 5 + 1];
2672 for (size_t i(0); i != size; ++i)
2673 lower[prefix + i] = mixed[i] | 0x20;
2675 if (!installed_.empty()) {
2676 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2677 memcpy(lower + prefix + size, ".list", 6);
2679 if (stat(lower, &info) != -1)
2680 upgraded_ = info.st_birthtime;
2683 PackageValue *metadata(PackageFind(lower + prefix, size));
2684 metadata_ = metadata;
2686 id_.set(NULL, metadata->name_, size);
2688 const char *latest(version_.VerStr());
2689 size_t length(strlen(latest));
2691 uint16_t vhash(hashlittle(latest, length));
2693 size_t capped(std::min<size_t>(8, length));
2694 latest = latest + length - capped;
2696 if (metadata->first_ == 0)
2697 metadata->first_ = now_;
2699 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2700 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2701 metadata->vhash_ = vhash;
2702 metadata->last_ = now_;
2703 } else if (metadata->last_ == 0)
2704 metadata->last_ = metadata->first_;
2707 _profile(Package$initWithVersion$Section)
2708 section_ = version_.Section();
2711 _profile(Package$initWithVersion$Flags)
2712 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2713 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2718 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2719 pkgCache::VerIterator version;
2721 _profile(Package$packageWithIterator$GetCandidateVer)
2722 version = [database policy]->GetCandidateVer(iterator);
2730 _profile(Package$packageWithIterator$Allocate)
2731 package = [Package allocWithZone:zone];
2734 _profile(Package$packageWithIterator$Initialize)
2736 initWithVersion:version
2743 _profile(Package$packageWithIterator$Autorelease)
2744 package = [package autorelease];
2750 - (pkgCache::PkgIterator) iterator {
2754 - (NSString *) section {
2755 if (section$_ == nil) {
2756 if (section_ == NULL)
2759 _profile(Package$section$mappedSectionForPointer)
2760 section$_ = [database_ mappedSectionForPointer:section_];
2765 - (NSString *) simpleSection {
2766 if (NSString *section = [self section])
2767 return Simplify(section);
2772 - (NSString *) longSection {
2773 return LocalizeSection([self section]);
2776 - (NSString *) shortSection {
2777 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2780 - (NSString *) uri {
2783 pkgIndexFile *index;
2784 pkgCache::PkgFileIterator file(file_.File());
2785 if (![database_ list].FindIndex(file, index))
2787 return [NSString stringWithUTF8String:iterator_->Path];
2788 //return [NSString stringWithUTF8String:file.Site()];
2789 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2793 - (MIMEAddress *) maintainer {
2794 @synchronized (database_) {
2795 if ([database_ era] != era_ || file_.end())
2798 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2799 const std::string &maintainer(parser->Maintainer());
2800 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2803 - (NSString *) md5sum {
2804 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2808 @synchronized (database_) {
2809 if ([database_ era] != era_ || version_.end())
2812 return version_->InstalledSize;
2815 - (NSString *) longDescription {
2816 @synchronized (database_) {
2817 if ([database_ era] != era_ || file_.end())
2820 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2821 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2823 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2824 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2825 if ([lines count] < 2)
2828 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2829 for (size_t i(1), e([lines count]); i != e; ++i) {
2830 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2831 [trimmed addObject:trim];
2834 return [trimmed componentsJoinedByString:@"\n"];
2837 - (NSString *) shortDescription {
2838 if (parsed_ != NULL)
2839 return static_cast<NSString *>(parsed_->tagline_);
2841 @synchronized (database_) {
2842 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2844 const char *start, *end;
2845 if (!parser.ShortDesc(start, end))
2848 if (end - start > 200)
2852 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2855 while (end != start && end[-1] == '\r')
2859 return [(id) CYStringCreate(start, end - start) autorelease];
2863 _profile(Package$index)
2864 CFStringRef name((CFStringRef) [self name]);
2865 if (CFStringGetLength(name) == 0)
2867 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2868 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2870 return toupper(character);
2874 - (PackageValue *) metadata {
2879 PackageValue *metadata([self metadata]);
2880 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2883 - (bool) subscribed {
2884 return [self metadata]->subscribed_;
2887 - (bool) setSubscribed:(bool)subscribed {
2888 PackageValue *metadata([self metadata]);
2889 if (metadata->subscribed_ == subscribed)
2891 metadata->subscribed_ = subscribed;
2899 - (NSString *) latest {
2903 - (NSString *) installed {
2907 - (BOOL) uninstalled {
2908 return installed_.empty();
2912 return !version_.end();
2915 - (BOOL) upgradableAndEssential:(BOOL)essential {
2916 _profile(Package$upgradableAndEssential)
2917 pkgCache::VerIterator current(iterator_.CurrentVer());
2919 return essential && essential_;
2921 return !version_.end() && version_ != current;
2925 - (BOOL) essential {
2930 return [database_ cache][iterator_].InstBroken();
2933 - (BOOL) unfiltered {
2934 _profile(Package$unfiltered$obsolete)
2935 if (_unlikely(obsolete_))
2939 _profile(Package$unfiltered$role)
2940 if (_unlikely(role_ > 3))
2948 if (![self unfiltered])
2953 _profile(Package$visible$section)
2954 section = [self section];
2957 _profile(Package$visible$isSectionVisible)
2958 if (!isSectionVisible(section))
2966 unsigned char current(iterator_->CurrentState);
2967 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2970 - (BOOL) halfConfigured {
2971 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2974 - (BOOL) halfInstalled {
2975 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2979 @synchronized (database_) {
2980 if ([database_ era] != era_ || iterator_.end())
2983 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2984 return state.Mode != pkgDepCache::ModeKeep;
2987 - (NSString *) mode {
2988 @synchronized (database_) {
2989 if ([database_ era] != era_ || iterator_.end())
2992 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2994 switch (state.Mode) {
2995 case pkgDepCache::ModeDelete:
2996 if ((state.iFlags & pkgDepCache::Purge) != 0)
3000 case pkgDepCache::ModeKeep:
3001 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3002 return @"REINSTALL";
3003 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3007 case pkgDepCache::ModeInstall:
3008 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3009 return @"REINSTALL";
3010 else*/ switch (state.Status) {
3012 return @"DOWNGRADE";
3018 return @"NEW_INSTALL";
3029 - (NSString *) name {
3030 return name_.empty() ? id_ : name_;
3033 - (UIImage *) icon {
3034 NSString *section = [self simpleSection];
3037 if (parsed_ != NULL)
3038 if (NSString *href = parsed_->icon_)
3039 if ([href hasPrefix:@"file:///"])
3040 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3041 if (icon == nil) if (section != nil)
3042 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3043 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3044 if ([dicon hasPrefix:@"file:///"])
3045 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3047 icon = [UIImage imageNamed:@"unknown.png"];
3051 - (NSString *) homepage {
3052 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3055 - (NSString *) depiction {
3056 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3059 - (MIMEAddress *) author {
3060 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3063 - (NSString *) support {
3064 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3067 - (NSArray *) files {
3068 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3069 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3072 fin.open([path UTF8String]);
3077 while (std::getline(fin, line))
3078 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3083 - (NSString *) state {
3084 @synchronized (database_) {
3085 if ([database_ era] != era_ || file_.end())
3088 switch (iterator_->CurrentState) {
3089 case pkgCache::State::NotInstalled:
3090 return @"NotInstalled";
3091 case pkgCache::State::UnPacked:
3093 case pkgCache::State::HalfConfigured:
3094 return @"HalfConfigured";
3095 case pkgCache::State::HalfInstalled:
3096 return @"HalfInstalled";
3097 case pkgCache::State::ConfigFiles:
3098 return @"ConfigFiles";
3099 case pkgCache::State::Installed:
3100 return @"Installed";
3101 case pkgCache::State::TriggersAwaited:
3102 return @"TriggersAwaited";
3103 case pkgCache::State::TriggersPending:
3104 return @"TriggersPending";
3107 return (NSString *) [NSNull null];
3110 - (NSString *) selection {
3111 @synchronized (database_) {
3112 if ([database_ era] != era_ || file_.end())
3115 switch (iterator_->SelectedState) {
3116 case pkgCache::State::Unknown:
3118 case pkgCache::State::Install:
3120 case pkgCache::State::Hold:
3122 case pkgCache::State::DeInstall:
3123 return @"DeInstall";
3124 case pkgCache::State::Purge:
3128 return (NSString *) [NSNull null];
3131 - (NSArray *) warnings {
3132 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3133 const char *name(iterator_.Name());
3135 size_t length(strlen(name));
3136 if (length < 2) invalid:
3137 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3138 else for (size_t i(0); i != length; ++i)
3140 /* XXX: technically this is not allowed */
3141 (name[i] < 'A' || name[i] > 'Z') &&
3142 (name[i] < 'a' || name[i] > 'z') &&
3143 (name[i] < '0' || name[i] > '9') &&
3144 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3147 if (strcmp(name, "cydia") != 0) {
3150 bool _private = false;
3152 bool dsstore = false;
3154 bool repository = [[self section] isEqualToString:@"Repositories"];
3156 if (NSArray *files = [self files])
3157 for (NSString *file in files)
3158 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3160 else if (!user && [file isEqualToString:@"/User"])
3162 else if (!_private && [file isEqualToString:@"/private"])
3164 else if (!stash && [file isEqualToString:@"/var/stash"])
3166 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3169 /* XXX: this is not sensitive enough. only some folders are valid. */
3170 if (cydia && !repository)
3171 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3173 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3175 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3177 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3179 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3182 return [warnings count] == 0 ? nil : warnings;
3185 - (NSArray *) applications {
3186 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3188 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3190 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3191 if (NSArray *files = [self files])
3192 for (NSString *file in files)
3193 if (application_r(file)) {
3194 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3195 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3196 if ([id isEqualToString:me])
3199 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3201 display = application_r[1];
3203 NSString *bundle([file stringByDeletingLastPathComponent]);
3204 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3205 // XXX: maybe this should check if this is really a string, not just for length
3206 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3208 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3210 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3211 [applications addObject:application];
3213 [application addObject:id];
3214 [application addObject:display];
3215 [application addObject:url];
3218 return [applications count] == 0 ? nil : applications;
3221 - (Source *) source {
3222 if (source_ == nil) {
3223 @synchronized (database_) {
3224 if ([database_ era] != era_ || file_.end())
3225 source_ = (Source *) [NSNull null];
3227 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3231 return source_ == (Source *) [NSNull null] ? nil : source_;
3234 - (time_t) upgraded {
3238 - (uint32_t) recent {
3239 return std::numeric_limits<uint32_t>::max() - upgraded_;
3246 - (BOOL) matches:(NSArray *)query {
3247 if (query == nil || [query count] == 0)
3256 string = [self name];
3257 length = [string length];
3260 for (NSString *term in query) {
3261 range = [string rangeOfString:term options:MatchCompareOptions_];
3262 if (range.location != NSNotFound)
3263 rank_ -= 6 * 1000000 / length;
3268 length = [string length];
3271 for (NSString *term in query) {
3272 range = [string rangeOfString:term options:MatchCompareOptions_];
3273 if (range.location != NSNotFound)
3274 rank_ -= 6 * 1000000 / length;
3278 string = [self shortDescription];
3279 length = [string length];
3280 NSUInteger stop(std::min<NSUInteger>(length, 200));
3283 for (NSString *term in query) {
3284 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3285 if (range.location != NSNotFound)
3286 rank_ -= 2 * 100000;
3292 - (NSArray *) tags {
3296 - (BOOL) hasTag:(NSString *)tag {
3297 return tags_ == nil ? NO : [tags_ containsObject:tag];
3300 - (NSString *) primaryPurpose {
3301 for (NSString *tag in (NSArray *) tags_)
3302 if ([tag hasPrefix:@"purpose::"])
3303 return [tag substringFromIndex:9];
3307 - (NSArray *) purposes {
3308 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3309 for (NSString *tag in (NSArray *) tags_)
3310 if ([tag hasPrefix:@"purpose::"])
3311 [purposes addObject:[tag substringFromIndex:9]];
3312 return [purposes count] == 0 ? nil : purposes;
3315 - (bool) isCommercial {
3316 return [self hasTag:@"cydia::commercial"];
3319 - (void) setIndex:(size_t)index {
3320 if (metadata_->index_ != index)
3321 metadata_->index_ = index;
3324 - (CYString &) cyname {
3325 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3328 - (uint32_t) compareBySection:(NSArray *)sections {
3329 NSString *section([self section]);
3330 for (size_t i(0), e([sections count]); i != e; ++i) {
3331 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3335 return _not(uint32_t);
3339 @synchronized (database_) {
3340 pkgProblemResolver *resolver = [database_ resolver];
3341 resolver->Clear(iterator_);
3343 pkgCacheFile &cache([database_ cache]);
3344 cache->SetReInstall(iterator_, false);
3345 cache->MarkKeep(iterator_, false);
3349 @synchronized (database_) {
3350 pkgProblemResolver *resolver = [database_ resolver];
3351 resolver->Clear(iterator_);
3352 resolver->Protect(iterator_);
3354 pkgCacheFile &cache([database_ cache]);
3355 cache->SetReInstall(iterator_, false);
3356 cache->MarkInstall(iterator_, false);
3358 pkgDepCache::StateCache &state((*cache)[iterator_]);
3359 if (!state.Install())
3360 cache->SetReInstall(iterator_, true);
3364 @synchronized (database_) {
3365 pkgProblemResolver *resolver = [database_ resolver];
3366 resolver->Clear(iterator_);
3367 resolver->Remove(iterator_);
3368 resolver->Protect(iterator_);
3370 pkgCacheFile &cache([database_ cache]);
3371 cache->SetReInstall(iterator_, false);
3372 cache->MarkDelete(iterator_, true);
3377 /* Section Class {{{ */
3378 @interface Section : NSObject {
3382 _H<NSString> localized_;
3385 - (NSComparisonResult) compareByLocalized:(Section *)section;
3386 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3387 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3388 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3390 - (NSString *) name;
3391 - (void) setName:(NSString *)name;
3397 - (void) addToCount;
3399 - (void) setCount:(size_t)count;
3400 - (NSString *) localized;
3404 @implementation Section
3406 - (NSComparisonResult) compareByLocalized:(Section *)section {
3407 NSString *lhs(localized_);
3408 NSString *rhs([section localized]);
3410 /*if ([lhs length] != 0 && [rhs length] != 0) {
3411 unichar lhc = [lhs characterAtIndex:0];
3412 unichar rhc = [rhs characterAtIndex:0];
3414 if (isalpha(lhc) && !isalpha(rhc))
3415 return NSOrderedAscending;
3416 else if (!isalpha(lhc) && isalpha(rhc))
3417 return NSOrderedDescending;
3420 return [lhs compare:rhs options:LaxCompareOptions_];
3423 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3424 if ((self = [self initWithName:name localize:NO]) != nil) {
3425 if (localized != nil)
3426 localized_ = localized;
3430 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3431 return [self initWithName:name row:0 localize:localize];
3434 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3435 if ((self = [super init]) != nil) {
3439 localized_ = LocalizeSection(name_);
3443 - (NSString *) name {
3447 - (void) setName:(NSString *)name {
3463 - (void) addToCount {
3467 - (void) setCount:(size_t)count {
3471 - (NSString *) localized {
3478 class CydiaLogCleaner :
3479 public pkgArchiveCleaner
3482 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3487 /* Database Implementation {{{ */
3488 @implementation Database
3490 + (Database *) sharedInstance {
3491 static _H<Database> instance;
3492 if (instance == nil)
3493 instance = [[[Database alloc] init] autorelease];
3501 - (void) releasePackages {
3502 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3503 CFArrayRemoveAllValues(packages_);
3507 // XXX: actually implement this thing
3509 [self releasePackages];
3510 apr_pool_destroy(pool_);
3511 NSRecycleZone(zone_);
3515 - (void) _readCydia:(NSNumber *)fd {
3516 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3517 std::istream is(&ib);
3520 static Pcre finish_r("^finish:([^:]*)$");
3522 while (std::getline(is, line)) {
3523 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3525 const char *data(line.c_str());
3526 size_t size = line.size();
3527 lprintf("C:%s\n", data);
3529 if (finish_r(data, size)) {
3530 NSString *finish = finish_r[1];
3531 int index = [Finishes_ indexOfObject:finish];
3532 if (index != INT_MAX && index > Finish_)
3542 - (void) _readStatus:(NSNumber *)fd {
3543 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3544 std::istream is(&ib);
3547 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3548 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3550 while (std::getline(is, line)) {
3551 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3553 const char *data(line.c_str());
3554 size_t size(line.size());
3555 lprintf("S:%s\n", data);
3557 if (conffile_r(data, size)) {
3558 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3559 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3560 } else if (strncmp(data, "status: ", 8) == 0) {
3561 // status: <package>: {unpacked,half-configured,installed}
3562 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3563 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3564 } else if (strncmp(data, "processing: ", 12) == 0) {
3565 // processing: configure: config-test
3566 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3567 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3568 } else if (pmstatus_r(data, size)) {
3569 std::string type([pmstatus_r[1] UTF8String]);
3571 NSString *package = pmstatus_r[2];
3572 if ([package isEqualToString:@"dpkg-exec"])
3575 float percent([pmstatus_r[3] floatValue]);
3576 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3578 NSString *string = pmstatus_r[4];
3580 if (type == "pmerror") {
3581 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3582 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3583 } else if (type == "pmstatus") {
3584 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3585 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3586 } else if (type == "pmconffile")
3587 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3589 lprintf("E:unknown pmstatus\n");
3591 lprintf("E:unknown status\n");
3599 - (void) _readOutput:(NSNumber *)fd {
3600 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3601 std::istream is(&ib);
3604 while (std::getline(is, line)) {
3605 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3607 lprintf("O:%s\n", line.c_str());
3609 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3610 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3622 - (Package *) packageWithName:(NSString *)name {
3625 @synchronized (self) {
3626 if (static_cast<pkgDepCache *>(cache_) == NULL)
3628 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3629 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3633 if ((self = [super init]) != nil) {
3640 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3641 apr_pool_create(&pool_, NULL);
3643 size_t capacity(MetaFile_->active_);
3649 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3650 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3654 _assert(pipe(fds) != -1);
3657 _config->Set("APT::Keep-Fds::", cydiafd_);
3658 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3661 detachNewThreadSelector:@selector(_readCydia:)
3663 withObject:[NSNumber numberWithInt:fds[0]]
3666 _assert(pipe(fds) != -1);
3670 detachNewThreadSelector:@selector(_readStatus:)
3672 withObject:[NSNumber numberWithInt:fds[0]]
3675 _assert(pipe(fds) != -1);
3676 _assert(dup2(fds[0], 0) != -1);
3677 _assert(close(fds[0]) != -1);
3679 input_ = fdopen(fds[1], "a");
3681 _assert(pipe(fds) != -1);
3682 _assert(dup2(fds[1], 1) != -1);
3683 _assert(close(fds[1]) != -1);
3686 detachNewThreadSelector:@selector(_readOutput:)
3688 withObject:[NSNumber numberWithInt:fds[0]]
3693 - (pkgCacheFile &) cache {
3697 - (pkgDepCache::Policy *) policy {
3701 - (pkgRecords *) records {
3705 - (pkgProblemResolver *) resolver {
3709 - (pkgAcquire &) fetcher {
3713 - (pkgSourceList &) list {
3717 - (NSArray *) packages {
3718 return (NSArray *) packages_;
3721 - (NSArray *) sources {
3725 - (Source *) sourceWithKey:(NSString *)key {
3726 for (Source *source in [self sources]) {
3727 if ([[source key] isEqualToString:key])
3732 - (bool) popErrorWithTitle:(NSString *)title {
3735 while (!_error->empty()) {
3737 bool warning(!_error->PopMessage(error));
3742 size_t size(error.size());
3743 if (size == 0 || error[size - 1] != '\n')
3745 error.resize(size - 1);
3748 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3750 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3751 if (warning && no_pubkey(error.c_str()))
3754 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3760 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3761 return [self popErrorWithTitle:title] || !success;
3764 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3765 @synchronized (self) {
3768 [self releasePackages];
3771 [sourceList_ removeAllObjects];
3791 apr_pool_clear(pool_);
3793 NSRecycleZone(zone_);
3794 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3796 int chk(creat("/tmp/cydia.chk", 0644));
3800 if (invocation != nil)
3801 [invocation invoke];
3803 NSString *title(UCLocalize("DATABASE"));
3805 list_ = new pkgSourceList();
3806 _profile(reloadDataWithInvocation$ReadMainList)
3807 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3811 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3812 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3813 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3814 [sourceList_ addObject:object];
3818 _root(true) _system->Lock();
3821 OpProgress progress;
3824 _profile(reloadDataWithInvocation$pkgCacheFile)
3825 opened = cache_.Open(progress, false);
3828 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3829 while (!_error->empty()) {
3831 bool warning(!_error->PopMessage(error));
3833 lprintf("cache_.Open():[%s]\n", error.c_str());
3835 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3839 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3840 repair = @selector(configure);
3841 //else if (error == "The package lists or status file could not be parsed or opened.")
3842 // repair = @selector(update);
3843 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3844 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3845 // else if (error == "Malformed Status line")
3846 // else if (error == "The list of sources could not be read.")
3848 if (repair != NULL) {
3850 [delegate_ repairWithSelector:repair];
3860 unlink("/tmp/cydia.chk");
3862 now_ = [[NSDate date] timeIntervalSince1970];
3864 policy_ = new pkgDepCache::Policy();
3865 records_ = new pkgRecords(cache_);
3866 resolver_ = new pkgProblemResolver(cache_);
3867 fetcher_ = new pkgAcquire(&status_);
3870 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3871 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3875 _profile(reloadDataWithInvocation$pkgApplyStatus)
3876 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3880 if (cache_->BrokenCount() != 0) {
3881 _profile(pkgApplyStatus$pkgFixBroken)
3882 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3886 if (cache_->BrokenCount() != 0) {
3887 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3891 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3892 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3897 for (Source *object in (id) sourceList_) {
3898 metaIndex *source([object metaIndex]);
3899 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3900 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3901 // XXX: this could be more intelligent
3902 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3903 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3905 sourceMap_[cached->ID] = object;
3910 /*std::vector<Package *> packages;
3911 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3914 _profile(reloadDataWithInvocation$packageWithIterator)
3915 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3916 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3917 //packages.push_back(package);
3918 CFArrayAppendValue(packages_, CFRetain(package));
3922 /*if (packages.empty())
3923 packages_ = [[NSArray alloc] init];
3925 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3928 _profile(reloadDataWithInvocation$radix$8)
3929 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3932 _profile(reloadDataWithInvocation$radix$4)
3933 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3936 _profile(reloadDataWithInvocation$radix$0)
3937 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3940 _profile(reloadDataWithInvocation$insertion)
3941 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3944 /*_profile(reloadDataWithInvocation$CFQSortArray)
3945 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3948 /*_profile(reloadDataWithInvocation$stdsort)
3949 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3952 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3953 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3956 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3957 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3961 size_t count(CFArrayGetCount(packages_));
3962 MetaFile_->active_ = count;
3963 for (size_t index(0); index != count; ++index)
3964 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3969 @synchronized (self) {
3971 resolver_ = new pkgProblemResolver(cache_);
3973 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3974 if (!cache_[iterator].Keep())
3975 cache_->MarkKeep(iterator, false);
3976 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3977 cache_->SetReInstall(iterator, false);
3980 - (void) configure {
3981 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3983 system([dpkg UTF8String]);
3988 @synchronized (self) {
3989 // XXX: I don't remember this condition
3994 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3996 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3998 if ([self popErrorWithTitle:title])
4002 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4004 CydiaLogCleaner cleaner;
4005 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4012 fetcher_->Shutdown();
4014 pkgRecords records(cache_);
4016 lock_ = new FileFd();
4017 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4019 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4021 if ([self popErrorWithTitle:title])
4025 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4028 manager_ = (_system->CreatePM(cache_));
4029 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4036 bool substrate(RestartSubstrate_);
4037 RestartSubstrate_ = false;
4039 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4041 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4043 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4045 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4046 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4049 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4051 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4053 [self popErrorWithTitle:title];
4057 bool failed = false;
4058 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4059 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4061 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4064 std::string uri = (*item)->DescURI();
4065 std::string error = (*item)->ErrorText;
4067 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4070 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4071 [delegate_ addProgressEventOnMainThread:event forTask:title];
4074 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4082 RestartSubstrate_ = true;
4085 pkgPackageManager::OrderResult result;
4086 _root(true) result = manager_->DoInstall(statusfd_);
4087 if ([self popErrorWithTitle:title])
4090 if (result == pkgPackageManager::Failed) {
4095 if (result != pkgPackageManager::Completed) {
4100 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4102 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4104 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4105 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4108 if (![before isEqualToArray:after])
4113 NSString *title(UCLocalize("UPGRADE"));
4114 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4120 [self updateWithStatus:status_];
4123 - (void) updateWithStatus:(CancelStatus &)status {
4124 NSString *title(UCLocalize("REFRESHING_DATA"));
4127 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4131 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4132 if ([self popErrorWithTitle:title])
4135 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4137 bool success(ListUpdate(status, list, PulseInterval_));
4138 if (status.WasCancelled())
4141 [self popErrorWithTitle:title forOperation:success];
4142 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4146 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4149 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4150 delegate_ = delegate;
4153 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4154 progress_ = delegate;
4155 status_.setDelegate(delegate);
4158 - (NSObject<ProgressDelegate> *) progressDelegate {
4162 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4163 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4164 return i == sourceMap_.end() ? nil : i->second;
4167 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4168 for (Source *source in (id) sourceList_)
4169 [source setFetch:fetch forURI:uri];
4172 - (void) resetFetch {
4173 for (Source *source in (id) sourceList_)
4174 [source resetFetch];
4177 - (NSString *) mappedSectionForPointer:(const char *)section {
4178 _H<NSString> *mapped;
4180 _profile(Database$mappedSectionForPointer$Cache)
4181 mapped = §ions_[section];
4184 if (*mapped == NULL) {
4185 size_t length(strlen(section));
4186 char spaced[length + 1];
4188 _profile(Database$mappedSectionForPointer$Replace)
4189 for (size_t index(0); index != length; ++index)
4190 spaced[index] = section[index] == '_' ? ' ' : section[index];
4191 spaced[length] = '\0';
4196 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4197 string = [NSString stringWithUTF8String:spaced];
4200 _profile(Database$mappedSectionForPointer$Map)
4201 string = [SectionMap_ objectForKey:string] ?: string;
4211 static _H<NSMutableSet> Diversions_;
4213 @interface Diversion : NSObject {
4216 _H<NSString> format_;
4221 @implementation Diversion
4223 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4224 if ((self = [super init]) != nil) {
4225 pattern_ = [from UTF8String];
4231 - (NSString *) divert:(NSString *)url {
4232 return !pattern_(url) ? nil : pattern_->*format_;
4235 + (NSURL *) divertURL:(NSURL *)url {
4237 NSString *href([url absoluteString]);
4239 for (Diversion *diversion in (id) Diversions_)
4240 if (NSString *diverted = [diversion divert:href]) {
4242 NSLog(@"div: %@", diverted);
4244 url = [NSURL URLWithString:diverted];
4251 - (NSString *) key {
4255 - (NSUInteger) hash {
4259 - (BOOL) isEqual:(Diversion *)object {
4260 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4265 @interface CydiaObject : NSObject {
4266 _H<CyteWebViewController> indirect_;
4267 _transient id delegate_;
4270 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4276 @interface CydiaWebViewController : CyteWebViewController {
4277 _H<CydiaObject> cydia_;
4280 + (void) addDiversion:(Diversion *)diversion;
4281 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4282 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4283 - (void) setDelegate:(id)delegate;
4287 /* Web Scripting {{{ */
4288 @implementation CydiaObject
4290 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4291 if ((self = [super init]) != nil) {
4292 indirect_ = (CyteWebViewController *) indirect;
4296 - (void) setDelegate:(id)delegate {
4297 delegate_ = delegate;
4300 + (NSArray *) _attributeKeys {
4301 return [NSArray arrayWithObjects:
4304 @"coreFoundationVersionNumber",
4321 - (NSArray *) attributeKeys {
4322 return [[self class] _attributeKeys];
4325 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4326 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4329 - (NSString *) version {
4333 - (NSString *) build {
4337 - (NSString *) coreFoundationVersionNumber {
4338 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4341 - (NSString *) device {
4342 return UniqueIdentifier();
4345 - (NSString *) firmware {
4346 return [[UIDevice currentDevice] systemVersion];
4349 - (NSString *) hostname {
4350 return [[UIDevice currentDevice] name];
4353 - (NSString *) idiom {
4354 return (id) Idiom_ ?: [NSNull null];
4357 - (NSString *) mcc {
4358 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4359 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4363 - (NSString *) mnc {
4364 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4365 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4369 - (NSString *) operator {
4370 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4371 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4375 - (NSString *) bbsnum {
4376 return (id) BBSNum_ ?: [NSNull null];
4379 - (NSString *) ecid {
4380 return (id) ChipID_ ?: [NSNull null];
4383 - (NSString *) serial {
4384 return SerialNumber_;
4387 - (NSString *) role {
4388 return (id) [NSNull null];
4391 - (NSString *) model {
4392 return [NSString stringWithUTF8String:Machine_];
4395 - (NSString *) token {
4396 return (id) Token_ ?: [NSNull null];
4399 + (NSString *) webScriptNameForSelector:(SEL)selector {
4401 else if (selector == @selector(addBridgedHost:))
4402 return @"addBridgedHost";
4403 else if (selector == @selector(addInsecureHost:))
4404 return @"addInsecureHost";
4405 else if (selector == @selector(addInternalRedirect::))
4406 return @"addInternalRedirect";
4407 else if (selector == @selector(addPipelinedHost:scheme:))
4408 return @"addPipelinedHost";
4409 else if (selector == @selector(addSource:::))
4410 return @"addSource";
4411 else if (selector == @selector(addTokenHost:))
4412 return @"addTokenHost";
4413 else if (selector == @selector(addTrivialSource:))
4414 return @"addTrivialSource";
4415 else if (selector == @selector(close))
4417 else if (selector == @selector(du:))
4419 else if (selector == @selector(stringWithFormat:arguments:))
4421 else if (selector == @selector(getAllSources))
4422 return @"getAllSources";
4423 else if (selector == @selector(getApplicationInfo:value:))
4424 return @"getApplicationInfoValue";
4425 else if (selector == @selector(getKernelNumber:))
4426 return @"getKernelNumber";
4427 else if (selector == @selector(getKernelString:))
4428 return @"getKernelString";
4429 else if (selector == @selector(getInstalledPackages))
4430 return @"getInstalledPackages";
4431 else if (selector == @selector(getIORegistryEntry::))
4432 return @"getIORegistryEntry";
4433 else if (selector == @selector(getLocaleIdentifier))
4434 return @"getLocaleIdentifier";
4435 else if (selector == @selector(getPreferredLanguages))
4436 return @"getPreferredLanguages";
4437 else if (selector == @selector(getPackageById:))
4438 return @"getPackageById";
4439 else if (selector == @selector(getMetadataKeys))
4440 return @"getMetadataKeys";
4441 else if (selector == @selector(getMetadataValue:))
4442 return @"getMetadataValue";
4443 else if (selector == @selector(getSessionValue:))
4444 return @"getSessionValue";
4445 else if (selector == @selector(installPackages:))
4446 return @"installPackages";
4447 else if (selector == @selector(isReachable:))
4448 return @"isReachable";
4449 else if (selector == @selector(localizedStringForKey:value:table:))
4451 else if (selector == @selector(popViewController:))
4452 return @"popViewController";
4453 else if (selector == @selector(refreshSources))
4454 return @"refreshSources";
4455 else if (selector == @selector(registerFrame:))
4456 return @"registerFrame";
4457 else if (selector == @selector(removeButton))
4458 return @"removeButton";
4459 else if (selector == @selector(saveConfig))
4460 return @"saveConfig";
4461 else if (selector == @selector(setMetadataValue::))
4462 return @"setMetadataValue";
4463 else if (selector == @selector(setSessionValue::))
4464 return @"setSessionValue";
4465 else if (selector == @selector(substitutePackageNames:))
4466 return @"substitutePackageNames";
4467 else if (selector == @selector(scrollToBottom:))
4468 return @"scrollToBottom";
4469 else if (selector == @selector(setAllowsNavigationAction:))
4470 return @"setAllowsNavigationAction";
4471 else if (selector == @selector(setBadgeValue:))
4472 return @"setBadgeValue";
4473 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4474 return @"setButtonImage";
4475 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4476 return @"setButtonTitle";
4477 else if (selector == @selector(setHidesBackButton:))
4478 return @"setHidesBackButton";
4479 else if (selector == @selector(setHidesNavigationBar:))
4480 return @"setHidesNavigationBar";
4481 else if (selector == @selector(setNavigationBarStyle:))
4482 return @"setNavigationBarStyle";
4483 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4484 return @"setNavigationBarTintColor";
4485 else if (selector == @selector(setPasteboardString:))
4486 return @"setPasteboardString";
4487 else if (selector == @selector(setPasteboardURL:))
4488 return @"setPasteboardURL";
4489 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4490 return @"setScrollAlwaysBounceVertical";
4491 else if (selector == @selector(setScrollIndicatorStyle:))
4492 return @"setScrollIndicatorStyle";
4493 else if (selector == @selector(setToken:))
4495 else if (selector == @selector(setViewportWidth:))
4496 return @"setViewportWidth";
4497 else if (selector == @selector(statfs:))
4499 else if (selector == @selector(supports:))
4501 else if (selector == @selector(unload))
4507 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4508 return [self webScriptNameForSelector:selector] == nil;
4511 - (BOOL) supports:(NSString *)feature {
4512 return [feature isEqualToString:@"window.open"];
4516 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4519 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4520 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4523 - (void) setScrollIndicatorStyle:(NSString *)style {
4524 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4527 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4528 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4531 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4533 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4534 return (id) [NSNull null];
4535 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4537 return (id) [NSNull null];
4538 return [info objectForKey:key];
4541 - (NSNumber *) getKernelNumber:(NSString *)name {
4542 const char *string([name UTF8String]);
4545 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4546 return (id) [NSNull null];
4548 if (size != sizeof(int))
4549 return (id) [NSNull null];
4552 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4553 return (id) [NSNull null];
4555 return [NSNumber numberWithInt:value];
4558 - (NSString *) getKernelString:(NSString *)name {
4559 const char *string([name UTF8String]);
4562 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4563 return (id) [NSNull null];
4565 char value[size + 1];
4566 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4567 return (id) [NSNull null];
4569 // XXX: just in case you request something ludicrous
4572 return [NSString stringWithCString:value];
4575 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4576 NSObject *value(CYIOGetValue([path UTF8String], entry));
4579 if ([value isKindOfClass:[NSData class]])
4580 value = CYHex((NSData *) value);
4585 - (NSArray *) getMetadataKeys {
4586 @synchronized (Values_) {
4587 return [Values_ allKeys];
4590 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4591 WebFrame *frame([iframe contentFrame]);
4592 [indirect_ registerFrame:frame];
4595 - (id) getMetadataValue:(NSString *)key {
4596 @synchronized (Values_) {
4597 return [Values_ objectForKey:key];
4600 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4601 @synchronized (Values_) {
4602 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4603 [Values_ removeObjectForKey:key];
4605 [Values_ setObject:value forKey:key];
4607 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4610 - (id) getSessionValue:(NSString *)key {
4611 @synchronized (SessionData_) {
4612 return [SessionData_ objectForKey:key];
4615 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4616 @synchronized (SessionData_) {
4617 if (value == (id) [WebUndefined undefined])
4618 [SessionData_ removeObjectForKey:key];
4620 [SessionData_ setObject:value forKey:key];
4623 - (void) addBridgedHost:(NSString *)host {
4624 @synchronized (HostConfig_) {
4625 [BridgedHosts_ addObject:host];
4628 - (void) addInsecureHost:(NSString *)host {
4629 @synchronized (HostConfig_) {
4630 [InsecureHosts_ addObject:host];
4633 - (void) addTokenHost:(NSString *)host {
4634 @synchronized (HostConfig_) {
4635 [TokenHosts_ addObject:host];
4638 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4639 @synchronized (HostConfig_) {
4640 if (scheme != (id) [WebUndefined undefined])
4641 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4643 [PipelinedHosts_ addObject:host];
4646 - (void) popViewController:(NSNumber *)value {
4647 if (value == (id) [WebUndefined undefined])
4648 value = [NSNumber numberWithBool:YES];
4649 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4652 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4653 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4655 for (NSString *section in sections)
4656 [array addObject:section];
4658 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4661 distribution, @"Distribution",
4663 nil] waitUntilDone:NO];
4666 - (void) addTrivialSource:(NSString *)href {
4667 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4670 - (void) refreshSources {
4671 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4674 - (void) saveConfig {
4675 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4678 - (NSArray *) getAllSources {
4679 return [[Database sharedInstance] sources];
4682 - (NSArray *) getInstalledPackages {
4683 Database *database([Database sharedInstance]);
4684 @synchronized (database) {
4685 NSArray *packages([database packages]);
4686 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4687 for (Package *package in packages)
4688 if (![package uninstalled])
4689 [installed addObject:package];
4693 - (Package *) getPackageById:(NSString *)id {
4694 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4698 return (Package *) [NSNull null];
4701 - (NSString *) getLocaleIdentifier {
4702 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4705 - (NSArray *) getPreferredLanguages {
4709 - (NSArray *) statfs:(NSString *)path {
4712 if (path == nil || statfs([path UTF8String], &stat) == -1)
4715 return [NSArray arrayWithObjects:
4716 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4717 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4718 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4722 - (NSNumber *) du:(NSString *)path {
4723 NSNumber *value(nil);
4726 _assert(pipe(fds) != -1);
4728 pid_t pid(ExecFork());
4730 _assert(dup2(fds[1], 1) != -1);
4731 _assert(close(fds[0]) != -1);
4732 _assert(close(fds[1]) != -1);
4733 /* XXX: this should probably not use du */
4734 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4737 _assert(close(fds[1]) != -1);
4739 if (FILE *du = fdopen(fds[0], "r")) {
4741 while (fgets(line, sizeof(line), du) != NULL) {
4742 size_t length(strlen(line));
4743 while (length != 0 && line[length - 1] == '\n')
4744 line[--length] = '\0';
4745 if (char *tab = strchr(line, '\t')) {
4747 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4753 _assert(close(fds[0]) != -1);
4760 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4763 - (NSNumber *) isReachable:(NSString *)name {
4764 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4767 - (void) installPackages:(NSArray *)packages {
4768 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4771 - (NSString *) substitutePackageNames:(NSString *)message {
4772 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4773 for (size_t i(0), e([words count]); i != e; ++i) {
4774 NSString *word([words objectAtIndex:i]);
4775 if (Package *package = [[Database sharedInstance] packageWithName:word])
4776 [words replaceObjectAtIndex:i withObject:[package name]];
4779 return [words componentsJoinedByString:@" "];
4782 - (void) removeButton {
4783 [indirect_ removeButton];
4786 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4787 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4790 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4791 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4794 - (void) setBadgeValue:(id)value {
4795 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4798 - (void) setAllowsNavigationAction:(NSString *)value {
4799 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4802 - (void) setHidesBackButton:(NSString *)value {
4803 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4806 - (void) setHidesNavigationBar:(NSString *)value {
4807 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4810 - (void) setNavigationBarStyle:(NSString *)value {
4811 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4814 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4815 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4816 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4817 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4820 - (void) setPasteboardString:(NSString *)value {
4821 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4824 - (void) setPasteboardURL:(NSString *)value {
4825 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4828 - (void) _setToken:(NSString *)token {
4832 [Metadata_ removeObjectForKey:@"Token"];
4834 [Metadata_ setObject:Token_ forKey:@"Token"];
4839 - (void) setToken:(NSString *)token {
4840 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4843 - (void) scrollToBottom:(NSNumber *)animated {
4844 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4847 - (void) setViewportWidth:(float)width {
4848 [indirect_ setViewportWidthOnMainThread:width];
4851 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4852 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4853 unsigned count([arguments count]);
4855 for (unsigned i(0); i != count; ++i)
4856 values[i] = [arguments objectAtIndex:i];
4857 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4860 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4861 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4863 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4865 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4871 @interface NSURL (CydiaSecure)
4874 @implementation NSURL (CydiaSecure)
4876 - (bool) isCydiaSecure {
4877 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4880 @synchronized (HostConfig_) {
4881 if ([InsecureHosts_ containsObject:[self host]])
4890 /* Cydia Browser Controller {{{ */
4891 @implementation CydiaWebViewController
4893 - (NSURL *) navigationURL {
4894 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4897 + (void) _initialize {
4898 [super _initialize];
4900 Diversions_ = [NSMutableSet setWithCapacity:0];
4903 + (void) addDiversion:(Diversion *)diversion {
4904 [Diversions_ addObject:diversion];
4907 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4908 [super webView:view didClearWindowObject:window forFrame:frame];
4909 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4912 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4913 WebDataSource *source([frame dataSource]);
4914 NSURLResponse *response([source response]);
4915 NSURL *url([response URL]);
4916 NSString *scheme([[url scheme] lowercaseString]);
4918 bool bridged(false);
4920 @synchronized (HostConfig_) {
4921 if ([scheme isEqualToString:@"file"])
4923 else if ([scheme isEqualToString:@"https"])
4924 if ([BridgedHosts_ containsObject:[url host]])
4929 [window setValue:cydia forKey:@"cydia"];
4932 - (void) _setupMail:(MFMailComposeViewController *)controller {
4933 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4935 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4936 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4939 - (NSURL *) URLWithURL:(NSURL *)url {
4940 return [Diversion divertURL:url];
4943 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4944 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4947 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4948 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4950 NSURL *url([copy URL]);
4951 NSString *href([url absoluteString]);
4952 NSString *host([url host]);
4954 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4955 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4956 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4957 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4960 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4961 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4963 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4967 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4968 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4969 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4970 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4975 @synchronized (HostConfig_) {
4976 bridged = [BridgedHosts_ containsObject:host];
4977 token = [TokenHosts_ containsObject:host];
4980 if ([url isCydiaSecure]) {
4982 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4983 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4985 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4986 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4993 - (void) setDelegate:(id)delegate {
4994 [super setDelegate:delegate];
4995 [cydia_ setDelegate:delegate];
4998 - (NSString *) applicationNameForUserAgent {
5003 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5004 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5010 @interface AppCacheController : CydiaWebViewController {
5015 @implementation AppCacheController
5017 - (void) didReceiveMemoryWarning {
5018 // XXX: this doesn't work
5021 - (bool) retainsNetworkActivityIndicator {
5029 @interface NSObject (CydiaScript)
5030 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5033 @implementation NSObject (CydiaScript)
5035 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5041 @implementation NSArray (CydiaScript)
5043 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5044 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5045 for (size_t i(0), e([self count]); i != e; ++i)
5046 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5052 @implementation NSDictionary (CydiaScript)
5054 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5055 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5057 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5064 /* Confirmation Controller {{{ */
5065 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5066 if (!iterator.end())
5067 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5068 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5070 pkgCache::PkgIterator package(dep.TargetPkg());
5073 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5080 @protocol ConfirmationControllerDelegate
5081 - (void) cancelAndClear:(bool)clear;
5082 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5086 @interface ConfirmationController : CydiaWebViewController {
5087 _transient Database *database_;
5089 _H<UIAlertView> essential_;
5091 _H<NSDictionary> changes_;
5092 _H<NSMutableArray> issues_;
5093 _H<NSDictionary> sizes_;
5098 - (id) initWithDatabase:(Database *)database;
5102 @implementation ConfirmationController
5106 RestartSubstrate_ = true;
5107 [delegate_ confirmWithNavigationController:[self navigationController]];
5110 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5111 NSString *context([alert context]);
5113 if ([context isEqualToString:@"remove"]) {
5114 if (button == [alert cancelButtonIndex])
5115 [self dismissModalViewControllerAnimated:YES];
5116 else if (button == [alert firstOtherButtonIndex]) {
5117 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5120 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5121 } else if ([context isEqualToString:@"unable"]) {
5122 [self dismissModalViewControllerAnimated:YES];
5123 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5125 [super alertView:alert clickedButtonAtIndex:button];
5129 - (void) _doContinue {
5130 [delegate_ cancelAndClear:NO];
5131 [self dismissModalViewControllerAnimated:YES];
5134 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5135 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5139 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5140 [super webView:view didClearWindowObject:window forFrame:frame];
5142 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5143 (id) changes_, @"changes",
5144 (id) issues_, @"issues",
5145 (id) sizes_, @"sizes",
5147 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5150 - (id) initWithDatabase:(Database *)database {
5151 if ((self = [super init]) != nil) {
5152 database_ = database;
5154 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5155 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5156 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5157 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5158 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5162 pkgCacheFile &cache([database_ cache]);
5163 NSArray *packages([database_ packages]);
5164 pkgDepCache::Policy *policy([database_ policy]);
5166 issues_ = [NSMutableArray arrayWithCapacity:4];
5168 for (Package *package in packages) {
5169 pkgCache::PkgIterator iterator([package iterator]);
5170 NSString *name([package id]);
5172 if ([package broken]) {
5173 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5175 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5177 reasons, @"reasons",
5180 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5184 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5185 pkgCache::DepIterator start;
5186 pkgCache::DepIterator end;
5187 dep.GlobOr(start, end); // ++dep
5189 if (!cache->IsImportantDep(end))
5191 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5194 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5196 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5197 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5198 clauses, @"clauses",
5202 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5204 pkgCache::PkgIterator target(start.TargetPkg());
5205 if (target->ProvidesList != 0)
5206 reason = @"missing";
5208 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5210 reason = @"installed";
5211 installed = [NSString stringWithUTF8String:ver.VerStr()];
5212 } else if (!cache[target].CandidateVerIter(cache).end())
5213 reason = @"uninstalled";
5214 else if (target->ProvidesList == 0)
5215 reason = @"uninstallable";
5217 reason = @"virtual";
5220 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5221 [NSString stringWithUTF8String:start.CompType()], @"operator",
5222 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5225 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5226 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5227 version, @"version",
5229 installed, @"installed",
5232 // yes, seriously. (wtf?)
5240 pkgDepCache::StateCache &state(cache[iterator]);
5242 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5244 if (state.NewInstall())
5245 [installs addObject:name];
5246 // XXX: else if (state.Install())
5247 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5248 [reinstalls addObject:name];
5249 // XXX: move before previous if
5250 else if (state.Upgrade())
5251 [upgrades addObject:name];
5252 else if (state.Downgrade())
5253 [downgrades addObject:name];
5254 else if (!state.Delete())
5255 // XXX: _assert(state.Keep());
5257 else if (special_r(name))
5258 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5259 [NSNull null], @"package",
5260 [NSArray arrayWithObjects:
5261 [NSDictionary dictionaryWithObjectsAndKeys:
5262 @"Conflicts", @"relationship",
5263 [NSArray arrayWithObjects:
5264 [NSDictionary dictionaryWithObjectsAndKeys:
5266 [NSNull null], @"version",
5267 @"installed", @"reason",
5274 if ([package essential])
5276 [removes addObject:name];
5279 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5280 substrate_ |= DepSubstrate(iterator.CurrentVer());
5285 else if (Advanced_) {
5286 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5288 essential_ = [[[UIAlertView alloc]
5289 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5290 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5292 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5294 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5298 [essential_ setContext:@"remove"];
5299 [essential_ setNumberOfRows:2];
5301 essential_ = [[[UIAlertView alloc]
5302 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5303 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5305 cancelButtonTitle:UCLocalize("OKAY")
5306 otherButtonTitles:nil
5309 [essential_ setContext:@"unable"];
5312 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5313 installs, @"installs",
5314 reinstalls, @"reinstalls",
5315 upgrades, @"upgrades",
5316 downgrades, @"downgrades",
5317 removes, @"removes",
5320 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5321 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5322 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5325 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5329 - (UIBarButtonItem *) leftButton {
5330 return [[[UIBarButtonItem alloc]
5331 initWithTitle:UCLocalize("CANCEL")
5332 style:UIBarButtonItemStylePlain
5334 action:@selector(cancelButtonClicked)
5339 - (void) applyRightButton {
5340 if ([issues_ count] == 0 && ![self isLoading])
5341 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5342 initWithTitle:UCLocalize("CONFIRM")
5343 style:UIBarButtonItemStyleDone
5345 action:@selector(confirmButtonClicked)
5348 [[self navigationItem] setRightBarButtonItem:nil];
5352 - (void) cancelButtonClicked {
5353 [delegate_ cancelAndClear:YES];
5354 [self dismissModalViewControllerAnimated:YES];
5358 - (void) confirmButtonClicked {
5359 if (essential_ != nil)
5369 /* Progress Data {{{ */
5370 @interface CydiaProgressData : NSObject {
5371 _transient id delegate_;
5380 _H<NSMutableArray> events_;
5381 _H<NSString> title_;
5383 _H<NSString> status_;
5384 _H<NSString> finish_;
5389 @implementation CydiaProgressData
5391 + (NSArray *) _attributeKeys {
5392 return [NSArray arrayWithObjects:
5404 - (NSArray *) attributeKeys {
5405 return [[self class] _attributeKeys];
5408 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5409 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5413 if ((self = [super init]) != nil) {
5414 events_ = [NSMutableArray arrayWithCapacity:32];
5422 - (void) setDelegate:(id)delegate {
5423 delegate_ = delegate;
5426 - (void) setPercent:(float)value {
5430 - (NSNumber *) percent {
5431 return [NSNumber numberWithFloat:percent_];
5434 - (void) setCurrent:(float)value {
5438 - (NSNumber *) current {
5439 return [NSNumber numberWithFloat:current_];
5442 - (void) setTotal:(float)value {
5446 - (NSNumber *) total {
5447 return [NSNumber numberWithFloat:total_];
5450 - (void) setSpeed:(float)value {
5454 - (NSNumber *) speed {
5455 return [NSNumber numberWithFloat:speed_];
5458 - (NSArray *) events {
5462 - (void) removeAllEvents {
5463 [events_ removeAllObjects];
5466 - (void) addEvent:(CydiaProgressEvent *)event {
5467 [events_ addObject:event];
5470 - (void) setTitle:(NSString *)text {
5474 - (NSString *) title {
5478 - (void) setFinish:(NSString *)text {
5482 - (NSString *) finish {
5483 return (id) finish_ ?: [NSNull null];
5486 - (void) setRunning:(bool)running {
5490 - (NSNumber *) running {
5491 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5496 /* Progress Controller {{{ */
5497 @interface ProgressController : CydiaWebViewController <
5500 _transient Database *database_;
5501 _H<CydiaProgressData, 1> progress_;
5505 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5507 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5509 - (void) setTitle:(NSString *)title;
5510 - (void) setCancellable:(bool)cancellable;
5514 @implementation ProgressController
5517 [database_ setProgressDelegate:nil];
5521 - (UIBarButtonItem *) leftButton {
5522 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5523 initWithTitle:UCLocalize("CANCEL")
5524 style:UIBarButtonItemStylePlain
5526 action:@selector(cancel)
5527 ] autorelease] : nil;
5530 - (void) updateCancel {
5531 [super applyLeftButton];
5534 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5535 if ((self = [super init]) != nil) {
5536 database_ = database;
5537 delegate_ = delegate;
5539 [database_ setProgressDelegate:self];
5541 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5542 [progress_ setDelegate:self];
5544 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5546 [scroller_ setBackgroundColor:[UIColor blackColor]];
5548 [[self navigationItem] setHidesBackButton:YES];
5550 [self updateCancel];
5554 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5555 [super webView:view didClearWindowObject:window forFrame:frame];
5556 [window setValue:progress_ forKey:@"cydiaProgress"];
5559 - (void) updateProgress {
5560 [self dispatchEvent:@"CydiaProgressUpdate"];
5563 - (void) viewWillAppear:(BOOL)animated {
5564 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5565 [super viewWillAppear:animated];
5568 - (void) reloadSpringBoard {
5569 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5570 system("/bin/launchctl stop com.apple.backboardd");
5572 system("/usr/bin/killall backboardd SpringBoard sbreload");
5576 pid_t pid(ExecFork());
5581 pid_t pid(ExecFork());
5583 execl("/usr/bin/sbreload", "sbreload", NULL);
5593 system("/usr/bin/killall backboardd SpringBoard sbreload");
5597 UpdateExternalStatus(0);
5600 [delegate_ saveState];
5604 [delegate_ returnToCydia];
5608 [delegate_ terminateWithSuccess];
5609 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5610 [delegate_ suspendWithAnimation:YES];
5612 [delegate_ suspend];*/
5624 UIProgressHUD *hud([delegate_ addProgressHUD]);
5625 [hud setText:UCLocalize("LOADING")];
5626 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5632 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5633 SBReboot(SBSSpringBoardServerPort());
5635 reboot2(RB_AUTOBOOT);
5642 - (void) setTitle:(NSString *)title {
5643 [progress_ setTitle:title];
5644 [self updateProgress];
5647 - (UIBarButtonItem *) rightButton {
5648 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5649 initWithTitle:UCLocalize("CLOSE")
5650 style:UIBarButtonItemStylePlain
5652 action:@selector(close)
5656 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5657 UpdateExternalStatus(1);
5659 [progress_ setRunning:true];
5660 [self setTitle:title];
5661 // implicit updateProgress
5663 SHA1SumValue notifyconf; {
5665 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5668 MMap mmap(file, MMap::ReadOnly);
5670 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5671 notifyconf = sha1.Result();
5675 SHA1SumValue springlist; {
5677 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5680 MMap mmap(file, MMap::ReadOnly);
5682 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5683 springlist = sha1.Result();
5687 if (invocation != nil) {
5688 [invocation yieldToSelector:@selector(invoke)];
5689 [self setTitle:@"COMPLETE"];
5694 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5697 MMap mmap(file, MMap::ReadOnly);
5699 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5700 if (!(notifyconf == sha1.Result()))
5707 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5710 MMap mmap(file, MMap::ReadOnly);
5712 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5713 if (!(springlist == sha1.Result()))
5719 if (RestartSubstrate_)
5723 RestartSubstrate_ = false;
5726 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5727 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5728 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5729 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5730 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5733 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5735 [progress_ setRunning:false];
5736 [self updateProgress];
5738 [self applyRightButton];
5741 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5742 [progress_ addEvent:event];
5743 [self updateProgress];
5746 - (bool) isProgressCancelled {
5747 return cancel_ == 2;
5752 [self updateCancel];
5755 - (void) setCancellable:(bool)cancellable {
5756 unsigned cancel(cancel_);
5760 else if (cancel_ == 0)
5763 if (cancel != cancel_)
5764 [self updateCancel];
5767 - (void) setProgressCancellable:(NSNumber *)cancellable {
5768 [self setCancellable:[cancellable boolValue]];
5771 - (void) setProgressPercent:(NSNumber *)percent {
5772 [progress_ setPercent:[percent floatValue]];
5773 [self updateProgress];
5776 - (void) setProgressStatus:(NSDictionary *)status {
5777 if (status == nil) {
5778 [progress_ setCurrent:0];
5779 [progress_ setTotal:0];
5780 [progress_ setSpeed:0];
5782 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5784 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5785 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5786 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5789 [self updateProgress];
5795 /* Package Cell {{{ */
5796 @interface PackageCell : CyteTableViewCell <
5797 CyteTableViewCellDelegate
5801 _H<NSString> description_;
5803 _H<NSString> source_;
5805 _H<UIImage> placard_;
5809 - (PackageCell *) init;
5810 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5812 - (void) drawContentRect:(CGRect)rect;
5816 @implementation PackageCell
5818 - (PackageCell *) init {
5819 CGRect frame(CGRectMake(0, 0, 320, 74));
5820 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5821 UIView *content([self contentView]);
5822 CGRect bounds([content bounds]);
5824 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5825 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5826 [content addSubview:content_];
5828 [content_ setDelegate:self];
5829 [content_ setOpaque:YES];
5833 - (NSString *) accessibilityLabel {
5837 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5838 summarized_ = summary;
5848 [content_ setBackgroundColor:[UIColor whiteColor]];
5852 Source *source = [package source];
5854 icon_ = [package icon];
5856 if (NSString *name = [package name])
5857 name_ = [NSString stringWithString:name];
5859 if (NSString *description = [package shortDescription])
5860 description_ = [NSString stringWithString:description];
5862 commercial_ = [package isCommercial];
5864 NSString *label = nil;
5865 bool trusted = false;
5867 if (source != nil) {
5868 label = [source label];
5869 trusted = [source trusted];
5870 } else if ([[package id] isEqualToString:@"firmware"])
5871 label = UCLocalize("APPLE");
5873 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5875 NSString *from(label);
5877 NSString *section = [package simpleSection];
5878 if (section != nil && ![section isEqualToString:label]) {
5879 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5880 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5883 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5885 if (NSString *purpose = [package primaryPurpose])
5886 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5891 if (NSString *mode = [package mode]) {
5892 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5893 color = RemovingColor_;
5894 placard = @"removing";
5896 color = InstallingColor_;
5897 placard = @"installing";
5900 color = [UIColor whiteColor];
5902 if ([package installed] != nil)
5903 placard = @"installed";
5908 [content_ setBackgroundColor:color];
5911 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5914 [self setNeedsDisplay];
5915 [content_ setNeedsDisplay];
5918 - (void) drawSummaryContentRect:(CGRect)rect {
5919 bool highlighted(highlighted_);
5920 float width([self bounds].size.width);
5924 rect.size = [(UIImage *) icon_ size];
5926 while (rect.size.width > 16 || rect.size.height > 16) {
5927 rect.size.width /= 2;
5928 rect.size.height /= 2;
5931 rect.origin.x = 19 - rect.size.width / 2;
5932 rect.origin.y = 19 - rect.size.height / 2;
5934 [icon_ drawInRect:Retina(rect)];
5937 if (badge_ != nil) {
5939 rect.size = [(UIImage *) badge_ size];
5941 rect.size.width /= 4;
5942 rect.size.height /= 4;
5944 rect.origin.x = 25 - rect.size.width / 2;
5945 rect.origin.y = 25 - rect.size.height / 2;
5947 [badge_ drawInRect:Retina(rect)];
5950 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5954 UISetColor(commercial_ ? Purple_ : Black_);
5955 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5957 if (placard_ != nil)
5958 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5961 - (void) drawNormalContentRect:(CGRect)rect {
5962 bool highlighted(highlighted_);
5963 float width([self bounds].size.width);
5967 rect.size = [(UIImage *) icon_ size];
5969 while (rect.size.width > 32 || rect.size.height > 32) {
5970 rect.size.width /= 2;
5971 rect.size.height /= 2;
5974 rect.origin.x = 25 - rect.size.width / 2;
5975 rect.origin.y = 25 - rect.size.height / 2;
5977 [icon_ drawInRect:Retina(rect)];
5980 if (badge_ != nil) {
5982 rect.size = [(UIImage *) badge_ size];
5984 rect.size.width /= 2;
5985 rect.size.height /= 2;
5987 rect.origin.x = 36 - rect.size.width / 2;
5988 rect.origin.y = 36 - rect.size.height / 2;
5990 [badge_ drawInRect:Retina(rect)];
5993 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5997 UISetColor(commercial_ ? Purple_ : Black_);
5998 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5999 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6002 UISetColor(commercial_ ? Purplish_ : Gray_);
6003 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6005 if (placard_ != nil)
6006 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6009 - (void) drawContentRect:(CGRect)rect {
6011 [self drawSummaryContentRect:rect];
6013 [self drawNormalContentRect:rect];
6018 /* Section Cell {{{ */
6019 @interface SectionCell : CyteTableViewCell <
6020 CyteTableViewCellDelegate
6022 _H<NSString> basic_;
6023 _H<NSString> section_;
6025 _H<NSString> count_;
6027 _H<UISwitch> switch_;
6031 - (void) setSection:(Section *)section editing:(BOOL)editing;
6035 @implementation SectionCell
6037 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6038 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6039 icon_ = [UIImage imageNamed:@"folder.png"];
6040 // XXX: this initial frame is wrong, but is fixed later
6041 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6042 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6044 UIView *content([self contentView]);
6045 CGRect bounds([content bounds]);
6047 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6048 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6049 [content addSubview:content_];
6050 [content_ setBackgroundColor:[UIColor whiteColor]];
6052 [content_ setDelegate:self];
6056 - (void) onSwitch:(id)sender {
6057 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6058 if (metadata == nil) {
6059 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6060 [Sections_ setObject:metadata forKey:basic_];
6063 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6067 - (void) setSection:(Section *)section editing:(BOOL)editing {
6068 if (editing != editing_) {
6070 [switch_ removeFromSuperview];
6072 [self addSubview:switch_];
6081 if (section == nil) {
6082 name_ = UCLocalize("ALL_PACKAGES");
6085 basic_ = [section name];
6086 section_ = [section localized];
6088 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6089 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6092 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6095 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6096 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6098 [content_ setNeedsDisplay];
6101 - (void) setFrame:(CGRect)frame {
6102 [super setFrame:frame];
6104 CGRect rect([switch_ frame]);
6105 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6108 - (NSString *) accessibilityLabel {
6112 - (void) drawContentRect:(CGRect)rect {
6113 bool highlighted(highlighted_ && !editing_);
6115 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6117 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6120 float width(rect.size.width);
6122 width -= 9 + [switch_ frame].size.width;
6126 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6128 CGSize size = [count_ sizeWithFont:Font14_];
6130 UISetColor(Folder_);
6132 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6138 /* File Table {{{ */
6139 @interface FileTable : CyteViewController <
6140 UITableViewDataSource,
6143 _transient Database *database_;
6144 _H<Package> package_;
6146 _H<NSMutableArray> files_;
6147 _H<UITableView, 2> list_;
6150 - (id) initWithDatabase:(Database *)database;
6151 - (void) setPackage:(Package *)package;
6155 @implementation FileTable
6157 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6158 return files_ == nil ? 0 : [files_ count];
6161 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6165 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6166 static NSString *reuseIdentifier = @"Cell";
6168 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6170 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6171 [cell setFont:[UIFont systemFontOfSize:16]];
6173 [cell setText:[files_ objectAtIndex:indexPath.row]];
6174 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6179 - (NSURL *) navigationURL {
6180 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6184 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6185 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6186 [list_ setRowHeight:24.0f];
6187 [(UITableView *) list_ setDataSource:self];
6188 [list_ setDelegate:self];
6189 [self setView:list_];
6192 - (void) viewDidLoad {
6193 [super viewDidLoad];
6195 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6198 - (void) releaseSubviews {
6204 [super releaseSubviews];
6207 - (id) initWithDatabase:(Database *)database {
6208 if ((self = [super init]) != nil) {
6209 database_ = database;
6213 - (void) setPackage:(Package *)package {
6217 files_ = [NSMutableArray arrayWithCapacity:32];
6219 if (package != nil) {
6221 name_ = [package id];
6223 if (NSArray *files = [package files])
6224 [files_ addObjectsFromArray:files];
6226 if ([files_ count] != 0) {
6227 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6228 [files_ removeObjectAtIndex:0];
6229 [files_ sortUsingSelector:@selector(compareByPath:)];
6231 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6232 [stack addObject:@"/"];
6234 for (int i(0), e([files_ count]); i != e; ++i) {
6235 NSString *file = [files_ objectAtIndex:i];
6236 while (![file hasPrefix:[stack lastObject]])
6237 [stack removeLastObject];
6238 NSString *directory = [stack lastObject];
6239 [stack addObject:[file stringByAppendingString:@"/"]];
6240 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6241 ([stack count] - 2) * 3, "",
6242 [file substringFromIndex:[directory length]]
6251 - (void) reloadData {
6254 [self setPackage:[database_ packageWithName:name_]];
6259 /* Package Controller {{{ */
6260 @interface CYPackageController : CydiaWebViewController <
6261 UIActionSheetDelegate
6263 _transient Database *database_;
6264 _H<Package> package_;
6267 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6268 _H<UIBarButtonItem> button_;
6271 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6275 @implementation CYPackageController
6277 - (NSURL *) navigationURL {
6278 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6281 - (void) _clickButtonWithName:(NSString *)name {
6282 if ([name isEqualToString:@"CLEAR"])
6283 [delegate_ clearPackage:package_];
6284 else if ([name isEqualToString:@"INSTALL"])
6285 [delegate_ installPackage:package_];
6286 else if ([name isEqualToString:@"REINSTALL"])
6287 [delegate_ installPackage:package_];
6288 else if ([name isEqualToString:@"REMOVE"])
6289 [delegate_ removePackage:package_];
6290 else if ([name isEqualToString:@"UPGRADE"])
6291 [delegate_ installPackage:package_];
6292 else _assert(false);
6295 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6296 NSString *context([sheet context]);
6298 if ([context isEqualToString:@"modify"]) {
6299 if (button != [sheet cancelButtonIndex]) {
6300 [self _clickButtonWithName:buttons_[button].first];
6303 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6307 - (bool) _allowJavaScriptPanel {
6312 - (void) _customButtonClicked {
6313 size_t count(buttons_.size());
6318 [self _clickButtonWithName:buttons_[0].first];
6320 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6321 for (const auto &button : buttons_)
6322 [buttons addObject:button.second];
6324 UIActionSheet *sheet = [[[UIActionSheet alloc]
6327 cancelButtonTitle:nil
6328 destructiveButtonTitle:nil
6329 otherButtonTitles:nil
6332 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6334 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6335 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6337 [sheet setContext:@"modify"];
6339 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6343 - (void) reloadButtonClicked {
6344 if (commercial_ && function_ == nil && [package_ uninstalled])
6346 [self customButtonClicked];
6349 - (void) applyLoadingTitle {
6350 // Don't show "Loading" as the title. Ever.
6353 - (UIBarButtonItem *) rightButton {
6358 - (void) setPageColor:(UIColor *)color {
6359 return [super setPageColor:nil];
6362 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6363 if ((self = [super init]) != nil) {
6364 database_ = database;
6365 name_ = name == nil ? @"" : [NSString stringWithString:name];
6366 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6370 - (void) reloadData {
6373 package_ = [database_ packageWithName:name_];
6377 if (package_ != nil) {
6378 [(Package *) package_ parse];
6380 commercial_ = [package_ isCommercial];
6382 if ([package_ mode] != nil)
6383 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6384 if ([package_ source] == nil);
6385 else if ([package_ upgradableAndEssential:NO])
6386 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6387 else if ([package_ uninstalled])
6388 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6390 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6391 if (![package_ uninstalled])
6392 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6396 switch (buttons_.size()) {
6397 case 0: title = nil; break;
6398 case 1: title = buttons_[0].second; break;
6399 default: title = UCLocalize("MODIFY"); break;
6402 button_ = [[[UIBarButtonItem alloc]
6404 style:UIBarButtonItemStylePlain
6406 action:@selector(customButtonClicked)
6410 - (bool) isLoading {
6411 return commercial_ ? [super isLoading] : false;
6417 /* Package List Controller {{{ */
6418 @interface PackageListController : CyteViewController <
6419 UITableViewDataSource,
6422 _transient Database *database_;
6424 _H<NSArray> packages_;
6425 _H<NSArray> sections_;
6426 _H<UITableView, 2> list_;
6428 _H<NSArray> thumbs_;
6429 std::vector<NSInteger> offset_;
6431 _H<NSString> title_;
6432 unsigned reloading_;
6435 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6436 - (void) setDelegate:(id)delegate;
6437 - (void) resetCursor;
6440 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6444 @implementation PackageListController
6446 - (NSURL *) referrerURL {
6447 return [self navigationURL];
6450 - (bool) isSummarized {
6454 - (bool) showsSections {
6458 - (void) deselectWithAnimation:(BOOL)animated {
6459 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6462 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6463 CGRect base = [[self view] bounds];
6464 base.size.height -= bounds.size.height;
6465 base.origin = [list_ frame].origin;
6467 [UIView beginAnimations:nil context:NULL];
6468 [UIView setAnimationBeginsFromCurrentState:YES];
6469 [UIView setAnimationCurve:curve];
6470 [UIView setAnimationDuration:duration];
6471 [list_ setFrame:base];
6472 [UIView commitAnimations];
6475 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6476 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6479 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6480 [self resizeForKeyboardBounds:bounds duration:0];
6483 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6484 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6485 *curve = UIViewAnimationCurveEaseInOut;
6487 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6489 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6492 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6495 - (void) keyboardWillShow:(NSNotification *)notification {
6498 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6499 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6501 NSTimeInterval duration;
6502 UIViewAnimationCurve curve;
6503 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6505 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6506 UIViewController *base = self;
6507 while ([base parentOrPresentingViewController] != nil)
6508 base = [base parentOrPresentingViewController];
6509 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6510 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6512 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6513 intersection.size.height += CYStatusBarHeight();
6515 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6518 - (void) keyboardWillHide:(NSNotification *)notification {
6519 NSTimeInterval duration;
6520 UIViewAnimationCurve curve;
6521 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6523 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6526 - (void) viewWillAppear:(BOOL)animated {
6527 [super viewWillAppear:animated];
6529 [self resizeForKeyboardBounds:CGRectZero];
6530 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6531 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6534 - (void) viewWillDisappear:(BOOL)animated {
6535 [super viewWillDisappear:animated];
6537 [self resizeForKeyboardBounds:CGRectZero];
6538 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6539 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6542 - (void) viewDidAppear:(BOOL)animated {
6543 [super viewDidAppear:animated];
6544 [self deselectWithAnimation:animated];
6547 - (void) didSelectPackage:(Package *)package {
6548 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6549 [view setDelegate:delegate_];
6550 [[self navigationController] pushViewController:view animated:YES];
6553 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6554 NSInteger count([sections_ count]);
6555 return count == 0 ? 1 : count;
6558 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6559 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6561 return [[sections_ objectAtIndex:section] name];
6564 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6565 if ([sections_ count] == 0)
6567 return [[sections_ objectAtIndex:section] count];
6570 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6571 @synchronized (database_) {
6572 if ([database_ era] != era_)
6575 Section *section([sections_ objectAtIndex:[path section]]);
6576 NSInteger row([path row]);
6577 Package *package([packages_ objectAtIndex:([section row] + row)]);
6578 return [[package retain] autorelease];
6581 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6582 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6584 cell = [[[PackageCell alloc] init] autorelease];
6586 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6587 [cell setPackage:package asSummary:[self isSummarized]];
6591 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6592 Package *package([self packageAtIndexPath:path]);
6593 package = [database_ packageWithName:[package id]];
6594 [self didSelectPackage:package];
6597 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6601 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6602 return offset_[index];
6605 - (void) updateHeight {
6606 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6609 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6610 if ((self = [super init]) != nil) {
6611 database_ = database;
6612 title_ = [title copy];
6613 [[self navigationItem] setTitle:title_];
6618 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6619 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6620 [self setView:view];
6622 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6623 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6624 [view addSubview:list_];
6626 // XXX: is 20 the most optimal number here?
6627 [list_ setSectionIndexMinimumDisplayRowCount:20];
6629 [(UITableView *) list_ setDataSource:self];
6630 [list_ setDelegate:self];
6632 [self updateHeight];
6635 - (void) releaseSubviews {
6644 [super releaseSubviews];
6647 - (void) setDelegate:(id)delegate {
6648 delegate_ = delegate;
6651 - (bool) shouldYield {
6655 - (bool) shouldBlock {
6659 - (NSMutableArray *) _reloadPackages {
6660 @synchronized (database_) {
6661 era_ = [database_ era];
6662 NSArray *packages([database_ packages]);
6664 return [NSMutableArray arrayWithArray:packages];
6667 - (void) _reloadData {
6668 if (reloading_ != 0) {
6673 NSMutableArray *packages;
6676 if ([self shouldYield]) {
6680 if (![self shouldBlock])
6683 hud = [delegate_ addProgressHUD];
6684 [hud setText:UCLocalize("LOADING")];
6688 packages = [self yieldToSelector:@selector(_reloadPackages)];
6691 [delegate_ removeProgressHUD:hud];
6692 } while (reloading_ == 2);
6694 packages = [self _reloadPackages];
6697 @synchronized (database_) {
6698 if (era_ != [database_ era])
6705 packages_ = packages;
6707 if ([self showsSections])
6708 sections_ = [self sectionsForPackages:packages];
6710 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6711 [section setCount:[packages_ count]];
6712 sections_ = [NSArray arrayWithObject:section];
6715 [self updateHeight];
6717 _profile(PackageTable$reloadData$List)
6718 [(UITableView *) list_ setDataSource:self];
6726 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6727 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6728 size_t end([packages count]);
6730 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6731 Section *section(prefix);
6733 thumbs_ = CollationThumbs_;
6734 offset_ = CollationOffset_;
6737 size_t offsets([CollationStarts_ count]);
6739 NSString *start([CollationStarts_ objectAtIndex:offset]);
6740 size_t length([start length]);
6742 for (size_t index(0); index != end; ++index) {
6744 Package *package([packages objectAtIndex:index]);
6745 NSString *name(PackageName(package, @selector(cyname)));
6747 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6748 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6749 NSString *title([CollationTitles_ objectAtIndex:offset]);
6750 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6751 [sections addObject:section];
6753 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6756 length = [start length];
6760 [section addToCount];
6763 for (; offset != offsets; ++offset) {
6764 NSString *title([CollationTitles_ objectAtIndex:offset]);
6765 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6766 [sections addObject:section];
6769 if ([prefix count] != 0) {
6770 Section *suffix([sections lastObject]);
6771 [prefix setName:[suffix name]];
6772 [suffix setName:nil];
6773 [sections insertObject:prefix atIndex:(offsets - 1)];
6779 - (void) reloadData {
6782 if ([self shouldYield])
6783 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6788 - (void) resetCursor {
6789 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6792 - (void) clearData {
6793 [self updateHeight];
6795 [list_ setDataSource:nil];
6803 /* Filtered Package List Controller {{{ */
6804 typedef Function<bool, Package *> PackageFilter;
6805 typedef Function<void, NSMutableArray *> PackageSorter;
6806 @interface FilteredPackageListController : PackageListController {
6807 PackageFilter filter_;
6808 PackageSorter sorter_;
6811 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6813 - (void) setFilter:(PackageFilter)filter;
6814 - (void) setSorter:(PackageSorter)sorter;
6818 @implementation FilteredPackageListController
6820 - (void) setFilter:(PackageFilter)filter {
6821 @synchronized (self) {
6825 - (void) setSorter:(PackageSorter)sorter {
6826 @synchronized (self) {
6830 - (NSMutableArray *) _reloadPackages {
6831 @synchronized (database_) {
6832 era_ = [database_ era];
6834 NSArray *packages([database_ packages]);
6835 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6837 PackageFilter filter;
6838 PackageSorter sorter;
6840 @synchronized (self) {
6845 _profile(PackageTable$reloadData$Filter)
6846 for (Package *package in packages)
6847 if ([package valid] && filter(package))
6848 [filtered addObject:package];
6856 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6857 if ((self = [super initWithDatabase:database title:title]) != nil) {
6858 [self setFilter:filter];
6865 /* Home Controller {{{ */
6866 @interface HomeController : CydiaWebViewController {
6867 CFRunLoopRef runloop_;
6868 SCNetworkReachabilityRef reachability_;
6873 @implementation HomeController
6875 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6876 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6880 if ((self = [super init]) != nil) {
6881 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6884 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6885 if (reachability_ != NULL) {
6886 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6887 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6889 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6890 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6897 if (reachability_ != NULL && runloop_ != NULL)
6898 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6902 - (NSURL *) navigationURL {
6903 return [NSURL URLWithString:@"cydia://home"];
6906 - (void) aboutButtonClicked {
6907 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6909 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6910 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6911 [alert setCancelButtonIndex:0];
6914 @"Copyright \u00a9 2008-2014\n"
6917 "Jay Freeman (saurik)\n"
6918 "saurik@saurik.com\n"
6919 "http://www.saurik.com/"
6925 - (UIBarButtonItem *) leftButton {
6926 return [[[UIBarButtonItem alloc]
6927 initWithTitle:UCLocalize("ABOUT")
6928 style:UIBarButtonItemStylePlain
6930 action:@selector(aboutButtonClicked)
6937 /* Cydia Navigation Controller Interface {{{ */
6938 @interface UINavigationController (Cydia)
6940 - (NSArray *) navigationURLCollection;
6941 - (void) unloadData;
6946 /* Cydia Tab Bar Controller {{{ */
6947 @interface CydiaTabBarController : CyteTabBarController <
6948 UITabBarControllerDelegate,
6951 _transient Database *database_;
6953 _H<UIActivityIndicatorView> indicator_;
6956 // XXX: ok, "updatedelegate_"?...
6957 _transient NSObject<CydiaDelegate> *updatedelegate_;
6960 - (NSArray *) navigationURLCollection;
6961 - (void) beginUpdate;
6966 @implementation CydiaTabBarController
6968 - (NSArray *) navigationURLCollection {
6969 NSMutableArray *items([NSMutableArray array]);
6971 // XXX: Should this deal with transient view controllers?
6972 for (id navigation in [self viewControllers]) {
6973 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6975 [items addObject:stack];
6981 - (id) initWithDatabase:(Database *)database {
6982 if ((self = [super init]) != nil) {
6983 database_ = database;
6984 [self setDelegate:self];
6986 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6987 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6989 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6993 - (void) setUpdate:(NSDate *)date {
6997 - (void) beginUpdate {
7001 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7002 UITabBarItem *item([controller tabBarItem]);
7004 [item setBadgeValue:@""];
7005 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7007 [indicator_ startAnimating];
7008 [badge addSubview:indicator_];
7010 [updatedelegate_ retainNetworkActivityIndicator];
7014 detachNewThreadSelector:@selector(performUpdate)
7020 - (void) performUpdate {
7021 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7023 SourceStatus status(self, database_);
7024 [database_ updateWithStatus:status];
7027 performSelectorOnMainThread:@selector(completeUpdate)
7035 - (void) stopUpdateWithSelector:(SEL)selector {
7037 [updatedelegate_ releaseNetworkActivityIndicator];
7039 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7040 [[controller tabBarItem] setBadgeValue:nil];
7042 [indicator_ removeFromSuperview];
7043 [indicator_ stopAnimating];
7045 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7048 - (void) completeUpdate {
7051 [self stopUpdateWithSelector:@selector(reloadData)];
7054 - (void) cancelUpdate {
7055 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7058 - (void) cancelPressed {
7059 [self cancelUpdate];
7066 - (bool) isSourceCancelled {
7070 - (void) startSourceFetch:(NSString *)uri {
7073 - (void) stopSourceFetch:(NSString *)uri {
7076 - (void) setUpdateDelegate:(id)delegate {
7077 updatedelegate_ = delegate;
7083 /* Cydia Navigation Controller Implementation {{{ */
7084 @implementation UINavigationController (Cydia)
7086 - (NSArray *) navigationURLCollection {
7087 NSMutableArray *stack([NSMutableArray array]);
7089 for (CyteViewController *controller in [self viewControllers]) {
7090 NSString *url = [[controller navigationURL] absoluteString];
7092 [stack addObject:url];
7098 - (void) reloadData {
7101 UIViewController *visible([self visibleViewController]);
7103 [visible reloadData];
7105 // on the iPad, this view controller is ALSO visible. :(
7107 if (UIViewController *top = [self topViewController])
7112 - (void) unloadData {
7113 for (CyteViewController *page in [self viewControllers])
7122 /* Cydia:// Protocol {{{ */
7123 @interface CydiaURLProtocol : NSURLProtocol {
7128 @implementation CydiaURLProtocol
7130 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7131 NSURL *url([request URL]);
7135 NSString *scheme([[url scheme] lowercaseString]);
7136 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7138 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7144 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7148 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7149 id<NSURLProtocolClient> client([self client]);
7151 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7153 NSData *data(UIImagePNGRepresentation(icon));
7155 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7156 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7157 [client URLProtocol:self didLoadData:data];
7158 [client URLProtocolDidFinishLoading:self];
7162 - (void) startLoading {
7163 id<NSURLProtocolClient> client([self client]);
7164 NSURLRequest *request([self request]);
7166 NSURL *url([request URL]);
7167 NSString *href([url absoluteString]);
7168 NSString *scheme([[url scheme] lowercaseString]);
7172 if ([scheme isEqualToString:@"cydia"])
7173 path = [href substringFromIndex:8];
7174 else if ([scheme isEqualToString:@"about"])
7175 path = [href substringFromIndex:12];
7176 else _assert(false);
7178 NSRange slash([path rangeOfString:@"/"]);
7181 if (slash.location == NSNotFound) {
7185 command = [path substringToIndex:slash.location];
7186 path = [path substringFromIndex:(slash.location + 1)];
7189 Database *database([Database sharedInstance]);
7191 if ([command isEqualToString:@"package-icon"]) {
7194 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7195 Package *package([database packageWithName:path]);
7199 UIImage *icon([package icon]);
7200 [self _returnPNGWithImage:icon forRequest:request];
7201 } else if ([command isEqualToString:@"uikit-image"]) {
7204 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7205 UIImage *icon(_UIImageWithName(path));
7206 [self _returnPNGWithImage:icon forRequest:request];
7207 } else if ([command isEqualToString:@"section-icon"]) {
7210 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7211 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7213 icon = [UIImage imageNamed:@"unknown.png"];
7214 [self _returnPNGWithImage:icon forRequest:request];
7216 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7220 - (void) stopLoading {
7226 /* Section Controller {{{ */
7227 @interface SectionController : FilteredPackageListController {
7229 _H<NSString> section_;
7232 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7236 @implementation SectionController
7238 - (NSURL *) referrerURL {
7239 NSString *name(section_);
7240 name = name ?: @"*";
7241 NSString *key(key_);
7243 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7246 - (NSURL *) navigationURL {
7247 NSString *name(section_);
7248 name = name ?: @"*";
7249 NSString *key(key_);
7251 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7254 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7257 title = UCLocalize("ALL_PACKAGES");
7258 else if (![section isEqual:@""])
7259 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7261 title = UCLocalize("NO_SECTION");
7263 if ((self = [super initWithDatabase:database title:title]) != nil) {
7264 key_ = [source key];
7269 - (void) reloadData {
7270 Source *source([database_ sourceWithKey:key_]);
7271 _H<NSString> name(section_);
7273 [self setFilter:[=](Package *package) {
7274 NSString *section([package section]);
7278 section == nil && [name length] == 0 ||
7279 [name isEqualToString:section]
7282 [package source] == source
7283 ) && [package visible];
7291 /* Sections Controller {{{ */
7292 @interface SectionsController : CyteViewController <
7293 UITableViewDataSource,
7296 _transient Database *database_;
7298 _H<NSMutableArray> sections_;
7299 _H<NSMutableArray> filtered_;
7300 _H<UITableView, 2> list_;
7303 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7304 - (void) editButtonClicked;
7308 @implementation SectionsController
7310 - (NSURL *) navigationURL {
7311 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7314 - (Source *) source {
7317 return [database_ sourceWithKey:key_];
7320 - (void) updateNavigationItem {
7321 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7322 if ([sections_ count] == 0) {
7323 [[self navigationItem] setRightBarButtonItem:nil];
7325 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7326 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7328 action:@selector(editButtonClicked)
7329 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7333 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7334 [super setEditing:editing animated:animated];
7339 [delegate_ updateData];
7341 [self updateNavigationItem];
7344 - (void) viewDidAppear:(BOOL)animated {
7345 [super viewDidAppear:animated];
7346 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7349 - (void) viewWillDisappear:(BOOL)animated {
7350 [super viewWillDisappear:animated];
7351 [self setEditing:NO];
7354 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7355 Section *section = nil;
7356 int index = [indexPath row];
7357 if (![self isEditing]) {
7360 section = [filtered_ objectAtIndex:index];
7362 section = [sections_ objectAtIndex:index];
7367 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7368 if ([self isEditing])
7369 return [sections_ count];
7371 return [filtered_ count] + 1;
7374 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7378 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7379 static NSString *reuseIdentifier = @"SectionCell";
7381 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7383 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7385 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7390 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7391 if ([self isEditing])
7394 Section *section = [self sectionAtIndexPath:indexPath];
7396 SectionController *controller = [[[SectionController alloc]
7397 initWithDatabase:database_
7398 source:[self source]
7399 section:[section name]
7401 [controller setDelegate:delegate_];
7403 [[self navigationController] pushViewController:controller animated:YES];
7407 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7408 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7409 [list_ setRowHeight:46];
7410 [(UITableView *) list_ setDataSource:self];
7411 [list_ setDelegate:self];
7412 [self setView:list_];
7415 - (void) viewDidLoad {
7416 [super viewDidLoad];
7418 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7421 - (void) releaseSubviews {
7427 [super releaseSubviews];
7430 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7431 if ((self = [super init]) != nil) {
7432 database_ = database;
7433 key_ = [source key];
7437 - (void) reloadData {
7440 NSArray *packages = [database_ packages];
7442 sections_ = [NSMutableArray arrayWithCapacity:16];
7443 filtered_ = [NSMutableArray arrayWithCapacity:16];
7445 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7447 Source *source([self source]);
7450 for (Package *package in packages) {
7451 if (source != nil && [package source] != source)
7454 NSString *name([package section]);
7455 NSString *key(name == nil ? @"" : name);
7459 _profile(SectionsView$reloadData$Section)
7460 section = [sections objectForKey:key];
7461 if (section == nil) {
7462 _profile(SectionsView$reloadData$Section$Allocate)
7463 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7464 [sections setObject:section forKey:key];
7469 [section addToCount];
7471 _profile(SectionsView$reloadData$Filter)
7472 if (![package valid] || ![package visible])
7480 [sections_ addObjectsFromArray:[sections allValues]];
7482 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7484 for (Section *section in (id) sections_) {
7485 size_t count([section row]);
7489 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7490 [section setCount:count];
7491 [filtered_ addObject:section];
7494 [self updateNavigationItem];
7499 - (void) editButtonClicked {
7500 [self setEditing:![self isEditing] animated:YES];
7506 /* Changes Controller {{{ */
7507 @interface ChangesController : FilteredPackageListController {
7511 - (id) initWithDatabase:(Database *)database;
7515 @implementation ChangesController
7517 - (NSURL *) referrerURL {
7518 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7521 - (NSURL *) navigationURL {
7522 return [NSURL URLWithString:@"cydia://changes"];
7525 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7526 @synchronized (database_) {
7527 if ([database_ era] != era_)
7530 NSUInteger sectionIndex([path section]);
7531 if (sectionIndex >= [sections_ count])
7533 Section *section([sections_ objectAtIndex:sectionIndex]);
7534 NSInteger row([path row]);
7535 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7538 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7539 NSString *context([alert context]);
7541 if ([context isEqualToString:@"norefresh"])
7542 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7545 - (void) setLeftBarButtonItem {
7546 if ([delegate_ updating])
7547 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7548 initWithTitle:UCLocalize("CANCEL")
7549 style:UIBarButtonItemStyleDone
7551 action:@selector(cancelButtonClicked)
7552 ] autorelease] animated:YES];
7554 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7555 initWithTitle:UCLocalize("REFRESH")
7556 style:UIBarButtonItemStylePlain
7558 action:@selector(refreshButtonClicked)
7559 ] autorelease] animated:YES];
7562 - (void) refreshButtonClicked {
7563 if ([delegate_ requestUpdate])
7564 [self setLeftBarButtonItem];
7567 - (void) cancelButtonClicked {
7568 [delegate_ cancelUpdate];
7571 - (void) upgradeButtonClicked {
7572 [delegate_ distUpgrade];
7573 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7576 - (bool) shouldYield {
7580 - (bool) shouldBlock {
7584 - (void) useFilter {
7585 @synchronized (self) {
7586 [self setFilter:[](Package *package) {
7587 return [package upgradableAndEssential:YES] || [package visible];
7590 [self setSorter:[](NSMutableArray *packages) {
7591 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7595 - (id) initWithDatabase:(Database *)database {
7596 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7601 - (void) viewDidLoad {
7602 [super viewDidLoad];
7603 [self setLeftBarButtonItem];
7606 - (void) viewWillAppear:(BOOL)animated {
7607 [super viewWillAppear:animated];
7608 [self setLeftBarButtonItem];
7611 - (void) reloadData {
7612 [self setLeftBarButtonItem];
7616 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7617 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7619 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7620 Section *ignored = nil;
7621 Section *section = nil;
7625 bool unseens = false;
7627 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7629 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7630 Package *package = [packages objectAtIndex:offset];
7632 BOOL uae = [package upgradableAndEssential:YES];
7636 time_t seen([package seen]);
7638 if (section == nil || last != seen) {
7642 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7645 _profile(ChangesController$reloadData$Allocate)
7646 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7647 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7648 [sections addObject:section];
7652 [section addToCount];
7653 } else if ([package ignored]) {
7654 if (ignored == nil) {
7655 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7657 [ignored addToCount];
7660 [upgradable addToCount];
7665 CFRelease(formatter);
7668 Section *last = [sections lastObject];
7669 size_t count = [last count];
7670 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7671 [sections removeLastObject];
7674 if ([ignored count] != 0)
7675 [sections insertObject:ignored atIndex:0];
7677 [sections insertObject:upgradable atIndex:0];
7681 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7682 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7683 style:UIBarButtonItemStylePlain
7685 action:@selector(upgradeButtonClicked)
7686 ] autorelease]) animated:YES];
7693 /* Search Controller {{{ */
7694 @interface SearchController : FilteredPackageListController <
7697 _H<UISearchBar, 1> search_;
7702 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7703 - (void) reloadData;
7707 @implementation SearchController
7709 - (NSURL *) referrerURL {
7710 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7713 - (NSURL *) navigationURL {
7714 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7715 return [NSURL URLWithString:@"cydia://search"];
7717 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7720 - (NSArray *) termsForQuery:(NSString *)query {
7721 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7722 for (NSString *component in [query componentsSeparatedByString:@" "])
7723 if ([component length] != 0)
7724 [terms addObject:component];
7729 - (void) useSearch {
7730 _H<NSArray> query([self termsForQuery:[search_ text]]);
7733 @synchronized (self) {
7734 [self setFilter:[=](Package *package) {
7735 if (![package unfiltered])
7737 if (![package matches:query])
7742 [self setSorter:[](NSMutableArray *packages) {
7743 [packages radixSortUsingSelector:@selector(rank)];
7751 - (void) usePrefix:(NSString *)prefix {
7752 _H<NSString> query(prefix);
7755 @synchronized (self) {
7756 [self setFilter:[=](Package *package) {
7757 if ([query length] == 0)
7759 if (![package unfiltered])
7761 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7766 [self setSorter:nullptr];
7772 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7774 [self usePrefix:[search_ text]];
7777 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7778 [search_ resignFirstResponder];
7782 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7783 [search_ setText:@""];
7784 [self searchBarButtonClicked:searchBar];
7787 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7788 [self searchBarButtonClicked:searchBar];
7791 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7792 [self usePrefix:text];
7795 - (bool) shouldYield {
7799 - (bool) shouldBlock {
7803 - (bool) isSummarized {
7807 - (bool) showsSections {
7811 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7812 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7813 search_ = [[[UISearchBar alloc] init] autorelease];
7814 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7815 [search_ setDelegate:self];
7817 UITextField *textField;
7818 if ([search_ respondsToSelector:@selector(searchField)])
7819 textField = [search_ searchField];
7821 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7823 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7824 [textField setEnablesReturnKeyAutomatically:NO];
7825 [[self navigationItem] setTitleView:textField];
7828 [search_ setText:query];
7833 - (void) viewDidAppear:(BOOL)animated {
7834 [super viewDidAppear:animated];
7836 if (!searchloaded_) {
7837 searchloaded_ = YES;
7838 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7839 [search_ layoutSubviews];
7842 if ([self isSummarized])
7843 [search_ becomeFirstResponder];
7846 - (void) reloadData {
7851 - (void) didSelectPackage:(Package *)package {
7852 [search_ resignFirstResponder];
7853 [super didSelectPackage:package];
7858 /* Package Settings Controller {{{ */
7859 @interface PackageSettingsController : CyteViewController <
7860 UITableViewDataSource,
7863 _transient Database *database_;
7865 _H<Package> package_;
7866 _H<UITableView, 2> table_;
7867 _H<UISwitch> subscribedSwitch_;
7868 _H<UISwitch> ignoredSwitch_;
7869 _H<UITableViewCell> subscribedCell_;
7870 _H<UITableViewCell> ignoredCell_;
7873 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7877 @implementation PackageSettingsController
7879 - (NSURL *) navigationURL {
7880 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7883 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7884 if (package_ == nil)
7887 if ([package_ installed] == nil)
7893 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7894 if (package_ == nil)
7897 // both sections contain just one item right now.
7901 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7905 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7907 return UCLocalize("SHOW_ALL_CHANGES_EX");
7909 return UCLocalize("IGNORE_UPGRADES_EX");
7912 - (void) onSubscribed:(id)control {
7913 bool value([control isOn]);
7914 if (package_ == nil)
7916 if ([package_ setSubscribed:value])
7917 [delegate_ updateData];
7920 - (void) _updateIgnored {
7921 const char *package([name_ UTF8String]);
7922 bool on([ignoredSwitch_ isOn]);
7924 pid_t pid(ExecFork());
7926 FILE *dpkg(popen("dpkg --set-selections", "w"));
7927 fwrite(package, strlen(package), 1, dpkg);
7930 fwrite(" hold\n", 6, 1, dpkg);
7932 fwrite(" install\n", 9, 1, dpkg);
7940 - (void) onIgnored:(id)control {
7941 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7942 [invocation setTarget:self];
7943 [invocation setSelector:@selector(_updateIgnored)];
7945 [delegate_ reloadDataWithInvocation:invocation];
7948 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7949 if (package_ == nil)
7952 switch ([indexPath section]) {
7953 case 0: return subscribedCell_;
7954 case 1: return ignoredCell_;
7963 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7964 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7965 [self setView:view];
7967 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7968 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7969 [(UITableView *) table_ setDataSource:self];
7970 [table_ setDelegate:self];
7971 [view addSubview:table_];
7973 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7974 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7975 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7977 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7978 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7979 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7981 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7982 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7983 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7984 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7986 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7987 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7988 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7989 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7992 - (void) viewDidLoad {
7993 [super viewDidLoad];
7995 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7998 - (void) releaseSubviews {
8000 subscribedCell_ = nil;
8002 ignoredSwitch_ = nil;
8003 subscribedSwitch_ = nil;
8005 [super releaseSubviews];
8008 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8009 if ((self = [super init]) != nil) {
8010 database_ = database;
8015 - (void) reloadData {
8018 package_ = [database_ packageWithName:name_];
8020 if (package_ != nil) {
8021 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8022 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8023 } // XXX: what now, G?
8025 [table_ reloadData];
8031 /* Installed Controller {{{ */
8032 @interface InstalledController : FilteredPackageListController {
8036 - (id) initWithDatabase:(Database *)database;
8037 - (void) queueStatusDidChange;
8041 @implementation InstalledController
8043 - (NSURL *) referrerURL {
8044 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8047 - (NSURL *) navigationURL {
8048 return [NSURL URLWithString:@"cydia://installed"];
8051 - (void) useRecent {
8054 @synchronized (self) {
8055 [self setFilter:[](Package *package) {
8056 return ![package uninstalled] && package->role_ < 7;
8059 [self setSorter:[](NSMutableArray *packages) {
8060 [packages radixSortUsingSelector:@selector(recent)];
8064 - (void) useFilter:(UISegmentedControl *)segmented {
8065 NSInteger selected([segmented selectedSegmentIndex]);
8067 return [self useRecent];
8068 bool simple(selected == 0);
8071 @synchronized (self) {
8072 [self setFilter:[=](Package *package) {
8073 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8076 [self setSorter:nullptr];
8079 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8081 return [super sectionsForPackages:packages];
8083 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8085 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8086 Section *section(nil);
8089 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8090 Package *package([packages objectAtIndex:offset]);
8092 time_t upgraded([package upgraded]);
8093 if (upgraded < 1168364520)
8096 upgraded -= upgraded % (60 * 60 * 24);
8098 if (section == nil || upgraded != last) {
8103 continue; // XXX: name = UCLocalize("...");
8105 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8109 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8110 [sections addObject:section];
8113 [section addToCount];
8116 CFRelease(formatter);
8120 - (id) initWithDatabase:(Database *)database {
8121 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8122 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8123 [segmented setSelectedSegmentIndex:0];
8124 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8125 [[self navigationItem] setTitleView:segmented];
8127 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8128 [self useFilter:segmented];
8130 [self queueStatusDidChange];
8135 - (void) queueButtonClicked {
8140 - (void) queueStatusDidChange {
8143 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8144 initWithTitle:UCLocalize("QUEUE")
8145 style:UIBarButtonItemStyleDone
8147 action:@selector(queueButtonClicked)
8150 [[self navigationItem] setRightBarButtonItem:nil];
8155 - (void) modeChanged:(UISegmentedControl *)segmented {
8156 [self useFilter:segmented];
8163 /* Source Cell {{{ */
8164 @interface SourceCell : CyteTableViewCell <
8165 CyteTableViewCellDelegate,
8168 _H<Source, 1> source_;
8171 _H<NSString> origin_;
8172 _H<NSString> label_;
8173 _H<UIActivityIndicatorView> indicator_;
8176 - (void) setSource:(Source *)source;
8177 - (void) setFetch:(NSNumber *)fetch;
8181 @implementation SourceCell
8183 - (void) _setImage:(NSArray *)data {
8184 if ([url_ isEqual:[data objectAtIndex:0]]) {
8185 icon_ = [data objectAtIndex:1];
8186 [content_ setNeedsDisplay];
8190 - (void) _setSource:(NSURL *) url {
8191 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8193 if (NSData *data = [NSURLConnection
8194 sendSynchronousRequest:[NSURLRequest
8196 cachePolicy:NSURLRequestUseProtocolCachePolicy
8200 returningResponse:NULL
8203 if (UIImage *image = [UIImage imageWithData:data])
8204 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8209 - (void) setSource:(Source *)source {
8211 [source_ setDelegate:self];
8213 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8215 icon_ = [UIImage imageNamed:@"unknown.png"];
8217 origin_ = [source name];
8218 label_ = [source rooturi];
8220 [content_ setNeedsDisplay];
8222 url_ = [source iconURL];
8223 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8226 - (void) setAllSource {
8228 [indicator_ stopAnimating];
8230 icon_ = [UIImage imageNamed:@"folder.png"];
8231 origin_ = UCLocalize("ALL_SOURCES");
8232 label_ = UCLocalize("ALL_SOURCES_EX");
8233 [content_ setNeedsDisplay];
8236 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8237 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8238 UIView *content([self contentView]);
8239 CGRect bounds([content bounds]);
8241 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8242 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8243 [content_ setBackgroundColor:[UIColor whiteColor]];
8244 [content addSubview:content_];
8246 [content_ setDelegate:self];
8247 [content_ setOpaque:YES];
8249 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8250 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8251 [content addSubview:indicator_];
8253 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8257 - (void) layoutSubviews {
8258 [super layoutSubviews];
8260 UIView *content([self contentView]);
8261 CGRect bounds([content bounds]);
8263 CGRect frame([indicator_ frame]);
8264 frame.origin.x = bounds.size.width - frame.size.width;
8265 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8267 if (kCFCoreFoundationVersionNumber < 800)
8268 frame.origin.x -= 8;
8269 [indicator_ setFrame:frame];
8272 - (NSString *) accessibilityLabel {
8276 - (void) drawContentRect:(CGRect)rect {
8277 bool highlighted(highlighted_);
8278 float width(rect.size.width);
8282 rect.size = [(UIImage *) icon_ size];
8284 while (rect.size.width > 32 || rect.size.height > 32) {
8285 rect.size.width /= 2;
8286 rect.size.height /= 2;
8289 rect.origin.x = 26 - rect.size.width / 2;
8290 rect.origin.y = 26 - rect.size.height / 2;
8292 [icon_ drawInRect:Retina(rect)];
8295 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8300 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8304 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8307 - (void) setFetch:(NSNumber *)fetch {
8308 if ([fetch boolValue])
8309 [indicator_ startAnimating];
8311 [indicator_ stopAnimating];
8316 /* Sources Controller {{{ */
8317 @interface SourcesController : CyteViewController <
8318 UITableViewDataSource,
8321 _transient Database *database_;
8324 _H<UITableView, 2> list_;
8325 _H<NSMutableArray> sources_;
8329 _H<UIProgressHUD> hud_;
8332 NSURLConnection *trivial_bz2_;
8333 NSURLConnection *trivial_gz_;
8338 - (id) initWithDatabase:(Database *)database;
8339 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8343 @implementation SourcesController
8345 - (void) _releaseConnection:(NSURLConnection *)connection {
8346 if (connection != nil) {
8347 [connection cancel];
8348 //[connection setDelegate:nil];
8349 [connection release];
8354 [self _releaseConnection:trivial_gz_];
8355 [self _releaseConnection:trivial_bz2_];
8360 - (NSURL *) navigationURL {
8361 return [NSURL URLWithString:@"cydia://sources"];
8364 - (void) viewDidAppear:(BOOL)animated {
8365 [super viewDidAppear:animated];
8366 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8369 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8373 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8375 return UCLocalize("INDIVIDUAL_SOURCES");
8379 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8382 case 1: return [sources_ count];
8387 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8388 @synchronized (database_) {
8389 if ([database_ era] != era_)
8391 if ([indexPath section] != 1)
8393 NSUInteger index([indexPath row]);
8394 if (index >= [sources_ count])
8396 return [sources_ objectAtIndex:index];
8399 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8400 static NSString *cellIdentifier = @"SourceCell";
8402 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8403 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8404 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8406 Source *source([self sourceAtIndexPath:indexPath]);
8408 [cell setAllSource];
8410 [cell setSource:source];
8415 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8416 SectionsController *controller([[[SectionsController alloc]
8417 initWithDatabase:database_
8418 source:[self sourceAtIndexPath:indexPath]
8421 [controller setDelegate:delegate_];
8422 [[self navigationController] pushViewController:controller animated:YES];
8425 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8426 if ([indexPath section] != 1)
8428 Source *source = [self sourceAtIndexPath:indexPath];
8429 return [source record] != nil;
8432 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8433 _assert([indexPath section] == 1);
8434 if (editingStyle == UITableViewCellEditingStyleDelete) {
8435 Source *source = [self sourceAtIndexPath:indexPath];
8436 if (source == nil) return;
8438 [Sources_ removeObjectForKey:[source key]];
8441 [delegate_ _saveConfig];
8442 [delegate_ reloadDataWithInvocation:nil];
8446 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8447 [self updateButtonsForEditingStatusAnimated:YES];
8451 [delegate_ addTrivialSource:href_];
8454 [delegate_ syncData];
8457 - (NSString *) getWarning {
8458 NSString *href(href_);
8459 NSRange colon([href rangeOfString:@"://"]);
8460 if (colon.location != NSNotFound)
8461 href = [href substringFromIndex:(colon.location + 3)];
8462 href = [href stringByAddingPercentEscapes];
8463 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8465 NSURL *url([NSURL URLWithString:href]);
8467 NSStringEncoding encoding;
8468 NSError *error(nil);
8470 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8471 return [warning length] == 0 ? nil : warning;
8475 - (void) _endConnection:(NSURLConnection *)connection {
8476 // XXX: the memory management in this method is horribly awkward
8478 NSURLConnection **field = NULL;
8479 if (connection == trivial_bz2_)
8480 field = &trivial_bz2_;
8481 else if (connection == trivial_gz_)
8482 field = &trivial_gz_;
8483 _assert(field != NULL);
8484 [connection release];
8488 trivial_bz2_ == nil &&
8491 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8493 [delegate_ releaseNetworkActivityIndicator];
8495 [delegate_ removeProgressHUD:hud_];
8499 if (warning != nil) {
8500 UIAlertView *alert = [[[UIAlertView alloc]
8501 initWithTitle:UCLocalize("SOURCE_WARNING")
8504 cancelButtonTitle:UCLocalize("CANCEL")
8506 UCLocalize("ADD_ANYWAY"),
8510 [alert setContext:@"warning"];
8511 [alert setNumberOfRows:1];
8514 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8520 } else if (error_ != nil) {
8521 UIAlertView *alert = [[[UIAlertView alloc]
8522 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8523 message:[error_ localizedDescription]
8525 cancelButtonTitle:UCLocalize("OK")
8526 otherButtonTitles:nil
8529 [alert setContext:@"urlerror"];
8534 UIAlertView *alert = [[[UIAlertView alloc]
8535 initWithTitle:UCLocalize("NOT_REPOSITORY")
8536 message:UCLocalize("NOT_REPOSITORY_EX")
8538 cancelButtonTitle:UCLocalize("OK")
8539 otherButtonTitles:nil
8542 [alert setContext:@"trivial"];
8552 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8553 switch ([response statusCode]) {
8559 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8560 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8562 [self _endConnection:connection];
8565 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8566 [self _endConnection:connection];
8569 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8570 NSURL *url([NSURL URLWithString:href]);
8572 NSMutableURLRequest *request = [NSMutableURLRequest
8574 cachePolicy:NSURLRequestUseProtocolCachePolicy
8578 [request setHTTPMethod:method];
8580 if (Machine_ != NULL)
8581 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8583 if (UniqueID_ != nil)
8584 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8586 if ([url isCydiaSecure]) {
8587 if (UniqueID_ != nil)
8588 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8591 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8594 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8595 NSString *context([alert context]);
8597 if ([context isEqualToString:@"source"]) {
8600 NSString *href = [[alert textField] text];
8602 static Pcre href_r("^http(s?)://[^# ]*$");
8603 if (!href_r(href)) {
8604 UIAlertView *alert = [[[UIAlertView alloc]
8605 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8606 message:UCLocalize("INVALID_URL_EX")
8608 cancelButtonTitle:UCLocalize("OK")
8609 otherButtonTitles:nil
8612 [alert setContext:@"badurl"];
8618 if (![href hasSuffix:@"/"])
8619 href_ = [href stringByAppendingString:@"/"];
8623 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8624 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8628 // XXX: this is stupid
8629 hud_ = [delegate_ addProgressHUD];
8630 [hud_ setText:UCLocalize("VERIFYING_URL")];
8631 [delegate_ retainNetworkActivityIndicator];
8640 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8641 } else if ([context isEqualToString:@"trivial"])
8642 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8643 else if ([context isEqualToString:@"urlerror"])
8644 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8645 else if ([context isEqualToString:@"warning"]) {
8648 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8657 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8661 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8662 BOOL editing([list_ isEditing]);
8665 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8666 initWithTitle:UCLocalize("ADD")
8667 style:UIBarButtonItemStylePlain
8669 action:@selector(addButtonClicked)
8670 ] autorelease] animated:animated];
8671 else if ([delegate_ updating])
8672 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8673 initWithTitle:UCLocalize("CANCEL")
8674 style:UIBarButtonItemStyleDone
8676 action:@selector(cancelButtonClicked)
8677 ] autorelease] animated:animated];
8679 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8680 initWithTitle:UCLocalize("REFRESH")
8681 style:UIBarButtonItemStylePlain
8683 action:@selector(refreshButtonClicked)
8684 ] autorelease] animated:animated];
8686 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8687 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8688 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8690 action:@selector(editButtonClicked)
8691 ] autorelease] animated:animated];
8695 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8696 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8697 [list_ setRowHeight:53];
8698 [(UITableView *) list_ setDataSource:self];
8699 [list_ setDelegate:self];
8700 [self setView:list_];
8703 - (void) viewDidLoad {
8704 [super viewDidLoad];
8706 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8707 [self updateButtonsForEditingStatusAnimated:NO];
8710 - (void) viewWillAppear:(BOOL)animated {
8711 [super viewWillAppear:animated];
8713 [list_ setEditing:NO];
8714 [self updateButtonsForEditingStatusAnimated:NO];
8717 - (void) releaseSubviews {
8722 [super releaseSubviews];
8725 - (id) initWithDatabase:(Database *)database {
8726 if ((self = [super init]) != nil) {
8727 database_ = database;
8731 - (void) reloadData {
8733 [self updateButtonsForEditingStatusAnimated:YES];
8735 @synchronized (database_) {
8736 era_ = [database_ era];
8738 sources_ = [NSMutableArray arrayWithCapacity:16];
8739 [sources_ addObjectsFromArray:[database_ sources]];
8741 [sources_ sortUsingSelector:@selector(compareByName:)];
8744 int count([sources_ count]);
8746 for (int i = 0; i != count; i++) {
8747 if ([[sources_ objectAtIndex:i] record] == nil)
8755 - (void) showAddSourcePrompt {
8756 UIAlertView *alert = [[[UIAlertView alloc]
8757 initWithTitle:UCLocalize("ENTER_APT_URL")
8760 cancelButtonTitle:UCLocalize("CANCEL")
8762 UCLocalize("ADD_SOURCE"),
8766 [alert setContext:@"source"];
8768 [alert setNumberOfRows:1];
8769 [alert addTextFieldWithValue:@"http://" label:@""];
8771 UITextInputTraits *traits = [[alert textField] textInputTraits];
8772 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8773 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8774 [traits setKeyboardType:UIKeyboardTypeURL];
8775 // XXX: UIReturnKeyDone
8776 [traits setReturnKeyType:UIReturnKeyNext];
8781 - (void) addButtonClicked {
8782 [self showAddSourcePrompt];
8785 - (void) refreshButtonClicked {
8786 if ([delegate_ requestUpdate])
8787 [self updateButtonsForEditingStatusAnimated:YES];
8790 - (void) cancelButtonClicked {
8791 [delegate_ cancelUpdate];
8794 - (void) editButtonClicked {
8795 [list_ setEditing:![list_ isEditing] animated:YES];
8796 [self updateButtonsForEditingStatusAnimated:YES];
8802 /* Stash Controller {{{ */
8803 @interface StashController : CyteViewController {
8804 _H<UIActivityIndicatorView> spinner_;
8805 _H<UILabel> status_;
8806 _H<UILabel> caption_;
8811 @implementation StashController
8814 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8815 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8816 [self setView:view];
8818 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8820 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8821 CGRect spinrect = [spinner_ frame];
8822 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8823 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8824 [spinner_ setFrame:spinrect];
8825 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8826 [view addSubview:spinner_];
8827 [spinner_ startAnimating];
8830 captrect.size.width = [[self view] frame].size.width;
8831 captrect.size.height = 40.0f;
8832 captrect.origin.x = 0;
8833 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8834 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8835 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8836 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8837 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8838 [caption_ setTextColor:[UIColor whiteColor]];
8839 [caption_ setBackgroundColor:[UIColor clearColor]];
8840 [caption_ setShadowColor:[UIColor blackColor]];
8841 [caption_ setTextAlignment:NSTextAlignmentCenter];
8842 [view addSubview:caption_];
8845 statusrect.size.width = [[self view] frame].size.width;
8846 statusrect.size.height = 30.0f;
8847 statusrect.origin.x = 0;
8848 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8849 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8850 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8851 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8852 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8853 [status_ setTextColor:[UIColor whiteColor]];
8854 [status_ setBackgroundColor:[UIColor clearColor]];
8855 [status_ setShadowColor:[UIColor blackColor]];
8856 [status_ setTextAlignment:NSTextAlignmentCenter];
8857 [view addSubview:status_];
8860 - (void) releaseSubviews {
8865 [super releaseSubviews];
8871 @interface CYURLCache : SDURLCache {
8876 @implementation CYURLCache
8878 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8881 else if ([event isEqualToString:@"no-cache"])
8883 else if ([event isEqualToString:@"store"])
8885 else if ([event isEqualToString:@"invalid"])
8887 else if ([event isEqualToString:@"memory"])
8889 else if ([event isEqualToString:@"disk"])
8891 else if ([event isEqualToString:@"miss"])
8894 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8898 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8899 if (NSURLResponse *response = [cached response])
8900 if (NSString *mime = [response MIMEType])
8901 if ([mime isEqualToString:@"text/cache-manifest"]) {
8902 NSURL *url([response URL]);
8905 NSLog(@"###: %@", [url absoluteString]);
8908 @synchronized (HostConfig_) {
8909 [CachedURLs_ addObject:url];
8913 [super storeCachedResponse:cached forRequest:request];
8918 @interface Cydia : UIApplication <
8919 ConfirmationControllerDelegate,
8923 _H<UIWindow> window_;
8924 _H<CydiaTabBarController> tabbar_;
8925 _H<CyteTabBarController> emulated_;
8927 _H<NSMutableArray> essential_;
8928 _H<NSMutableArray> broken_;
8930 Database *database_;
8932 _H<NSURL> starturl_;
8937 _H<StashController> stash_;
8946 @implementation Cydia
8948 - (void) lockSuspend {
8949 if (locked_++ == 0) {
8950 if ($SBSSetInterceptsMenuButtonForever != NULL)
8951 (*$SBSSetInterceptsMenuButtonForever)(true);
8953 [self setIdleTimerDisabled:YES];
8957 - (void) unlockSuspend {
8958 if (--locked_ == 0) {
8959 [self setIdleTimerDisabled:NO];
8961 if ($SBSSetInterceptsMenuButtonForever != NULL)
8962 (*$SBSSetInterceptsMenuButtonForever)(false);
8966 - (void) beginUpdate {
8967 [tabbar_ beginUpdate];
8970 - (void) cancelUpdate {
8971 [tabbar_ cancelUpdate];
8974 - (bool) requestUpdate {
8975 if (IsReachable("cydia.saurik.com")) {
8979 UIAlertView *alert = [[[UIAlertView alloc]
8980 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8981 message:@"Host Unreachable" // XXX: Localize
8983 cancelButtonTitle:UCLocalize("OK")
8984 otherButtonTitles:nil
8987 [alert setContext:@"norefresh"];
8995 return [tabbar_ updating];
8999 if ([broken_ count] != 0) {
9000 int count = [broken_ count];
9002 UIAlertView *alert = [[[UIAlertView alloc]
9003 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9004 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9006 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9008 UCLocalize("TEMPORARY_IGNORE"),
9012 [alert setContext:@"fixhalf"];
9013 [alert setNumberOfRows:2];
9015 } else if (!Ignored_ && [essential_ count] != 0) {
9016 int count = [essential_ count];
9018 UIAlertView *alert = [[[UIAlertView alloc]
9019 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9020 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9022 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9024 UCLocalize("UPGRADE_ESSENTIAL"),
9025 UCLocalize("COMPLETE_UPGRADE"),
9029 [alert setContext:@"upgrade"];
9034 - (void) returnToCydia {
9038 - (void) _saveConfig {
9039 @synchronized (database_) {
9046 NSString *error(nil);
9048 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9050 NSError *error(nil);
9051 _root(true) if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9052 NSLog(@"failure to save metadata data: %@", error);
9057 NSLog(@"failure to serialize metadata: %@", error);
9061 CydiaWriteSources();
9064 // Navigation controller for the queuing badge.
9065 - (UINavigationController *) queueNavigationController {
9066 NSArray *controllers = [tabbar_ viewControllers];
9067 return [controllers objectAtIndex:3];
9070 - (void) unloadData {
9071 [tabbar_ unloadData];
9074 - (void) _updateData {
9078 UINavigationController *navigation = [self queueNavigationController];
9080 id queuedelegate = nil;
9081 if ([[navigation viewControllers] count] > 0)
9082 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9084 [queuedelegate queueStatusDidChange];
9085 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9088 - (void) _refreshIfPossible:(NSDate *)update {
9089 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9091 bool recently = false;
9092 if (update != nil) {
9093 NSTimeInterval interval([update timeIntervalSinceNow]);
9094 if (interval <= 0 && interval > -(15*60))
9098 // Don't automatic refresh if:
9099 // - We already refreshed recently.
9100 // - We already auto-refreshed this launch.
9101 // - Auto-refresh is disabled.
9102 // - Cydia's server is not reachable
9103 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9104 // If we are cancelling, we need to make sure it knows it's already loaded.
9107 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9109 // We are going to load, so remember that.
9112 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9118 - (void) refreshIfPossible {
9119 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9122 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9123 _profile(reloadDataWithInvocation)
9124 @synchronized (self) {
9125 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9127 [hud setText:UCLocalize("RELOADING_DATA")];
9129 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9133 [essential_ removeAllObjects];
9134 [broken_ removeAllObjects];
9136 _profile(reloadDataWithInvocation$Essential)
9137 NSArray *packages([database_ packages]);
9138 for (Package *package in packages) {
9140 [broken_ addObject:package];
9141 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9142 if ([package essential] && [package installed] != nil)
9143 [essential_ addObject:package];
9149 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9152 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9153 [changesItem setBadgeValue:badge];
9154 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9155 [self setApplicationIconBadgeNumber:changes];
9158 [changesItem setBadgeValue:nil];
9159 [changesItem setAnimatedBadge:NO];
9160 [self setApplicationIconBadgeNumber:0];
9166 [self removeProgressHUD:hud];
9173 - (void) updateData {
9177 - (void) updateDataAndLoad {
9179 if ([database_ progressDelegate] == nil)
9185 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9188 - (void) disemulate {
9189 if (emulated_ == nil)
9192 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9193 [window_ setRootViewController:tabbar_];
9195 [window_ addSubview:[tabbar_ view]];
9196 [[emulated_ view] removeFromSuperview];
9200 [window_ setUserInteractionEnabled:YES];
9203 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9204 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9206 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9208 UIViewController *parent;
9209 if (emulated_ == nil)
9218 [parent presentModalViewController:navigation animated:YES];
9221 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9222 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9224 if (navigation != nil)
9225 [navigation pushViewController:progress animated:YES];
9227 [self presentModalViewController:progress force:YES];
9229 [progress invoke:invocation withTitle:title];
9233 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9234 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9237 - (void) repairWithInvocation:(NSInvocation *)invocation {
9239 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9243 - (void) repairWithSelector:(SEL)selector {
9244 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9247 - (void) reloadData {
9248 [self reloadDataWithInvocation:nil];
9249 if ([database_ progressDelegate] == nil)
9255 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9258 - (void) addSource:(NSDictionary *) source {
9259 CydiaAddSource(source);
9262 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9263 CydiaAddSource(href, distribution, sections);
9266 - (void) addTrivialSource:(NSString *)href {
9267 CydiaAddSource(href, @"./");
9270 - (void) updateValues {
9275 pkgProblemResolver *resolver = [database_ resolver];
9277 resolver->InstallProtect();
9278 if (!resolver->Resolve(true))
9283 // XXX: this is a really crappy way of doing this.
9284 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9285 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9286 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9287 if ([tabbar_ updating])
9288 [tabbar_ cancelUpdate];
9290 if (![database_ prepare])
9293 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9294 [page setDelegate:self];
9295 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9298 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9299 [tabbar_ presentModalViewController:confirm_ animated:YES];
9305 @synchronized (self) {
9310 - (void) clearPackage:(Package *)package {
9311 @synchronized (self) {
9318 - (void) installPackages:(NSArray *)packages {
9319 @synchronized (self) {
9320 for (Package *package in packages)
9327 - (void) installPackage:(Package *)package {
9328 @synchronized (self) {
9335 - (void) removePackage:(Package *)package {
9336 @synchronized (self) {
9343 - (void) distUpgrade {
9344 @synchronized (self) {
9345 if (![database_ upgrade])
9353 system("/usr/bin/uicache");
9358 UIProgressHUD *hud([self addProgressHUD]);
9359 [hud setText:UCLocalize("LOADING")];
9360 [self yieldToSelector:@selector(_uicache)];
9361 [self removeProgressHUD:hud];
9365 [database_ perform];
9366 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9367 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9370 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9373 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9374 [self unlockSuspend];
9377 - (void) retainNetworkActivityIndicator {
9378 if (activity_++ == 0)
9379 [self setNetworkActivityIndicatorVisible:YES];
9382 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9386 - (void) releaseNetworkActivityIndicator {
9387 if (--activity_ == 0)
9388 [self setNetworkActivityIndicatorVisible:NO];
9391 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9396 - (void) cancelAndClear:(bool)clear {
9397 @synchronized (self) {
9409 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9410 NSString *context([alert context]);
9412 if ([context isEqualToString:@"conffile"]) {
9413 FILE *input = [database_ input];
9414 if (button == [alert cancelButtonIndex])
9415 fprintf(input, "N\n");
9416 else if (button == [alert firstOtherButtonIndex])
9417 fprintf(input, "Y\n");
9420 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9421 } else if ([context isEqualToString:@"fixhalf"]) {
9422 if (button == [alert cancelButtonIndex]) {
9423 @synchronized (self) {
9424 _root(false) for (Package *broken in (id) broken_) {
9427 NSString *id = [broken id];
9428 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9429 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9430 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9431 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9437 } else if (button == [alert firstOtherButtonIndex]) {
9438 [broken_ removeAllObjects];
9442 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9443 } else if ([context isEqualToString:@"upgrade"]) {
9444 if (button == [alert firstOtherButtonIndex]) {
9445 @synchronized (self) {
9446 for (Package *essential in (id) essential_)
9447 [essential install];
9452 } else if (button == [alert firstOtherButtonIndex] + 1) {
9454 } else if (button == [alert cancelButtonIndex]) {
9458 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9462 - (void) system:(NSString *)command {
9463 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9466 system([command UTF8String]);
9472 - (void) applicationWillSuspend {
9474 [super applicationWillSuspend];
9477 - (BOOL) isSafeToSuspend {
9480 NSLog(@"isSafeToSuspend: locked_ != 0");
9485 if ([tabbar_ modalViewController] != nil)
9488 // Use external process status API internally.
9489 // This is probably a really bad idea.
9490 // XXX: what is the point of this? does this solve anything at all?
9491 uint64_t status = 0;
9493 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9494 notify_get_state(notify_token, &status);
9495 notify_cancel(notify_token);
9500 NSLog(@"isSafeToSuspend: status != 0");
9506 NSLog(@"isSafeToSuspend: -> true");
9511 - (void) applicationSuspend:(__GSEvent *)event {
9512 if ([self isSafeToSuspend])
9513 [super applicationSuspend:event];
9516 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9517 if ([self isSafeToSuspend])
9518 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9521 - (void) _setSuspended:(BOOL)value {
9522 if ([self isSafeToSuspend])
9523 [super _setSuspended:value];
9526 - (UIProgressHUD *) addProgressHUD {
9527 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9528 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9530 [window_ setUserInteractionEnabled:NO];
9532 UIViewController *target(tabbar_);
9533 if (UIViewController *modal = [target modalViewController])
9536 [hud showInView:[target view]];
9542 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9543 [self unlockSuspend];
9545 [hud removeFromSuperview];
9546 [window_ setUserInteractionEnabled:YES];
9549 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9550 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9553 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9554 NSString *scheme([[url scheme] lowercaseString]);
9555 if ([[url absoluteString] length] <= [scheme length] + 3)
9557 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9558 NSArray *components([path componentsSeparatedByString:@"/"]);
9560 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9561 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9562 if (controller != nil)
9563 [controller setDelegate:self];
9567 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9570 NSString *base([components objectAtIndex:0]);
9572 CyteViewController *controller = nil;
9574 if ([base isEqualToString:@"url"]) {
9575 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9576 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9577 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9578 } else if (!external && [components count] == 1) {
9579 if ([base isEqualToString:@"sources"]) {
9580 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9583 if ([base isEqualToString:@"home"]) {
9584 controller = [[[HomeController alloc] init] autorelease];
9587 if ([base isEqualToString:@"sections"]) {
9588 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9591 if ([base isEqualToString:@"search"]) {
9592 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9595 if ([base isEqualToString:@"changes"]) {
9596 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9599 if ([base isEqualToString:@"installed"]) {
9600 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9602 } else if ([components count] == 2) {
9603 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9605 if ([base isEqualToString:@"package"]) {
9606 controller = [self pageForPackage:argument withReferrer:referrer];
9609 if (!external && [base isEqualToString:@"search"]) {
9610 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9613 if (!external && [base isEqualToString:@"sections"]) {
9614 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9616 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9619 if (!external && [base isEqualToString:@"sources"]) {
9620 if ([argument isEqualToString:@"add"]) {
9621 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9622 [(SourcesController *)controller showAddSourcePrompt];
9624 Source *source([database_ sourceWithKey:argument]);
9625 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9629 if (!external && [base isEqualToString:@"launch"]) {
9630 [self launchApplicationWithIdentifier:argument suspended:NO];
9633 } else if (!external && [components count] == 3) {
9634 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9635 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9637 if ([base isEqualToString:@"package"]) {
9638 if ([arg2 isEqualToString:@"settings"]) {
9639 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9640 } else if ([arg2 isEqualToString:@"files"]) {
9641 if (Package *package = [database_ packageWithName:arg1]) {
9642 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9643 [(FileTable *)controller setPackage:package];
9648 if ([base isEqualToString:@"sections"]) {
9649 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9650 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9651 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9655 [controller setDelegate:self];
9659 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9660 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9663 [tabbar_ setUnselectedViewController:page];
9668 - (void) applicationOpenURL:(NSURL *)url {
9669 [super applicationOpenURL:url];
9674 [self openCydiaURL:url forExternal:YES];
9677 - (void) applicationWillResignActive:(UIApplication *)application {
9678 // Stop refreshing if you get a phone call or lock the device.
9679 if ([tabbar_ updating])
9680 [tabbar_ cancelUpdate];
9682 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9683 [super applicationWillResignActive:application];
9686 - (void) saveState {
9687 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9688 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9689 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9695 - (void) applicationWillTerminate:(UIApplication *)application {
9699 - (void) setConfigurationData:(NSString *)data {
9700 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9702 if (!conffile_r(data)) {
9703 lprintf("E:invalid conffile\n");
9707 NSString *ofile = conffile_r[1];
9708 //NSString *nfile = conffile_r[2];
9710 UIAlertView *alert = [[[UIAlertView alloc]
9711 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9712 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9714 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9716 UCLocalize("ACCEPT_NEW_COPY"),
9717 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9721 [alert setContext:@"conffile"];
9722 [alert setNumberOfRows:2];
9726 - (void) addStashController {
9728 stash_ = [[[StashController alloc] init] autorelease];
9729 [window_ addSubview:[stash_ view]];
9732 - (void) removeStashController {
9733 [[stash_ view] removeFromSuperview];
9735 [self unlockSuspend];
9739 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9740 UpdateExternalStatus(1);
9741 _root(true) [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9742 UpdateExternalStatus(0);
9744 [self removeStashController];
9746 pid_t pid(ExecFork());
9748 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9749 perror("launchctl stop");
9755 - (void) setupViewControllers {
9756 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9758 NSMutableArray *items;
9759 if (kCFCoreFoundationVersionNumber < 800) {
9760 items = [NSMutableArray arrayWithObjects:
9761 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9762 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9763 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9764 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9765 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9768 items = [NSMutableArray arrayWithObjects:
9769 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9770 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9771 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9772 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9773 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9777 NSMutableArray *controllers([NSMutableArray array]);
9778 for (UITabBarItem *item in items) {
9779 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9780 [controller setTabBarItem:item];
9781 [controllers addObject:controller];
9783 [tabbar_ setViewControllers:controllers];
9785 [tabbar_ setUpdateDelegate:self];
9788 - (void) _sendMemoryWarningNotification {
9789 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9790 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9792 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9795 - (void) _sendMemoryWarningNotifications {
9797 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9803 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9805 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9808 - (void) applicationDidFinishLaunching:(id)unused {
9809 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9812 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9813 [self setApplicationSupportsShakeToEdit:NO];
9815 @synchronized (HostConfig_) {
9816 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9819 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9820 initWithMemoryCapacity:524288
9821 diskCapacity:10485760
9822 diskPath:Cache("SDURLCache")
9825 [CydiaWebViewController _initialize];
9827 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9829 // this would disallow http{,s} URLs from accessing this data
9830 //[WebView registerURLSchemeAsLocal:@"cydia"];
9832 Font12_ = [UIFont systemFontOfSize:12];
9833 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9834 Font14_ = [UIFont systemFontOfSize:14];
9835 Font18_ = [UIFont systemFontOfSize:18];
9836 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9837 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9839 essential_ = [NSMutableArray arrayWithCapacity:4];
9840 broken_ = [NSMutableArray arrayWithCapacity:4];
9842 // XXX: I really need this thing... like, seriously... I'm sorry
9843 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9845 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9846 [window_ orderFront:self];
9847 [window_ makeKey:self];
9848 [window_ setHidden:NO];
9851 [self addStashController];
9852 // XXX: this would be much cleaner as a yieldToSelector:
9853 // that way the removeStashController could happen right here inline
9854 // we also could no longer require the useless stash_ field anymore
9855 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9860 int error(stat("/", &root));
9861 _assert(error != -1);
9863 #define Stash_(path) do { \
9864 struct stat folder; \
9865 int error(lstat((path), &folder)); \
9866 if (error != -1 && ( \
9867 folder.st_dev == root.st_dev && \
9868 S_ISDIR(folder.st_mode) \
9869 ) || error == -1 && ( \
9870 errno == ENOENT || \
9875 Stash_("/Applications");
9876 Stash_("/Library/Ringtones");
9877 Stash_("/Library/Wallpaper");
9878 //Stash_("/usr/bin");
9879 Stash_("/usr/include");
9880 Stash_("/usr/lib/pam");
9881 Stash_("/usr/share");
9882 //Stash_("/var/lib");
9884 database_ = [Database sharedInstance];
9885 [database_ setDelegate:self];
9887 [window_ setUserInteractionEnabled:NO];
9888 [self setupViewControllers];
9890 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9891 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9892 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9894 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9895 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9896 [emulated_ setSelectedIndex:0];
9898 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9899 [emulated_ concealTabBarSelection];
9901 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9902 [window_ setRootViewController:emulated_];
9904 [window_ addSubview:[emulated_ view]];
9906 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9910 - (NSArray *) defaultStartPages {
9911 NSMutableArray *standard = [NSMutableArray array];
9912 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9913 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9914 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9915 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9916 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9922 if ([emulated_ modalViewController] != nil)
9923 [emulated_ dismissModalViewControllerAnimated:YES];
9924 [window_ setUserInteractionEnabled:NO];
9926 [self reloadDataWithInvocation:nil];
9927 [self refreshIfPossible];
9930 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9931 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9932 int standardIndex = 0;
9933 NSArray *standard = [self defaultStartPages];
9940 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9941 if (valid && closed != nil) {
9942 NSTimeInterval interval([closed timeIntervalSinceNow]);
9943 // XXX: Is 30 minutes the optimal time here?
9944 if (interval <= -(30*60))
9948 if (valid && [saved count] != [standard count])
9952 for (unsigned int i = 0; i < [standard count]; i++) {
9953 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9954 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9955 // but it's good enough for now.
9956 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9963 NSArray *items = nil;
9965 [tabbar_ setSelectedIndex:savedIndex];
9968 [tabbar_ setSelectedIndex:standardIndex];
9972 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9973 NSArray *stack = [items objectAtIndex:tab];
9974 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9975 NSMutableArray *current = [NSMutableArray array];
9977 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9978 NSString *addr = [stack objectAtIndex:nav];
9979 NSURL *url = [NSURL URLWithString:addr];
9980 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9982 [current addObject:page];
9985 [navigation setViewControllers:current];
9988 // (Try to) show the startup URL.
9989 if (starturl_ != nil) {
9990 [self openCydiaURL:starturl_ forExternal:YES];
9995 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9996 if (item != nil && IsWildcat_) {
9997 [sheet showFromBarButtonItem:item animated:YES];
9999 [sheet showInView:window_];
10003 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10004 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10005 [progress setTitle:task];
10006 [progress addProgressEvent:event];
10009 - (void) addProgressEventForTask:(NSArray *)data {
10010 CydiaProgressEvent *event([data objectAtIndex:0]);
10011 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10012 [self addProgressEvent:event forTask:task];
10015 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10016 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10022 id Alloc_(id self, SEL selector) {
10023 id object = alloc_(self, selector);
10024 lprintf("[%s]A-%p\n", self->isa->name, object);
10029 id Dealloc_(id self, SEL selector) {
10030 id object = dealloc_(self, selector);
10031 lprintf("[%s]D-%p\n", self->isa->name, object);
10035 Class $NSURLConnection;
10037 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10038 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10040 NSURL *url([copy URL]);
10042 NSString *host([url host]);
10043 NSString *scheme([[url scheme] lowercaseString]);
10045 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10047 @synchronized (HostConfig_) {
10048 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10049 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10050 [copy setHTTPShouldUsePipelining:YES];
10052 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10053 if ([control isEqualToString:@"max-age=0"])
10054 if ([CachedURLs_ containsObject:url]) {
10056 NSLog(@"~~~: %@", url);
10059 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10061 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10062 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10063 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10067 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10073 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10074 CGSize size([[UIScreen mainScreen] bounds].size);
10075 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10076 if ([$WAKWindow hasLandscapeOrientation])
10077 std::swap(size.width, size.height);*/
10081 Class $NSUserDefaults;
10083 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10084 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10085 return Cache("LocalStorage");
10086 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10089 int main(int argc, char *argv[]) {
10092 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10096 UpdateExternalStatus(0);
10098 UIScreen *screen([UIScreen mainScreen]);
10099 if ([screen respondsToSelector:@selector(scale)])
10100 ScreenScale_ = [screen scale];
10104 UIDevice *device([UIDevice currentDevice]);
10105 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10106 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10107 if (idiom == UIUserInterfaceIdiomPad)
10111 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10113 Pcre pattern("^([0-9]+\\.[0-9]+)");
10115 if (pattern([device systemVersion]))
10116 Firmware_ = pattern[1];
10117 if (pattern(Cydia_))
10118 Major_ = pattern[1];
10120 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10122 HostConfig_ = [[[NSObject alloc] init] autorelease];
10123 @synchronized (HostConfig_) {
10124 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10125 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10126 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10127 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10128 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10131 NSString *ui(@"ui/ios");
10133 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10134 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10135 UI_ = CydiaURL(ui);
10137 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10139 /* Library Hacks {{{ */
10140 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10142 $WAKWindow = objc_getClass("WAKWindow");
10143 if ($WAKWindow != NULL)
10144 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10145 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10147 $NSURLConnection = objc_getClass("NSURLConnection");
10148 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10149 if (NSURLConnection$init$ != NULL) {
10150 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10151 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10154 $NSUserDefaults = objc_getClass("NSUserDefaults");
10155 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10156 if (NSUserDefaults$objectForKey$ != NULL) {
10157 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10158 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10161 /* Set Locale {{{ */
10162 Locale_ = CFLocaleCopyCurrent();
10163 Languages_ = [NSLocale preferredLanguages];
10165 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10166 //NSLog(@"%@", [Languages_ description]);
10169 if (Locale_ != NULL)
10170 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10171 else if (Languages_ != nil && [Languages_ count] != 0)
10172 lang = [[Languages_ objectAtIndex:0] UTF8String];
10174 // XXX: consider just setting to C and then falling through?
10177 if (lang != NULL) {
10178 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10179 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10182 NSLog(@"Setting Language: %s", lang);
10184 if (lang != NULL) {
10185 setenv("LANG", lang, true);
10186 std::setlocale(LC_ALL, lang);
10189 /* Index Collation {{{ */
10190 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10191 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10192 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10193 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10194 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10195 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10197 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10199 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10200 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10201 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})
10202 CollationOffset_.push_back(offset);
10203 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];
10204 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];
10207 CollationThumbs_ = [collation sectionIndexTitles];
10208 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10209 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10211 CollationTitles_ = [collation sectionTitles];
10212 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10214 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10215 if (&transform != NULL && transform != nil) {
10216 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10217 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10218 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10219 UErrorCode code(U_ZERO_ERROR);
10220 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10221 if (!U_SUCCESS(code))
10222 NSLog(@"%s", u_errorName(code));
10226 } @catch (NSException *e) {
10230 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10232 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];
10233 for (NSInteger offset(0); offset != 28; ++offset)
10234 CollationOffset_.push_back(offset);
10236 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];
10237 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];
10241 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10243 /* Parse Arguments {{{ */
10244 bool substrate(false);
10250 for (int argi(1); argi != argc; ++argi)
10251 if (strcmp(argv[argi], "--") == 0) {
10253 argv[argi] = argv[0];
10259 for (int argi(1); argi != arge; ++argi)
10260 if (strcmp(args[argi], "--substrate") == 0)
10263 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10267 App_ = [[NSBundle mainBundle] bundlePath];
10270 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10272 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10273 alloc_ = alloc->method_imp;
10274 alloc->method_imp = (IMP) &Alloc_;*/
10276 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10277 dealloc_ = dealloc->method_imp;
10278 dealloc->method_imp = (IMP) &Dealloc_;*/
10280 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10281 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10283 /* System Information {{{ */
10287 size = sizeof(maxproc);
10288 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10289 perror("sysctlbyname(\"kern.maxproc\", ?)");
10290 else if (maxproc < 64) {
10292 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10293 perror("sysctlbyname(\"kern.maxproc\", #)");
10296 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10297 char *osversion = new char[size];
10298 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10299 perror("sysctlbyname(\"kern.osversion\", ?)");
10301 System_ = [NSString stringWithUTF8String:osversion];
10303 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10304 char *machine = new char[size];
10305 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10306 perror("sysctlbyname(\"hw.machine\", ?)");
10308 Machine_ = machine;
10310 int64_t usermem(0);
10311 size = sizeof(usermem);
10312 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10315 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10316 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10317 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10319 UniqueID_ = UniqueIdentifier(device);
10321 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10322 Product_ = [info objectForKey:@"SafariProductVersion"];
10323 Safari_ = [info objectForKey:@"CFBundleVersion"];
10326 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10328 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10329 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10330 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10331 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10332 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10333 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10335 UserAgent_ = agent;
10337 /* Load Database {{{ */
10339 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10341 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10343 if (Metadata_ == NULL)
10344 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10346 Settings_ = [Metadata_ objectForKey:@"Settings"];
10348 Packages_ = [Metadata_ objectForKey:@"Packages"];
10350 Values_ = [Metadata_ objectForKey:@"Values"];
10351 Sections_ = [Metadata_ objectForKey:@"Sections"];
10352 Sources_ = [Metadata_ objectForKey:@"Sources"];
10354 Token_ = [Metadata_ objectForKey:@"Token"];
10356 Version_ = [Metadata_ objectForKey:@"Version"];
10359 if (Values_ == nil) {
10360 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10361 [Metadata_ setObject:Values_ forKey:@"Values"];
10364 if (Sections_ == nil) {
10365 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10366 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10369 if (Sources_ == nil) {
10370 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10371 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10374 if (Version_ == nil) {
10375 Version_ = [NSNumber numberWithUnsignedInt:0];
10376 [Metadata_ setObject:Version_ forKey:@"Version"];
10379 if ([Version_ unsignedIntValue] == 0) {
10380 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10381 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10382 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10383 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10385 Version_ = [NSNumber numberWithUnsignedInt:1];
10386 [Metadata_ setObject:Version_ forKey:@"Version"];
10388 [Metadata_ removeObjectForKey:@"LastUpdate"];
10393 _H<NSMutableArray> broken([NSMutableArray array]);
10394 for (NSString *key in (id) Sources_)
10395 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10396 [broken addObject:key];
10397 if ([broken count] != 0) {
10398 for (NSString *key in (id) broken)
10399 [Sources_ removeObjectForKey:key];
10404 CydiaWriteSources();
10407 _root(true) MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10410 if (Packages_ != nil) {
10412 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10416 [Metadata_ removeObjectForKey:@"Packages"];
10422 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10424 #define MobileSubstrate_(name) \
10425 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10426 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10427 if (handle == NULL) \
10428 NSLog(@"%s", dlerror()); \
10431 MobileSubstrate_(Activator)
10432 MobileSubstrate_(libstatusbar)
10433 MobileSubstrate_(SimulatedKeyEvents)
10434 MobileSubstrate_(WinterBoard)
10436 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10437 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10439 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10441 _root(true) if (access("/User", F_OK) != 0 || version != 6) {
10443 system("/usr/libexec/cydia/firmware.sh");
10447 if (access("/tmp/cydia.chk", F_OK) == 0) {
10448 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10449 _assert(errno == ENOENT);
10450 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10451 _assert(errno == ENOENT);
10454 /* APT Initialization {{{ */
10455 _assert(pkgInitConfig(*_config));
10456 _assert(pkgInitSystem(*_config, _system));
10459 _config->Set("APT::Acquire::Translation", lang);
10461 // XXX: this timeout might be important :(
10462 //_config->Set("Acquire::http::Timeout", 15);
10464 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10466 mkdir([Cache_ UTF8String], 0755);
10467 mkdir([Cache("archives") UTF8String], 0755);
10468 mkdir([Cache("archives/partial") UTF8String], 0755);
10469 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10471 mkdir([Cache("lists") UTF8String], 0755);
10472 mkdir([Cache("lists/partial") UTF8String], 0755);
10473 mkdir([Cache("periodic") UTF8String], 0755);
10474 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10476 /* Color Choices {{{ */
10477 space_ = CGColorSpaceCreateDeviceRGB();
10479 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10480 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10481 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10482 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10483 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10484 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10485 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10486 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10487 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10488 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10490 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10491 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10493 /* UIKit Configuration {{{ */
10494 // XXX: I have a feeling this was important
10495 //UIKeyboardDisableAutomaticAppearance();
10498 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10500 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10501 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10502 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10504 PulseInterval_ = fast ? 50000 : 500000;
10506 Colon_ = UCLocalize("COLON_DELIMITED");
10507 Elision_ = UCLocalize("ELISION");
10508 Error_ = UCLocalize("ERROR");
10509 Warning_ = UCLocalize("WARNING");
10512 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10514 CGColorSpaceRelease(space_);
10515 CFRelease(Locale_);