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];
3819 OpProgress progress;
3822 _profile(reloadDataWithInvocation$pkgCacheFile)
3823 opened = cache_.Open(progress, false);
3826 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3827 while (!_error->empty()) {
3829 bool warning(!_error->PopMessage(error));
3831 lprintf("cache_.Open():[%s]\n", error.c_str());
3833 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3837 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3838 repair = @selector(configure);
3839 //else if (error == "The package lists or status file could not be parsed or opened.")
3840 // repair = @selector(update);
3841 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3842 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3843 // else if (error == "Malformed Status line")
3844 // else if (error == "The list of sources could not be read.")
3846 if (repair != NULL) {
3848 [delegate_ repairWithSelector:repair];
3857 unlink("/tmp/cydia.chk");
3859 now_ = [[NSDate date] timeIntervalSince1970];
3861 policy_ = new pkgDepCache::Policy();
3862 records_ = new pkgRecords(cache_);
3863 resolver_ = new pkgProblemResolver(cache_);
3864 fetcher_ = new pkgAcquire(&status_);
3867 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3868 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3872 _profile(reloadDataWithInvocation$pkgApplyStatus)
3873 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3877 if (cache_->BrokenCount() != 0) {
3878 _profile(pkgApplyStatus$pkgFixBroken)
3879 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3883 if (cache_->BrokenCount() != 0) {
3884 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3888 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3889 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3894 for (Source *object in (id) sourceList_) {
3895 metaIndex *source([object metaIndex]);
3896 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3897 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3898 // XXX: this could be more intelligent
3899 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3900 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3902 sourceMap_[cached->ID] = object;
3907 /*std::vector<Package *> packages;
3908 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3911 _profile(reloadDataWithInvocation$packageWithIterator)
3912 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3913 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3914 //packages.push_back(package);
3915 CFArrayAppendValue(packages_, CFRetain(package));
3919 /*if (packages.empty())
3920 packages_ = [[NSArray alloc] init];
3922 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3925 _profile(reloadDataWithInvocation$radix$8)
3926 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3929 _profile(reloadDataWithInvocation$radix$4)
3930 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3933 _profile(reloadDataWithInvocation$radix$0)
3934 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3937 _profile(reloadDataWithInvocation$insertion)
3938 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3941 /*_profile(reloadDataWithInvocation$CFQSortArray)
3942 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3945 /*_profile(reloadDataWithInvocation$stdsort)
3946 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3949 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3950 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3953 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3954 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3958 size_t count(CFArrayGetCount(packages_));
3959 MetaFile_->active_ = count;
3960 for (size_t index(0); index != count; ++index)
3961 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3966 @synchronized (self) {
3968 resolver_ = new pkgProblemResolver(cache_);
3970 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3971 if (!cache_[iterator].Keep())
3972 cache_->MarkKeep(iterator, false);
3973 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3974 cache_->SetReInstall(iterator, false);
3977 - (void) configure {
3978 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3980 system([dpkg UTF8String]);
3985 @synchronized (self) {
3986 // XXX: I don't remember this condition
3991 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3993 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3995 if ([self popErrorWithTitle:title])
3999 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4001 CydiaLogCleaner cleaner;
4002 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4009 fetcher_->Shutdown();
4011 pkgRecords records(cache_);
4013 lock_ = new FileFd();
4014 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4016 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4018 if ([self popErrorWithTitle:title])
4022 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4025 manager_ = (_system->CreatePM(cache_));
4026 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4033 bool substrate(RestartSubstrate_);
4034 RestartSubstrate_ = false;
4036 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4038 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4040 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4042 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4043 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4046 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4048 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4050 [self popErrorWithTitle:title];
4054 bool failed = false;
4055 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4056 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4058 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4061 std::string uri = (*item)->DescURI();
4062 std::string error = (*item)->ErrorText;
4064 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4067 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4068 [delegate_ addProgressEventOnMainThread:event forTask:title];
4071 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4079 RestartSubstrate_ = true;
4082 pkgPackageManager::OrderResult result;
4083 _root(true) result = manager_->DoInstall(statusfd_);
4084 if ([self popErrorWithTitle:title])
4087 if (result == pkgPackageManager::Failed) {
4092 if (result != pkgPackageManager::Completed) {
4097 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4099 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4101 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4102 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4105 if (![before isEqualToArray:after])
4110 NSString *title(UCLocalize("UPGRADE"));
4111 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4117 [self updateWithStatus:status_];
4120 - (void) updateWithStatus:(CancelStatus &)status {
4121 NSString *title(UCLocalize("REFRESHING_DATA"));
4124 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4128 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4129 if ([self popErrorWithTitle:title])
4132 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4134 bool success(ListUpdate(status, list, PulseInterval_));
4135 if (status.WasCancelled())
4138 [self popErrorWithTitle:title forOperation:success];
4139 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4143 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4146 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4147 delegate_ = delegate;
4150 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4151 progress_ = delegate;
4152 status_.setDelegate(delegate);
4155 - (NSObject<ProgressDelegate> *) progressDelegate {
4159 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4160 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4161 return i == sourceMap_.end() ? nil : i->second;
4164 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4165 for (Source *source in (id) sourceList_)
4166 [source setFetch:fetch forURI:uri];
4169 - (void) resetFetch {
4170 for (Source *source in (id) sourceList_)
4171 [source resetFetch];
4174 - (NSString *) mappedSectionForPointer:(const char *)section {
4175 _H<NSString> *mapped;
4177 _profile(Database$mappedSectionForPointer$Cache)
4178 mapped = §ions_[section];
4181 if (*mapped == NULL) {
4182 size_t length(strlen(section));
4183 char spaced[length + 1];
4185 _profile(Database$mappedSectionForPointer$Replace)
4186 for (size_t index(0); index != length; ++index)
4187 spaced[index] = section[index] == '_' ? ' ' : section[index];
4188 spaced[length] = '\0';
4193 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4194 string = [NSString stringWithUTF8String:spaced];
4197 _profile(Database$mappedSectionForPointer$Map)
4198 string = [SectionMap_ objectForKey:string] ?: string;
4208 static _H<NSMutableSet> Diversions_;
4210 @interface Diversion : NSObject {
4213 _H<NSString> format_;
4218 @implementation Diversion
4220 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4221 if ((self = [super init]) != nil) {
4222 pattern_ = [from UTF8String];
4228 - (NSString *) divert:(NSString *)url {
4229 return !pattern_(url) ? nil : pattern_->*format_;
4232 + (NSURL *) divertURL:(NSURL *)url {
4234 NSString *href([url absoluteString]);
4236 for (Diversion *diversion in (id) Diversions_)
4237 if (NSString *diverted = [diversion divert:href]) {
4239 NSLog(@"div: %@", diverted);
4241 url = [NSURL URLWithString:diverted];
4248 - (NSString *) key {
4252 - (NSUInteger) hash {
4256 - (BOOL) isEqual:(Diversion *)object {
4257 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4262 @interface CydiaObject : NSObject {
4263 _H<CyteWebViewController> indirect_;
4264 _transient id delegate_;
4267 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4273 @interface CydiaWebViewController : CyteWebViewController {
4274 _H<CydiaObject> cydia_;
4277 + (void) addDiversion:(Diversion *)diversion;
4278 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4279 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4280 - (void) setDelegate:(id)delegate;
4284 /* Web Scripting {{{ */
4285 @implementation CydiaObject
4287 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4288 if ((self = [super init]) != nil) {
4289 indirect_ = (CyteWebViewController *) indirect;
4293 - (void) setDelegate:(id)delegate {
4294 delegate_ = delegate;
4297 + (NSArray *) _attributeKeys {
4298 return [NSArray arrayWithObjects:
4301 @"coreFoundationVersionNumber",
4318 - (NSArray *) attributeKeys {
4319 return [[self class] _attributeKeys];
4322 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4323 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4326 - (NSString *) version {
4330 - (NSString *) build {
4334 - (NSString *) coreFoundationVersionNumber {
4335 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4338 - (NSString *) device {
4339 return UniqueIdentifier();
4342 - (NSString *) firmware {
4343 return [[UIDevice currentDevice] systemVersion];
4346 - (NSString *) hostname {
4347 return [[UIDevice currentDevice] name];
4350 - (NSString *) idiom {
4351 return (id) Idiom_ ?: [NSNull null];
4354 - (NSString *) mcc {
4355 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4356 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4360 - (NSString *) mnc {
4361 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4362 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4366 - (NSString *) operator {
4367 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4368 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4372 - (NSString *) bbsnum {
4373 return (id) BBSNum_ ?: [NSNull null];
4376 - (NSString *) ecid {
4377 return (id) ChipID_ ?: [NSNull null];
4380 - (NSString *) serial {
4381 return SerialNumber_;
4384 - (NSString *) role {
4385 return (id) [NSNull null];
4388 - (NSString *) model {
4389 return [NSString stringWithUTF8String:Machine_];
4392 - (NSString *) token {
4393 return (id) Token_ ?: [NSNull null];
4396 + (NSString *) webScriptNameForSelector:(SEL)selector {
4398 else if (selector == @selector(addBridgedHost:))
4399 return @"addBridgedHost";
4400 else if (selector == @selector(addInsecureHost:))
4401 return @"addInsecureHost";
4402 else if (selector == @selector(addInternalRedirect::))
4403 return @"addInternalRedirect";
4404 else if (selector == @selector(addPipelinedHost:scheme:))
4405 return @"addPipelinedHost";
4406 else if (selector == @selector(addSource:::))
4407 return @"addSource";
4408 else if (selector == @selector(addTokenHost:))
4409 return @"addTokenHost";
4410 else if (selector == @selector(addTrivialSource:))
4411 return @"addTrivialSource";
4412 else if (selector == @selector(close))
4414 else if (selector == @selector(du:))
4416 else if (selector == @selector(stringWithFormat:arguments:))
4418 else if (selector == @selector(getAllSources))
4419 return @"getAllSources";
4420 else if (selector == @selector(getApplicationInfo:value:))
4421 return @"getApplicationInfoValue";
4422 else if (selector == @selector(getKernelNumber:))
4423 return @"getKernelNumber";
4424 else if (selector == @selector(getKernelString:))
4425 return @"getKernelString";
4426 else if (selector == @selector(getInstalledPackages))
4427 return @"getInstalledPackages";
4428 else if (selector == @selector(getIORegistryEntry::))
4429 return @"getIORegistryEntry";
4430 else if (selector == @selector(getLocaleIdentifier))
4431 return @"getLocaleIdentifier";
4432 else if (selector == @selector(getPreferredLanguages))
4433 return @"getPreferredLanguages";
4434 else if (selector == @selector(getPackageById:))
4435 return @"getPackageById";
4436 else if (selector == @selector(getMetadataKeys))
4437 return @"getMetadataKeys";
4438 else if (selector == @selector(getMetadataValue:))
4439 return @"getMetadataValue";
4440 else if (selector == @selector(getSessionValue:))
4441 return @"getSessionValue";
4442 else if (selector == @selector(installPackages:))
4443 return @"installPackages";
4444 else if (selector == @selector(isReachable:))
4445 return @"isReachable";
4446 else if (selector == @selector(localizedStringForKey:value:table:))
4448 else if (selector == @selector(popViewController:))
4449 return @"popViewController";
4450 else if (selector == @selector(refreshSources))
4451 return @"refreshSources";
4452 else if (selector == @selector(registerFrame:))
4453 return @"registerFrame";
4454 else if (selector == @selector(removeButton))
4455 return @"removeButton";
4456 else if (selector == @selector(saveConfig))
4457 return @"saveConfig";
4458 else if (selector == @selector(setMetadataValue::))
4459 return @"setMetadataValue";
4460 else if (selector == @selector(setSessionValue::))
4461 return @"setSessionValue";
4462 else if (selector == @selector(substitutePackageNames:))
4463 return @"substitutePackageNames";
4464 else if (selector == @selector(scrollToBottom:))
4465 return @"scrollToBottom";
4466 else if (selector == @selector(setAllowsNavigationAction:))
4467 return @"setAllowsNavigationAction";
4468 else if (selector == @selector(setBadgeValue:))
4469 return @"setBadgeValue";
4470 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4471 return @"setButtonImage";
4472 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4473 return @"setButtonTitle";
4474 else if (selector == @selector(setHidesBackButton:))
4475 return @"setHidesBackButton";
4476 else if (selector == @selector(setHidesNavigationBar:))
4477 return @"setHidesNavigationBar";
4478 else if (selector == @selector(setNavigationBarStyle:))
4479 return @"setNavigationBarStyle";
4480 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4481 return @"setNavigationBarTintColor";
4482 else if (selector == @selector(setPasteboardString:))
4483 return @"setPasteboardString";
4484 else if (selector == @selector(setPasteboardURL:))
4485 return @"setPasteboardURL";
4486 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4487 return @"setScrollAlwaysBounceVertical";
4488 else if (selector == @selector(setScrollIndicatorStyle:))
4489 return @"setScrollIndicatorStyle";
4490 else if (selector == @selector(setToken:))
4492 else if (selector == @selector(setViewportWidth:))
4493 return @"setViewportWidth";
4494 else if (selector == @selector(statfs:))
4496 else if (selector == @selector(supports:))
4498 else if (selector == @selector(unload))
4504 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4505 return [self webScriptNameForSelector:selector] == nil;
4508 - (BOOL) supports:(NSString *)feature {
4509 return [feature isEqualToString:@"window.open"];
4513 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4516 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4517 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4520 - (void) setScrollIndicatorStyle:(NSString *)style {
4521 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4524 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4525 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4528 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4530 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4531 return (id) [NSNull null];
4532 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4534 return (id) [NSNull null];
4535 return [info objectForKey:key];
4538 - (NSNumber *) getKernelNumber:(NSString *)name {
4539 const char *string([name UTF8String]);
4542 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4543 return (id) [NSNull null];
4545 if (size != sizeof(int))
4546 return (id) [NSNull null];
4549 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4550 return (id) [NSNull null];
4552 return [NSNumber numberWithInt:value];
4555 - (NSString *) getKernelString:(NSString *)name {
4556 const char *string([name UTF8String]);
4559 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4560 return (id) [NSNull null];
4562 char value[size + 1];
4563 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4564 return (id) [NSNull null];
4566 // XXX: just in case you request something ludicrous
4569 return [NSString stringWithCString:value];
4572 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4573 NSObject *value(CYIOGetValue([path UTF8String], entry));
4576 if ([value isKindOfClass:[NSData class]])
4577 value = CYHex((NSData *) value);
4582 - (NSArray *) getMetadataKeys {
4583 @synchronized (Values_) {
4584 return [Values_ allKeys];
4587 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4588 WebFrame *frame([iframe contentFrame]);
4589 [indirect_ registerFrame:frame];
4592 - (id) getMetadataValue:(NSString *)key {
4593 @synchronized (Values_) {
4594 return [Values_ objectForKey:key];
4597 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4598 @synchronized (Values_) {
4599 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4600 [Values_ removeObjectForKey:key];
4602 [Values_ setObject:value forKey:key];
4604 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4607 - (id) getSessionValue:(NSString *)key {
4608 @synchronized (SessionData_) {
4609 return [SessionData_ objectForKey:key];
4612 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4613 @synchronized (SessionData_) {
4614 if (value == (id) [WebUndefined undefined])
4615 [SessionData_ removeObjectForKey:key];
4617 [SessionData_ setObject:value forKey:key];
4620 - (void) addBridgedHost:(NSString *)host {
4621 @synchronized (HostConfig_) {
4622 [BridgedHosts_ addObject:host];
4625 - (void) addInsecureHost:(NSString *)host {
4626 @synchronized (HostConfig_) {
4627 [InsecureHosts_ addObject:host];
4630 - (void) addTokenHost:(NSString *)host {
4631 @synchronized (HostConfig_) {
4632 [TokenHosts_ addObject:host];
4635 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4636 @synchronized (HostConfig_) {
4637 if (scheme != (id) [WebUndefined undefined])
4638 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4640 [PipelinedHosts_ addObject:host];
4643 - (void) popViewController:(NSNumber *)value {
4644 if (value == (id) [WebUndefined undefined])
4645 value = [NSNumber numberWithBool:YES];
4646 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4649 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4650 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4652 for (NSString *section in sections)
4653 [array addObject:section];
4655 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4658 distribution, @"Distribution",
4660 nil] waitUntilDone:NO];
4663 - (void) addTrivialSource:(NSString *)href {
4664 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4667 - (void) refreshSources {
4668 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4671 - (void) saveConfig {
4672 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4675 - (NSArray *) getAllSources {
4676 return [[Database sharedInstance] sources];
4679 - (NSArray *) getInstalledPackages {
4680 Database *database([Database sharedInstance]);
4681 @synchronized (database) {
4682 NSArray *packages([database packages]);
4683 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4684 for (Package *package in packages)
4685 if (![package uninstalled])
4686 [installed addObject:package];
4690 - (Package *) getPackageById:(NSString *)id {
4691 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4695 return (Package *) [NSNull null];
4698 - (NSString *) getLocaleIdentifier {
4699 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4702 - (NSArray *) getPreferredLanguages {
4706 - (NSArray *) statfs:(NSString *)path {
4709 if (path == nil || statfs([path UTF8String], &stat) == -1)
4712 return [NSArray arrayWithObjects:
4713 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4714 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4715 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4719 - (NSNumber *) du:(NSString *)path {
4720 NSNumber *value(nil);
4723 _assert(pipe(fds) != -1);
4725 pid_t pid(ExecFork());
4727 _assert(dup2(fds[1], 1) != -1);
4728 _assert(close(fds[0]) != -1);
4729 _assert(close(fds[1]) != -1);
4730 /* XXX: this should probably not use du */
4731 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4734 _assert(close(fds[1]) != -1);
4736 if (FILE *du = fdopen(fds[0], "r")) {
4738 while (fgets(line, sizeof(line), du) != NULL) {
4739 size_t length(strlen(line));
4740 while (length != 0 && line[length - 1] == '\n')
4741 line[--length] = '\0';
4742 if (char *tab = strchr(line, '\t')) {
4744 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4750 _assert(close(fds[0]) != -1);
4757 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4760 - (NSNumber *) isReachable:(NSString *)name {
4761 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4764 - (void) installPackages:(NSArray *)packages {
4765 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4768 - (NSString *) substitutePackageNames:(NSString *)message {
4769 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4770 for (size_t i(0), e([words count]); i != e; ++i) {
4771 NSString *word([words objectAtIndex:i]);
4772 if (Package *package = [[Database sharedInstance] packageWithName:word])
4773 [words replaceObjectAtIndex:i withObject:[package name]];
4776 return [words componentsJoinedByString:@" "];
4779 - (void) removeButton {
4780 [indirect_ removeButton];
4783 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4784 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4787 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4788 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4791 - (void) setBadgeValue:(id)value {
4792 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4795 - (void) setAllowsNavigationAction:(NSString *)value {
4796 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4799 - (void) setHidesBackButton:(NSString *)value {
4800 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4803 - (void) setHidesNavigationBar:(NSString *)value {
4804 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4807 - (void) setNavigationBarStyle:(NSString *)value {
4808 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4811 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4812 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4813 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4814 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4817 - (void) setPasteboardString:(NSString *)value {
4818 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4821 - (void) setPasteboardURL:(NSString *)value {
4822 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4825 - (void) _setToken:(NSString *)token {
4829 [Metadata_ removeObjectForKey:@"Token"];
4831 [Metadata_ setObject:Token_ forKey:@"Token"];
4836 - (void) setToken:(NSString *)token {
4837 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4840 - (void) scrollToBottom:(NSNumber *)animated {
4841 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4844 - (void) setViewportWidth:(float)width {
4845 [indirect_ setViewportWidthOnMainThread:width];
4848 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4849 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4850 unsigned count([arguments count]);
4852 for (unsigned i(0); i != count; ++i)
4853 values[i] = [arguments objectAtIndex:i];
4854 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4857 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4858 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4860 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4862 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4868 @interface NSURL (CydiaSecure)
4871 @implementation NSURL (CydiaSecure)
4873 - (bool) isCydiaSecure {
4874 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4877 @synchronized (HostConfig_) {
4878 if ([InsecureHosts_ containsObject:[self host]])
4887 /* Cydia Browser Controller {{{ */
4888 @implementation CydiaWebViewController
4890 - (NSURL *) navigationURL {
4891 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4894 + (void) _initialize {
4895 [super _initialize];
4897 Diversions_ = [NSMutableSet setWithCapacity:0];
4900 + (void) addDiversion:(Diversion *)diversion {
4901 [Diversions_ addObject:diversion];
4904 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4905 [super webView:view didClearWindowObject:window forFrame:frame];
4906 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4909 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4910 WebDataSource *source([frame dataSource]);
4911 NSURLResponse *response([source response]);
4912 NSURL *url([response URL]);
4913 NSString *scheme([[url scheme] lowercaseString]);
4915 bool bridged(false);
4917 @synchronized (HostConfig_) {
4918 if ([scheme isEqualToString:@"file"])
4920 else if ([scheme isEqualToString:@"https"])
4921 if ([BridgedHosts_ containsObject:[url host]])
4926 [window setValue:cydia forKey:@"cydia"];
4929 - (void) _setupMail:(MFMailComposeViewController *)controller {
4930 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4932 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4933 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4936 - (NSURL *) URLWithURL:(NSURL *)url {
4937 return [Diversion divertURL:url];
4940 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4941 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4944 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4945 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4947 NSURL *url([copy URL]);
4948 NSString *href([url absoluteString]);
4949 NSString *host([url host]);
4951 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4952 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4953 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4954 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4957 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4958 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4960 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4964 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4965 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4966 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4967 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4972 @synchronized (HostConfig_) {
4973 bridged = [BridgedHosts_ containsObject:host];
4974 token = [TokenHosts_ containsObject:host];
4977 if ([url isCydiaSecure]) {
4979 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4980 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4982 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4983 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4990 - (void) setDelegate:(id)delegate {
4991 [super setDelegate:delegate];
4992 [cydia_ setDelegate:delegate];
4995 - (NSString *) applicationNameForUserAgent {
5000 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5001 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5007 @interface AppCacheController : CydiaWebViewController {
5012 @implementation AppCacheController
5014 - (void) didReceiveMemoryWarning {
5015 // XXX: this doesn't work
5018 - (bool) retainsNetworkActivityIndicator {
5026 @interface NSObject (CydiaScript)
5027 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5030 @implementation NSObject (CydiaScript)
5032 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5038 @implementation NSArray (CydiaScript)
5040 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5041 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5042 for (size_t i(0), e([self count]); i != e; ++i)
5043 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5049 @implementation NSDictionary (CydiaScript)
5051 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5052 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5054 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5061 /* Confirmation Controller {{{ */
5062 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5063 if (!iterator.end())
5064 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5065 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5067 pkgCache::PkgIterator package(dep.TargetPkg());
5070 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5077 @protocol ConfirmationControllerDelegate
5078 - (void) cancelAndClear:(bool)clear;
5079 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5083 @interface ConfirmationController : CydiaWebViewController {
5084 _transient Database *database_;
5086 _H<UIAlertView> essential_;
5088 _H<NSDictionary> changes_;
5089 _H<NSMutableArray> issues_;
5090 _H<NSDictionary> sizes_;
5095 - (id) initWithDatabase:(Database *)database;
5099 @implementation ConfirmationController
5103 RestartSubstrate_ = true;
5104 [delegate_ confirmWithNavigationController:[self navigationController]];
5107 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5108 NSString *context([alert context]);
5110 if ([context isEqualToString:@"remove"]) {
5111 if (button == [alert cancelButtonIndex])
5112 [self dismissModalViewControllerAnimated:YES];
5113 else if (button == [alert firstOtherButtonIndex]) {
5114 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5117 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5118 } else if ([context isEqualToString:@"unable"]) {
5119 [self dismissModalViewControllerAnimated:YES];
5120 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5122 [super alertView:alert clickedButtonAtIndex:button];
5126 - (void) _doContinue {
5127 [delegate_ cancelAndClear:NO];
5128 [self dismissModalViewControllerAnimated:YES];
5131 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5132 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5136 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5137 [super webView:view didClearWindowObject:window forFrame:frame];
5139 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5140 (id) changes_, @"changes",
5141 (id) issues_, @"issues",
5142 (id) sizes_, @"sizes",
5144 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5147 - (id) initWithDatabase:(Database *)database {
5148 if ((self = [super init]) != nil) {
5149 database_ = database;
5151 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5152 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5153 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5154 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5155 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5159 pkgCacheFile &cache([database_ cache]);
5160 NSArray *packages([database_ packages]);
5161 pkgDepCache::Policy *policy([database_ policy]);
5163 issues_ = [NSMutableArray arrayWithCapacity:4];
5165 for (Package *package in packages) {
5166 pkgCache::PkgIterator iterator([package iterator]);
5167 NSString *name([package id]);
5169 if ([package broken]) {
5170 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5172 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5174 reasons, @"reasons",
5177 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5181 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5182 pkgCache::DepIterator start;
5183 pkgCache::DepIterator end;
5184 dep.GlobOr(start, end); // ++dep
5186 if (!cache->IsImportantDep(end))
5188 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5191 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5193 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5194 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5195 clauses, @"clauses",
5199 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5201 pkgCache::PkgIterator target(start.TargetPkg());
5202 if (target->ProvidesList != 0)
5203 reason = @"missing";
5205 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5207 reason = @"installed";
5208 installed = [NSString stringWithUTF8String:ver.VerStr()];
5209 } else if (!cache[target].CandidateVerIter(cache).end())
5210 reason = @"uninstalled";
5211 else if (target->ProvidesList == 0)
5212 reason = @"uninstallable";
5214 reason = @"virtual";
5217 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5218 [NSString stringWithUTF8String:start.CompType()], @"operator",
5219 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5222 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5223 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5224 version, @"version",
5226 installed, @"installed",
5229 // yes, seriously. (wtf?)
5237 pkgDepCache::StateCache &state(cache[iterator]);
5239 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5241 if (state.NewInstall())
5242 [installs addObject:name];
5243 // XXX: else if (state.Install())
5244 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5245 [reinstalls addObject:name];
5246 // XXX: move before previous if
5247 else if (state.Upgrade())
5248 [upgrades addObject:name];
5249 else if (state.Downgrade())
5250 [downgrades addObject:name];
5251 else if (!state.Delete())
5252 // XXX: _assert(state.Keep());
5254 else if (special_r(name))
5255 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5256 [NSNull null], @"package",
5257 [NSArray arrayWithObjects:
5258 [NSDictionary dictionaryWithObjectsAndKeys:
5259 @"Conflicts", @"relationship",
5260 [NSArray arrayWithObjects:
5261 [NSDictionary dictionaryWithObjectsAndKeys:
5263 [NSNull null], @"version",
5264 @"installed", @"reason",
5271 if ([package essential])
5273 [removes addObject:name];
5276 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5277 substrate_ |= DepSubstrate(iterator.CurrentVer());
5282 else if (Advanced_) {
5283 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5285 essential_ = [[[UIAlertView alloc]
5286 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5287 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5289 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5291 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5295 [essential_ setContext:@"remove"];
5296 [essential_ setNumberOfRows:2];
5298 essential_ = [[[UIAlertView alloc]
5299 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5300 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5302 cancelButtonTitle:UCLocalize("OKAY")
5303 otherButtonTitles:nil
5306 [essential_ setContext:@"unable"];
5309 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5310 installs, @"installs",
5311 reinstalls, @"reinstalls",
5312 upgrades, @"upgrades",
5313 downgrades, @"downgrades",
5314 removes, @"removes",
5317 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5318 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5319 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5322 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5326 - (UIBarButtonItem *) leftButton {
5327 return [[[UIBarButtonItem alloc]
5328 initWithTitle:UCLocalize("CANCEL")
5329 style:UIBarButtonItemStylePlain
5331 action:@selector(cancelButtonClicked)
5336 - (void) applyRightButton {
5337 if ([issues_ count] == 0 && ![self isLoading])
5338 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5339 initWithTitle:UCLocalize("CONFIRM")
5340 style:UIBarButtonItemStyleDone
5342 action:@selector(confirmButtonClicked)
5345 [[self navigationItem] setRightBarButtonItem:nil];
5349 - (void) cancelButtonClicked {
5350 [delegate_ cancelAndClear:YES];
5351 [self dismissModalViewControllerAnimated:YES];
5355 - (void) confirmButtonClicked {
5356 if (essential_ != nil)
5366 /* Progress Data {{{ */
5367 @interface CydiaProgressData : NSObject {
5368 _transient id delegate_;
5377 _H<NSMutableArray> events_;
5378 _H<NSString> title_;
5380 _H<NSString> status_;
5381 _H<NSString> finish_;
5386 @implementation CydiaProgressData
5388 + (NSArray *) _attributeKeys {
5389 return [NSArray arrayWithObjects:
5401 - (NSArray *) attributeKeys {
5402 return [[self class] _attributeKeys];
5405 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5406 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5410 if ((self = [super init]) != nil) {
5411 events_ = [NSMutableArray arrayWithCapacity:32];
5419 - (void) setDelegate:(id)delegate {
5420 delegate_ = delegate;
5423 - (void) setPercent:(float)value {
5427 - (NSNumber *) percent {
5428 return [NSNumber numberWithFloat:percent_];
5431 - (void) setCurrent:(float)value {
5435 - (NSNumber *) current {
5436 return [NSNumber numberWithFloat:current_];
5439 - (void) setTotal:(float)value {
5443 - (NSNumber *) total {
5444 return [NSNumber numberWithFloat:total_];
5447 - (void) setSpeed:(float)value {
5451 - (NSNumber *) speed {
5452 return [NSNumber numberWithFloat:speed_];
5455 - (NSArray *) events {
5459 - (void) removeAllEvents {
5460 [events_ removeAllObjects];
5463 - (void) addEvent:(CydiaProgressEvent *)event {
5464 [events_ addObject:event];
5467 - (void) setTitle:(NSString *)text {
5471 - (NSString *) title {
5475 - (void) setFinish:(NSString *)text {
5479 - (NSString *) finish {
5480 return (id) finish_ ?: [NSNull null];
5483 - (void) setRunning:(bool)running {
5487 - (NSNumber *) running {
5488 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5493 /* Progress Controller {{{ */
5494 @interface ProgressController : CydiaWebViewController <
5497 _transient Database *database_;
5498 _H<CydiaProgressData, 1> progress_;
5502 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5504 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5506 - (void) setTitle:(NSString *)title;
5507 - (void) setCancellable:(bool)cancellable;
5511 @implementation ProgressController
5514 [database_ setProgressDelegate:nil];
5518 - (UIBarButtonItem *) leftButton {
5519 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5520 initWithTitle:UCLocalize("CANCEL")
5521 style:UIBarButtonItemStylePlain
5523 action:@selector(cancel)
5524 ] autorelease] : nil;
5527 - (void) updateCancel {
5528 [super applyLeftButton];
5531 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5532 if ((self = [super init]) != nil) {
5533 database_ = database;
5534 delegate_ = delegate;
5536 [database_ setProgressDelegate:self];
5538 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5539 [progress_ setDelegate:self];
5541 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5543 [scroller_ setBackgroundColor:[UIColor blackColor]];
5545 [[self navigationItem] setHidesBackButton:YES];
5547 [self updateCancel];
5551 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5552 [super webView:view didClearWindowObject:window forFrame:frame];
5553 [window setValue:progress_ forKey:@"cydiaProgress"];
5556 - (void) updateProgress {
5557 [self dispatchEvent:@"CydiaProgressUpdate"];
5560 - (void) viewWillAppear:(BOOL)animated {
5561 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5562 [super viewWillAppear:animated];
5565 - (void) reloadSpringBoard {
5566 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5567 system("/bin/launchctl stop com.apple.backboardd");
5569 system("/usr/bin/killall backboardd SpringBoard sbreload");
5573 pid_t pid(ExecFork());
5578 pid_t pid(ExecFork());
5580 execl("/usr/bin/sbreload", "sbreload", NULL);
5590 system("/usr/bin/killall backboardd SpringBoard sbreload");
5594 UpdateExternalStatus(0);
5597 [delegate_ saveState];
5601 [delegate_ returnToCydia];
5605 [delegate_ terminateWithSuccess];
5606 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5607 [delegate_ suspendWithAnimation:YES];
5609 [delegate_ suspend];*/
5621 UIProgressHUD *hud([delegate_ addProgressHUD]);
5622 [hud setText:UCLocalize("LOADING")];
5623 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5629 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5630 SBReboot(SBSSpringBoardServerPort());
5632 reboot2(RB_AUTOBOOT);
5639 - (void) setTitle:(NSString *)title {
5640 [progress_ setTitle:title];
5641 [self updateProgress];
5644 - (UIBarButtonItem *) rightButton {
5645 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5646 initWithTitle:UCLocalize("CLOSE")
5647 style:UIBarButtonItemStylePlain
5649 action:@selector(close)
5653 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5654 UpdateExternalStatus(1);
5656 [progress_ setRunning:true];
5657 [self setTitle:title];
5658 // implicit updateProgress
5660 SHA1SumValue notifyconf; {
5662 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5665 MMap mmap(file, MMap::ReadOnly);
5667 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5668 notifyconf = sha1.Result();
5672 SHA1SumValue springlist; {
5674 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5677 MMap mmap(file, MMap::ReadOnly);
5679 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5680 springlist = sha1.Result();
5684 if (invocation != nil) {
5685 [invocation yieldToSelector:@selector(invoke)];
5686 [self setTitle:@"COMPLETE"];
5691 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5694 MMap mmap(file, MMap::ReadOnly);
5696 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5697 if (!(notifyconf == sha1.Result()))
5704 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5707 MMap mmap(file, MMap::ReadOnly);
5709 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5710 if (!(springlist == sha1.Result()))
5716 if (RestartSubstrate_)
5720 RestartSubstrate_ = false;
5723 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5724 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5725 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5726 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5727 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5730 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5732 [progress_ setRunning:false];
5733 [self updateProgress];
5735 [self applyRightButton];
5738 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5739 [progress_ addEvent:event];
5740 [self updateProgress];
5743 - (bool) isProgressCancelled {
5744 return cancel_ == 2;
5749 [self updateCancel];
5752 - (void) setCancellable:(bool)cancellable {
5753 unsigned cancel(cancel_);
5757 else if (cancel_ == 0)
5760 if (cancel != cancel_)
5761 [self updateCancel];
5764 - (void) setProgressCancellable:(NSNumber *)cancellable {
5765 [self setCancellable:[cancellable boolValue]];
5768 - (void) setProgressPercent:(NSNumber *)percent {
5769 [progress_ setPercent:[percent floatValue]];
5770 [self updateProgress];
5773 - (void) setProgressStatus:(NSDictionary *)status {
5774 if (status == nil) {
5775 [progress_ setCurrent:0];
5776 [progress_ setTotal:0];
5777 [progress_ setSpeed:0];
5779 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5781 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5782 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5783 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5786 [self updateProgress];
5792 /* Package Cell {{{ */
5793 @interface PackageCell : CyteTableViewCell <
5794 CyteTableViewCellDelegate
5798 _H<NSString> description_;
5800 _H<NSString> source_;
5802 _H<UIImage> placard_;
5806 - (PackageCell *) init;
5807 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5809 - (void) drawContentRect:(CGRect)rect;
5813 @implementation PackageCell
5815 - (PackageCell *) init {
5816 CGRect frame(CGRectMake(0, 0, 320, 74));
5817 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5818 UIView *content([self contentView]);
5819 CGRect bounds([content bounds]);
5821 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5822 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5823 [content addSubview:content_];
5825 [content_ setDelegate:self];
5826 [content_ setOpaque:YES];
5830 - (NSString *) accessibilityLabel {
5834 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5835 summarized_ = summary;
5845 [content_ setBackgroundColor:[UIColor whiteColor]];
5849 Source *source = [package source];
5851 icon_ = [package icon];
5853 if (NSString *name = [package name])
5854 name_ = [NSString stringWithString:name];
5856 if (NSString *description = [package shortDescription])
5857 description_ = [NSString stringWithString:description];
5859 commercial_ = [package isCommercial];
5861 NSString *label = nil;
5862 bool trusted = false;
5864 if (source != nil) {
5865 label = [source label];
5866 trusted = [source trusted];
5867 } else if ([[package id] isEqualToString:@"firmware"])
5868 label = UCLocalize("APPLE");
5870 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5872 NSString *from(label);
5874 NSString *section = [package simpleSection];
5875 if (section != nil && ![section isEqualToString:label]) {
5876 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5877 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5880 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5882 if (NSString *purpose = [package primaryPurpose])
5883 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5888 if (NSString *mode = [package mode]) {
5889 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5890 color = RemovingColor_;
5891 placard = @"removing";
5893 color = InstallingColor_;
5894 placard = @"installing";
5897 color = [UIColor whiteColor];
5899 if ([package installed] != nil)
5900 placard = @"installed";
5905 [content_ setBackgroundColor:color];
5908 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5911 [self setNeedsDisplay];
5912 [content_ setNeedsDisplay];
5915 - (void) drawSummaryContentRect:(CGRect)rect {
5916 bool highlighted(highlighted_);
5917 float width([self bounds].size.width);
5921 rect.size = [(UIImage *) icon_ size];
5923 while (rect.size.width > 16 || rect.size.height > 16) {
5924 rect.size.width /= 2;
5925 rect.size.height /= 2;
5928 rect.origin.x = 19 - rect.size.width / 2;
5929 rect.origin.y = 19 - rect.size.height / 2;
5931 [icon_ drawInRect:Retina(rect)];
5934 if (badge_ != nil) {
5936 rect.size = [(UIImage *) badge_ size];
5938 rect.size.width /= 4;
5939 rect.size.height /= 4;
5941 rect.origin.x = 25 - rect.size.width / 2;
5942 rect.origin.y = 25 - rect.size.height / 2;
5944 [badge_ drawInRect:Retina(rect)];
5947 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5951 UISetColor(commercial_ ? Purple_ : Black_);
5952 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5954 if (placard_ != nil)
5955 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5958 - (void) drawNormalContentRect:(CGRect)rect {
5959 bool highlighted(highlighted_);
5960 float width([self bounds].size.width);
5964 rect.size = [(UIImage *) icon_ size];
5966 while (rect.size.width > 32 || rect.size.height > 32) {
5967 rect.size.width /= 2;
5968 rect.size.height /= 2;
5971 rect.origin.x = 25 - rect.size.width / 2;
5972 rect.origin.y = 25 - rect.size.height / 2;
5974 [icon_ drawInRect:Retina(rect)];
5977 if (badge_ != nil) {
5979 rect.size = [(UIImage *) badge_ size];
5981 rect.size.width /= 2;
5982 rect.size.height /= 2;
5984 rect.origin.x = 36 - rect.size.width / 2;
5985 rect.origin.y = 36 - rect.size.height / 2;
5987 [badge_ drawInRect:Retina(rect)];
5990 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5994 UISetColor(commercial_ ? Purple_ : Black_);
5995 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5996 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5999 UISetColor(commercial_ ? Purplish_ : Gray_);
6000 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6002 if (placard_ != nil)
6003 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6006 - (void) drawContentRect:(CGRect)rect {
6008 [self drawSummaryContentRect:rect];
6010 [self drawNormalContentRect:rect];
6015 /* Section Cell {{{ */
6016 @interface SectionCell : CyteTableViewCell <
6017 CyteTableViewCellDelegate
6019 _H<NSString> basic_;
6020 _H<NSString> section_;
6022 _H<NSString> count_;
6024 _H<UISwitch> switch_;
6028 - (void) setSection:(Section *)section editing:(BOOL)editing;
6032 @implementation SectionCell
6034 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6035 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6036 icon_ = [UIImage imageNamed:@"folder.png"];
6037 // XXX: this initial frame is wrong, but is fixed later
6038 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6039 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6041 UIView *content([self contentView]);
6042 CGRect bounds([content bounds]);
6044 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6045 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6046 [content addSubview:content_];
6047 [content_ setBackgroundColor:[UIColor whiteColor]];
6049 [content_ setDelegate:self];
6053 - (void) onSwitch:(id)sender {
6054 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6055 if (metadata == nil) {
6056 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6057 [Sections_ setObject:metadata forKey:basic_];
6060 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6064 - (void) setSection:(Section *)section editing:(BOOL)editing {
6065 if (editing != editing_) {
6067 [switch_ removeFromSuperview];
6069 [self addSubview:switch_];
6078 if (section == nil) {
6079 name_ = UCLocalize("ALL_PACKAGES");
6082 basic_ = [section name];
6083 section_ = [section localized];
6085 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6086 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6089 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6092 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6093 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6095 [content_ setNeedsDisplay];
6098 - (void) setFrame:(CGRect)frame {
6099 [super setFrame:frame];
6101 CGRect rect([switch_ frame]);
6102 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6105 - (NSString *) accessibilityLabel {
6109 - (void) drawContentRect:(CGRect)rect {
6110 bool highlighted(highlighted_ && !editing_);
6112 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6114 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6117 float width(rect.size.width);
6119 width -= 9 + [switch_ frame].size.width;
6123 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6125 CGSize size = [count_ sizeWithFont:Font14_];
6127 UISetColor(Folder_);
6129 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6135 /* File Table {{{ */
6136 @interface FileTable : CyteViewController <
6137 UITableViewDataSource,
6140 _transient Database *database_;
6141 _H<Package> package_;
6143 _H<NSMutableArray> files_;
6144 _H<UITableView, 2> list_;
6147 - (id) initWithDatabase:(Database *)database;
6148 - (void) setPackage:(Package *)package;
6152 @implementation FileTable
6154 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6155 return files_ == nil ? 0 : [files_ count];
6158 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6162 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6163 static NSString *reuseIdentifier = @"Cell";
6165 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6167 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6168 [cell setFont:[UIFont systemFontOfSize:16]];
6170 [cell setText:[files_ objectAtIndex:indexPath.row]];
6171 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6176 - (NSURL *) navigationURL {
6177 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6181 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6182 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6183 [list_ setRowHeight:24.0f];
6184 [(UITableView *) list_ setDataSource:self];
6185 [list_ setDelegate:self];
6186 [self setView:list_];
6189 - (void) viewDidLoad {
6190 [super viewDidLoad];
6192 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6195 - (void) releaseSubviews {
6201 [super releaseSubviews];
6204 - (id) initWithDatabase:(Database *)database {
6205 if ((self = [super init]) != nil) {
6206 database_ = database;
6210 - (void) setPackage:(Package *)package {
6214 files_ = [NSMutableArray arrayWithCapacity:32];
6216 if (package != nil) {
6218 name_ = [package id];
6220 if (NSArray *files = [package files])
6221 [files_ addObjectsFromArray:files];
6223 if ([files_ count] != 0) {
6224 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6225 [files_ removeObjectAtIndex:0];
6226 [files_ sortUsingSelector:@selector(compareByPath:)];
6228 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6229 [stack addObject:@"/"];
6231 for (int i(0), e([files_ count]); i != e; ++i) {
6232 NSString *file = [files_ objectAtIndex:i];
6233 while (![file hasPrefix:[stack lastObject]])
6234 [stack removeLastObject];
6235 NSString *directory = [stack lastObject];
6236 [stack addObject:[file stringByAppendingString:@"/"]];
6237 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6238 ([stack count] - 2) * 3, "",
6239 [file substringFromIndex:[directory length]]
6248 - (void) reloadData {
6251 [self setPackage:[database_ packageWithName:name_]];
6256 /* Package Controller {{{ */
6257 @interface CYPackageController : CydiaWebViewController <
6258 UIActionSheetDelegate
6260 _transient Database *database_;
6261 _H<Package> package_;
6264 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6265 _H<UIBarButtonItem> button_;
6268 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6272 @implementation CYPackageController
6274 - (NSURL *) navigationURL {
6275 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6278 - (void) _clickButtonWithName:(NSString *)name {
6279 if ([name isEqualToString:@"CLEAR"])
6280 [delegate_ clearPackage:package_];
6281 else if ([name isEqualToString:@"INSTALL"])
6282 [delegate_ installPackage:package_];
6283 else if ([name isEqualToString:@"REINSTALL"])
6284 [delegate_ installPackage:package_];
6285 else if ([name isEqualToString:@"REMOVE"])
6286 [delegate_ removePackage:package_];
6287 else if ([name isEqualToString:@"UPGRADE"])
6288 [delegate_ installPackage:package_];
6289 else _assert(false);
6292 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6293 NSString *context([sheet context]);
6295 if ([context isEqualToString:@"modify"]) {
6296 if (button != [sheet cancelButtonIndex]) {
6297 [self _clickButtonWithName:buttons_[button].first];
6300 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6304 - (bool) _allowJavaScriptPanel {
6309 - (void) _customButtonClicked {
6310 size_t count(buttons_.size());
6315 [self _clickButtonWithName:buttons_[0].first];
6317 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6318 for (const auto &button : buttons_)
6319 [buttons addObject:button.second];
6321 UIActionSheet *sheet = [[[UIActionSheet alloc]
6324 cancelButtonTitle:nil
6325 destructiveButtonTitle:nil
6326 otherButtonTitles:nil
6329 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6331 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6332 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6334 [sheet setContext:@"modify"];
6336 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6340 - (void) reloadButtonClicked {
6341 if (commercial_ && function_ == nil && [package_ uninstalled])
6343 [self customButtonClicked];
6346 - (void) applyLoadingTitle {
6347 // Don't show "Loading" as the title. Ever.
6350 - (UIBarButtonItem *) rightButton {
6355 - (void) setPageColor:(UIColor *)color {
6356 return [super setPageColor:nil];
6359 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6360 if ((self = [super init]) != nil) {
6361 database_ = database;
6362 name_ = name == nil ? @"" : [NSString stringWithString:name];
6363 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6367 - (void) reloadData {
6370 package_ = [database_ packageWithName:name_];
6374 if (package_ != nil) {
6375 [(Package *) package_ parse];
6377 commercial_ = [package_ isCommercial];
6379 if ([package_ mode] != nil)
6380 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6381 if ([package_ source] == nil);
6382 else if ([package_ upgradableAndEssential:NO])
6383 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6384 else if ([package_ uninstalled])
6385 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6387 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6388 if (![package_ uninstalled])
6389 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6393 switch (buttons_.size()) {
6394 case 0: title = nil; break;
6395 case 1: title = buttons_[0].second; break;
6396 default: title = UCLocalize("MODIFY"); break;
6399 button_ = [[[UIBarButtonItem alloc]
6401 style:UIBarButtonItemStylePlain
6403 action:@selector(customButtonClicked)
6407 - (bool) isLoading {
6408 return commercial_ ? [super isLoading] : false;
6414 /* Package List Controller {{{ */
6415 @interface PackageListController : CyteViewController <
6416 UITableViewDataSource,
6419 _transient Database *database_;
6421 _H<NSArray> packages_;
6422 _H<NSArray> sections_;
6423 _H<UITableView, 2> list_;
6425 _H<NSArray> thumbs_;
6426 std::vector<NSInteger> offset_;
6428 _H<NSString> title_;
6429 unsigned reloading_;
6432 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6433 - (void) setDelegate:(id)delegate;
6434 - (void) resetCursor;
6437 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6441 @implementation PackageListController
6443 - (NSURL *) referrerURL {
6444 return [self navigationURL];
6447 - (bool) isSummarized {
6451 - (bool) showsSections {
6455 - (void) deselectWithAnimation:(BOOL)animated {
6456 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6459 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6460 CGRect base = [[self view] bounds];
6461 base.size.height -= bounds.size.height;
6462 base.origin = [list_ frame].origin;
6464 [UIView beginAnimations:nil context:NULL];
6465 [UIView setAnimationBeginsFromCurrentState:YES];
6466 [UIView setAnimationCurve:curve];
6467 [UIView setAnimationDuration:duration];
6468 [list_ setFrame:base];
6469 [UIView commitAnimations];
6472 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6473 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6476 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6477 [self resizeForKeyboardBounds:bounds duration:0];
6480 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6481 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6482 *curve = UIViewAnimationCurveEaseInOut;
6484 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6486 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6489 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6492 - (void) keyboardWillShow:(NSNotification *)notification {
6495 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6496 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6498 NSTimeInterval duration;
6499 UIViewAnimationCurve curve;
6500 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6502 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6503 UIViewController *base = self;
6504 while ([base parentOrPresentingViewController] != nil)
6505 base = [base parentOrPresentingViewController];
6506 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6507 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6509 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6510 intersection.size.height += CYStatusBarHeight();
6512 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6515 - (void) keyboardWillHide:(NSNotification *)notification {
6516 NSTimeInterval duration;
6517 UIViewAnimationCurve curve;
6518 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6520 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6523 - (void) viewWillAppear:(BOOL)animated {
6524 [super viewWillAppear:animated];
6526 [self resizeForKeyboardBounds:CGRectZero];
6527 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6528 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6531 - (void) viewWillDisappear:(BOOL)animated {
6532 [super viewWillDisappear:animated];
6534 [self resizeForKeyboardBounds:CGRectZero];
6535 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6536 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6539 - (void) viewDidAppear:(BOOL)animated {
6540 [super viewDidAppear:animated];
6541 [self deselectWithAnimation:animated];
6544 - (void) didSelectPackage:(Package *)package {
6545 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6546 [view setDelegate:delegate_];
6547 [[self navigationController] pushViewController:view animated:YES];
6550 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6551 NSInteger count([sections_ count]);
6552 return count == 0 ? 1 : count;
6555 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6556 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6558 return [[sections_ objectAtIndex:section] name];
6561 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6562 if ([sections_ count] == 0)
6564 return [[sections_ objectAtIndex:section] count];
6567 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6568 @synchronized (database_) {
6569 if ([database_ era] != era_)
6572 Section *section([sections_ objectAtIndex:[path section]]);
6573 NSInteger row([path row]);
6574 Package *package([packages_ objectAtIndex:([section row] + row)]);
6575 return [[package retain] autorelease];
6578 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6579 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6581 cell = [[[PackageCell alloc] init] autorelease];
6583 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6584 [cell setPackage:package asSummary:[self isSummarized]];
6588 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6589 Package *package([self packageAtIndexPath:path]);
6590 package = [database_ packageWithName:[package id]];
6591 [self didSelectPackage:package];
6594 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6598 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6599 return offset_[index];
6602 - (void) updateHeight {
6603 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6606 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6607 if ((self = [super init]) != nil) {
6608 database_ = database;
6609 title_ = [title copy];
6610 [[self navigationItem] setTitle:title_];
6615 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6616 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6617 [self setView:view];
6619 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6620 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6621 [view addSubview:list_];
6623 // XXX: is 20 the most optimal number here?
6624 [list_ setSectionIndexMinimumDisplayRowCount:20];
6626 [(UITableView *) list_ setDataSource:self];
6627 [list_ setDelegate:self];
6629 [self updateHeight];
6632 - (void) releaseSubviews {
6641 [super releaseSubviews];
6644 - (void) setDelegate:(id)delegate {
6645 delegate_ = delegate;
6648 - (bool) shouldYield {
6652 - (bool) shouldBlock {
6656 - (NSMutableArray *) _reloadPackages {
6657 @synchronized (database_) {
6658 era_ = [database_ era];
6659 NSArray *packages([database_ packages]);
6661 return [NSMutableArray arrayWithArray:packages];
6664 - (void) _reloadData {
6665 if (reloading_ != 0) {
6670 NSMutableArray *packages;
6673 if ([self shouldYield]) {
6677 if (![self shouldBlock])
6680 hud = [delegate_ addProgressHUD];
6681 [hud setText:UCLocalize("LOADING")];
6685 packages = [self yieldToSelector:@selector(_reloadPackages)];
6688 [delegate_ removeProgressHUD:hud];
6689 } while (reloading_ == 2);
6691 packages = [self _reloadPackages];
6694 @synchronized (database_) {
6695 if (era_ != [database_ era])
6702 packages_ = packages;
6704 if ([self showsSections])
6705 sections_ = [self sectionsForPackages:packages];
6707 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6708 [section setCount:[packages_ count]];
6709 sections_ = [NSArray arrayWithObject:section];
6712 [self updateHeight];
6714 _profile(PackageTable$reloadData$List)
6715 [(UITableView *) list_ setDataSource:self];
6723 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6724 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6725 size_t end([packages count]);
6727 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6728 Section *section(prefix);
6730 thumbs_ = CollationThumbs_;
6731 offset_ = CollationOffset_;
6734 size_t offsets([CollationStarts_ count]);
6736 NSString *start([CollationStarts_ objectAtIndex:offset]);
6737 size_t length([start length]);
6739 for (size_t index(0); index != end; ++index) {
6741 Package *package([packages objectAtIndex:index]);
6742 NSString *name(PackageName(package, @selector(cyname)));
6744 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6745 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6746 NSString *title([CollationTitles_ objectAtIndex:offset]);
6747 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6748 [sections addObject:section];
6750 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6753 length = [start length];
6757 [section addToCount];
6760 for (; offset != offsets; ++offset) {
6761 NSString *title([CollationTitles_ objectAtIndex:offset]);
6762 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6763 [sections addObject:section];
6766 if ([prefix count] != 0) {
6767 Section *suffix([sections lastObject]);
6768 [prefix setName:[suffix name]];
6769 [suffix setName:nil];
6770 [sections insertObject:prefix atIndex:(offsets - 1)];
6776 - (void) reloadData {
6779 if ([self shouldYield])
6780 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6785 - (void) resetCursor {
6786 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6789 - (void) clearData {
6790 [self updateHeight];
6792 [list_ setDataSource:nil];
6800 /* Filtered Package List Controller {{{ */
6801 typedef Function<bool, Package *> PackageFilter;
6802 typedef Function<void, NSMutableArray *> PackageSorter;
6803 @interface FilteredPackageListController : PackageListController {
6804 PackageFilter filter_;
6805 PackageSorter sorter_;
6808 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6810 - (void) setFilter:(PackageFilter)filter;
6811 - (void) setSorter:(PackageSorter)sorter;
6815 @implementation FilteredPackageListController
6817 - (void) setFilter:(PackageFilter)filter {
6818 @synchronized (self) {
6822 - (void) setSorter:(PackageSorter)sorter {
6823 @synchronized (self) {
6827 - (NSMutableArray *) _reloadPackages {
6828 @synchronized (database_) {
6829 era_ = [database_ era];
6831 NSArray *packages([database_ packages]);
6832 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6834 PackageFilter filter;
6835 PackageSorter sorter;
6837 @synchronized (self) {
6842 _profile(PackageTable$reloadData$Filter)
6843 for (Package *package in packages)
6844 if ([package valid] && filter(package))
6845 [filtered addObject:package];
6853 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6854 if ((self = [super initWithDatabase:database title:title]) != nil) {
6855 [self setFilter:filter];
6862 /* Home Controller {{{ */
6863 @interface HomeController : CydiaWebViewController {
6864 CFRunLoopRef runloop_;
6865 SCNetworkReachabilityRef reachability_;
6870 @implementation HomeController
6872 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6873 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6877 if ((self = [super init]) != nil) {
6878 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6881 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6882 if (reachability_ != NULL) {
6883 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6884 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6886 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6887 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6894 if (reachability_ != NULL && runloop_ != NULL)
6895 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6899 - (NSURL *) navigationURL {
6900 return [NSURL URLWithString:@"cydia://home"];
6903 - (void) aboutButtonClicked {
6904 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6906 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6907 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6908 [alert setCancelButtonIndex:0];
6911 @"Copyright \u00a9 2008-2014\n"
6914 "Jay Freeman (saurik)\n"
6915 "saurik@saurik.com\n"
6916 "http://www.saurik.com/"
6922 - (UIBarButtonItem *) leftButton {
6923 return [[[UIBarButtonItem alloc]
6924 initWithTitle:UCLocalize("ABOUT")
6925 style:UIBarButtonItemStylePlain
6927 action:@selector(aboutButtonClicked)
6934 /* Cydia Navigation Controller Interface {{{ */
6935 @interface UINavigationController (Cydia)
6937 - (NSArray *) navigationURLCollection;
6938 - (void) unloadData;
6943 /* Cydia Tab Bar Controller {{{ */
6944 @interface CydiaTabBarController : CyteTabBarController <
6945 UITabBarControllerDelegate,
6948 _transient Database *database_;
6950 _H<UIActivityIndicatorView> indicator_;
6953 // XXX: ok, "updatedelegate_"?...
6954 _transient NSObject<CydiaDelegate> *updatedelegate_;
6957 - (NSArray *) navigationURLCollection;
6958 - (void) beginUpdate;
6963 @implementation CydiaTabBarController
6965 - (NSArray *) navigationURLCollection {
6966 NSMutableArray *items([NSMutableArray array]);
6968 // XXX: Should this deal with transient view controllers?
6969 for (id navigation in [self viewControllers]) {
6970 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6972 [items addObject:stack];
6978 - (id) initWithDatabase:(Database *)database {
6979 if ((self = [super init]) != nil) {
6980 database_ = database;
6981 [self setDelegate:self];
6983 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6984 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6986 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6990 - (void) setUpdate:(NSDate *)date {
6994 - (void) beginUpdate {
6998 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6999 UITabBarItem *item([controller tabBarItem]);
7001 [item setBadgeValue:@""];
7002 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7004 [indicator_ startAnimating];
7005 [badge addSubview:indicator_];
7007 [updatedelegate_ retainNetworkActivityIndicator];
7011 detachNewThreadSelector:@selector(performUpdate)
7017 - (void) performUpdate {
7018 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7020 SourceStatus status(self, database_);
7021 [database_ updateWithStatus:status];
7024 performSelectorOnMainThread:@selector(completeUpdate)
7032 - (void) stopUpdateWithSelector:(SEL)selector {
7034 [updatedelegate_ releaseNetworkActivityIndicator];
7036 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7037 [[controller tabBarItem] setBadgeValue:nil];
7039 [indicator_ removeFromSuperview];
7040 [indicator_ stopAnimating];
7042 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7045 - (void) completeUpdate {
7048 [self stopUpdateWithSelector:@selector(reloadData)];
7051 - (void) cancelUpdate {
7052 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7055 - (void) cancelPressed {
7056 [self cancelUpdate];
7063 - (bool) isSourceCancelled {
7067 - (void) startSourceFetch:(NSString *)uri {
7070 - (void) stopSourceFetch:(NSString *)uri {
7073 - (void) setUpdateDelegate:(id)delegate {
7074 updatedelegate_ = delegate;
7080 /* Cydia Navigation Controller Implementation {{{ */
7081 @implementation UINavigationController (Cydia)
7083 - (NSArray *) navigationURLCollection {
7084 NSMutableArray *stack([NSMutableArray array]);
7086 for (CyteViewController *controller in [self viewControllers]) {
7087 NSString *url = [[controller navigationURL] absoluteString];
7089 [stack addObject:url];
7095 - (void) reloadData {
7098 UIViewController *visible([self visibleViewController]);
7100 [visible reloadData];
7102 // on the iPad, this view controller is ALSO visible. :(
7104 if (UIViewController *top = [self topViewController])
7109 - (void) unloadData {
7110 for (CyteViewController *page in [self viewControllers])
7119 /* Cydia:// Protocol {{{ */
7120 @interface CydiaURLProtocol : NSURLProtocol {
7125 @implementation CydiaURLProtocol
7127 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7128 NSURL *url([request URL]);
7132 NSString *scheme([[url scheme] lowercaseString]);
7133 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7135 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7141 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7145 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7146 id<NSURLProtocolClient> client([self client]);
7148 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7150 NSData *data(UIImagePNGRepresentation(icon));
7152 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7153 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7154 [client URLProtocol:self didLoadData:data];
7155 [client URLProtocolDidFinishLoading:self];
7159 - (void) startLoading {
7160 id<NSURLProtocolClient> client([self client]);
7161 NSURLRequest *request([self request]);
7163 NSURL *url([request URL]);
7164 NSString *href([url absoluteString]);
7165 NSString *scheme([[url scheme] lowercaseString]);
7169 if ([scheme isEqualToString:@"cydia"])
7170 path = [href substringFromIndex:8];
7171 else if ([scheme isEqualToString:@"about"])
7172 path = [href substringFromIndex:12];
7173 else _assert(false);
7175 NSRange slash([path rangeOfString:@"/"]);
7178 if (slash.location == NSNotFound) {
7182 command = [path substringToIndex:slash.location];
7183 path = [path substringFromIndex:(slash.location + 1)];
7186 Database *database([Database sharedInstance]);
7188 if ([command isEqualToString:@"package-icon"]) {
7191 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7192 Package *package([database packageWithName:path]);
7196 UIImage *icon([package icon]);
7197 [self _returnPNGWithImage:icon forRequest:request];
7198 } else if ([command isEqualToString:@"uikit-image"]) {
7201 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7202 UIImage *icon(_UIImageWithName(path));
7203 [self _returnPNGWithImage:icon forRequest:request];
7204 } else if ([command isEqualToString:@"section-icon"]) {
7207 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7208 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7210 icon = [UIImage imageNamed:@"unknown.png"];
7211 [self _returnPNGWithImage:icon forRequest:request];
7213 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7217 - (void) stopLoading {
7223 /* Section Controller {{{ */
7224 @interface SectionController : FilteredPackageListController {
7226 _H<NSString> section_;
7229 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7233 @implementation SectionController
7235 - (NSURL *) referrerURL {
7236 NSString *name(section_);
7237 name = name ?: @"*";
7238 NSString *key(key_);
7240 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7243 - (NSURL *) navigationURL {
7244 NSString *name(section_);
7245 name = name ?: @"*";
7246 NSString *key(key_);
7248 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7251 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7254 title = UCLocalize("ALL_PACKAGES");
7255 else if (![section isEqual:@""])
7256 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7258 title = UCLocalize("NO_SECTION");
7260 if ((self = [super initWithDatabase:database title:title]) != nil) {
7261 key_ = [source key];
7266 - (void) reloadData {
7267 Source *source([database_ sourceWithKey:key_]);
7268 _H<NSString> name(section_);
7270 [self setFilter:[=](Package *package) {
7271 NSString *section([package section]);
7275 section == nil && [name length] == 0 ||
7276 [name isEqualToString:section]
7279 [package source] == source
7280 ) && [package visible];
7288 /* Sections Controller {{{ */
7289 @interface SectionsController : CyteViewController <
7290 UITableViewDataSource,
7293 _transient Database *database_;
7295 _H<NSMutableArray> sections_;
7296 _H<NSMutableArray> filtered_;
7297 _H<UITableView, 2> list_;
7300 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7301 - (void) editButtonClicked;
7305 @implementation SectionsController
7307 - (NSURL *) navigationURL {
7308 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7311 - (Source *) source {
7314 return [database_ sourceWithKey:key_];
7317 - (void) updateNavigationItem {
7318 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7319 if ([sections_ count] == 0) {
7320 [[self navigationItem] setRightBarButtonItem:nil];
7322 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7323 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7325 action:@selector(editButtonClicked)
7326 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7330 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7331 [super setEditing:editing animated:animated];
7336 [delegate_ updateData];
7338 [self updateNavigationItem];
7341 - (void) viewDidAppear:(BOOL)animated {
7342 [super viewDidAppear:animated];
7343 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7346 - (void) viewWillDisappear:(BOOL)animated {
7347 [super viewWillDisappear:animated];
7348 [self setEditing:NO];
7351 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7352 Section *section = nil;
7353 int index = [indexPath row];
7354 if (![self isEditing]) {
7357 section = [filtered_ objectAtIndex:index];
7359 section = [sections_ objectAtIndex:index];
7364 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7365 if ([self isEditing])
7366 return [sections_ count];
7368 return [filtered_ count] + 1;
7371 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7375 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7376 static NSString *reuseIdentifier = @"SectionCell";
7378 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7380 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7382 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7387 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7388 if ([self isEditing])
7391 Section *section = [self sectionAtIndexPath:indexPath];
7393 SectionController *controller = [[[SectionController alloc]
7394 initWithDatabase:database_
7395 source:[self source]
7396 section:[section name]
7398 [controller setDelegate:delegate_];
7400 [[self navigationController] pushViewController:controller animated:YES];
7404 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7405 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7406 [list_ setRowHeight:46];
7407 [(UITableView *) list_ setDataSource:self];
7408 [list_ setDelegate:self];
7409 [self setView:list_];
7412 - (void) viewDidLoad {
7413 [super viewDidLoad];
7415 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7418 - (void) releaseSubviews {
7424 [super releaseSubviews];
7427 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7428 if ((self = [super init]) != nil) {
7429 database_ = database;
7430 key_ = [source key];
7434 - (void) reloadData {
7437 NSArray *packages = [database_ packages];
7439 sections_ = [NSMutableArray arrayWithCapacity:16];
7440 filtered_ = [NSMutableArray arrayWithCapacity:16];
7442 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7444 Source *source([self source]);
7447 for (Package *package in packages) {
7448 if (source != nil && [package source] != source)
7451 NSString *name([package section]);
7452 NSString *key(name == nil ? @"" : name);
7456 _profile(SectionsView$reloadData$Section)
7457 section = [sections objectForKey:key];
7458 if (section == nil) {
7459 _profile(SectionsView$reloadData$Section$Allocate)
7460 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7461 [sections setObject:section forKey:key];
7466 [section addToCount];
7468 _profile(SectionsView$reloadData$Filter)
7469 if (![package valid] || ![package visible])
7477 [sections_ addObjectsFromArray:[sections allValues]];
7479 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7481 for (Section *section in (id) sections_) {
7482 size_t count([section row]);
7486 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7487 [section setCount:count];
7488 [filtered_ addObject:section];
7491 [self updateNavigationItem];
7496 - (void) editButtonClicked {
7497 [self setEditing:![self isEditing] animated:YES];
7503 /* Changes Controller {{{ */
7504 @interface ChangesController : FilteredPackageListController {
7508 - (id) initWithDatabase:(Database *)database;
7512 @implementation ChangesController
7514 - (NSURL *) referrerURL {
7515 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7518 - (NSURL *) navigationURL {
7519 return [NSURL URLWithString:@"cydia://changes"];
7522 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7523 @synchronized (database_) {
7524 if ([database_ era] != era_)
7527 NSUInteger sectionIndex([path section]);
7528 if (sectionIndex >= [sections_ count])
7530 Section *section([sections_ objectAtIndex:sectionIndex]);
7531 NSInteger row([path row]);
7532 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7535 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7536 NSString *context([alert context]);
7538 if ([context isEqualToString:@"norefresh"])
7539 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7542 - (void) setLeftBarButtonItem {
7543 if ([delegate_ updating])
7544 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7545 initWithTitle:UCLocalize("CANCEL")
7546 style:UIBarButtonItemStyleDone
7548 action:@selector(cancelButtonClicked)
7549 ] autorelease] animated:YES];
7551 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7552 initWithTitle:UCLocalize("REFRESH")
7553 style:UIBarButtonItemStylePlain
7555 action:@selector(refreshButtonClicked)
7556 ] autorelease] animated:YES];
7559 - (void) refreshButtonClicked {
7560 if ([delegate_ requestUpdate])
7561 [self setLeftBarButtonItem];
7564 - (void) cancelButtonClicked {
7565 [delegate_ cancelUpdate];
7568 - (void) upgradeButtonClicked {
7569 [delegate_ distUpgrade];
7570 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7573 - (bool) shouldYield {
7577 - (bool) shouldBlock {
7581 - (void) useFilter {
7582 @synchronized (self) {
7583 [self setFilter:[](Package *package) {
7584 return [package upgradableAndEssential:YES] || [package visible];
7587 [self setSorter:[](NSMutableArray *packages) {
7588 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7592 - (id) initWithDatabase:(Database *)database {
7593 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7598 - (void) viewDidLoad {
7599 [super viewDidLoad];
7600 [self setLeftBarButtonItem];
7603 - (void) viewWillAppear:(BOOL)animated {
7604 [super viewWillAppear:animated];
7605 [self setLeftBarButtonItem];
7608 - (void) reloadData {
7609 [self setLeftBarButtonItem];
7613 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7614 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7616 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7617 Section *ignored = nil;
7618 Section *section = nil;
7622 bool unseens = false;
7624 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7626 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7627 Package *package = [packages objectAtIndex:offset];
7629 BOOL uae = [package upgradableAndEssential:YES];
7633 time_t seen([package seen]);
7635 if (section == nil || last != seen) {
7639 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7642 _profile(ChangesController$reloadData$Allocate)
7643 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7644 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7645 [sections addObject:section];
7649 [section addToCount];
7650 } else if ([package ignored]) {
7651 if (ignored == nil) {
7652 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7654 [ignored addToCount];
7657 [upgradable addToCount];
7662 CFRelease(formatter);
7665 Section *last = [sections lastObject];
7666 size_t count = [last count];
7667 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7668 [sections removeLastObject];
7671 if ([ignored count] != 0)
7672 [sections insertObject:ignored atIndex:0];
7674 [sections insertObject:upgradable atIndex:0];
7678 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7679 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7680 style:UIBarButtonItemStylePlain
7682 action:@selector(upgradeButtonClicked)
7683 ] autorelease]) animated:YES];
7690 /* Search Controller {{{ */
7691 @interface SearchController : FilteredPackageListController <
7694 _H<UISearchBar, 1> search_;
7699 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7700 - (void) reloadData;
7704 @implementation SearchController
7706 - (NSURL *) referrerURL {
7707 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7710 - (NSURL *) navigationURL {
7711 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7712 return [NSURL URLWithString:@"cydia://search"];
7714 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7717 - (NSArray *) termsForQuery:(NSString *)query {
7718 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7719 for (NSString *component in [query componentsSeparatedByString:@" "])
7720 if ([component length] != 0)
7721 [terms addObject:component];
7726 - (void) useSearch {
7727 _H<NSArray> query([self termsForQuery:[search_ text]]);
7730 @synchronized (self) {
7731 [self setFilter:[=](Package *package) {
7732 if (![package unfiltered])
7734 if (![package matches:query])
7739 [self setSorter:[](NSMutableArray *packages) {
7740 [packages radixSortUsingSelector:@selector(rank)];
7748 - (void) usePrefix:(NSString *)prefix {
7749 _H<NSString> query(prefix);
7752 @synchronized (self) {
7753 [self setFilter:[=](Package *package) {
7754 if ([query length] == 0)
7756 if (![package unfiltered])
7758 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7763 [self setSorter:nullptr];
7769 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7771 [self usePrefix:[search_ text]];
7774 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7775 [search_ resignFirstResponder];
7779 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7780 [search_ setText:@""];
7781 [self searchBarButtonClicked:searchBar];
7784 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7785 [self searchBarButtonClicked:searchBar];
7788 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7789 [self usePrefix:text];
7792 - (bool) shouldYield {
7796 - (bool) shouldBlock {
7800 - (bool) isSummarized {
7804 - (bool) showsSections {
7808 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7809 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7810 search_ = [[[UISearchBar alloc] init] autorelease];
7811 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7812 [search_ setDelegate:self];
7814 UITextField *textField;
7815 if ([search_ respondsToSelector:@selector(searchField)])
7816 textField = [search_ searchField];
7818 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7820 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7821 [textField setEnablesReturnKeyAutomatically:NO];
7822 [[self navigationItem] setTitleView:textField];
7825 [search_ setText:query];
7830 - (void) viewDidAppear:(BOOL)animated {
7831 [super viewDidAppear:animated];
7833 if (!searchloaded_) {
7834 searchloaded_ = YES;
7835 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7836 [search_ layoutSubviews];
7839 if ([self isSummarized])
7840 [search_ becomeFirstResponder];
7843 - (void) reloadData {
7848 - (void) didSelectPackage:(Package *)package {
7849 [search_ resignFirstResponder];
7850 [super didSelectPackage:package];
7855 /* Package Settings Controller {{{ */
7856 @interface PackageSettingsController : CyteViewController <
7857 UITableViewDataSource,
7860 _transient Database *database_;
7862 _H<Package> package_;
7863 _H<UITableView, 2> table_;
7864 _H<UISwitch> subscribedSwitch_;
7865 _H<UISwitch> ignoredSwitch_;
7866 _H<UITableViewCell> subscribedCell_;
7867 _H<UITableViewCell> ignoredCell_;
7870 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7874 @implementation PackageSettingsController
7876 - (NSURL *) navigationURL {
7877 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7880 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7881 if (package_ == nil)
7884 if ([package_ installed] == nil)
7890 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7891 if (package_ == nil)
7894 // both sections contain just one item right now.
7898 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7902 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7904 return UCLocalize("SHOW_ALL_CHANGES_EX");
7906 return UCLocalize("IGNORE_UPGRADES_EX");
7909 - (void) onSubscribed:(id)control {
7910 bool value([control isOn]);
7911 if (package_ == nil)
7913 if ([package_ setSubscribed:value])
7914 [delegate_ updateData];
7917 - (void) _updateIgnored {
7918 const char *package([name_ UTF8String]);
7919 bool on([ignoredSwitch_ isOn]);
7921 pid_t pid(ExecFork());
7923 FILE *dpkg(popen("dpkg --set-selections", "w"));
7924 fwrite(package, strlen(package), 1, dpkg);
7927 fwrite(" hold\n", 6, 1, dpkg);
7929 fwrite(" install\n", 9, 1, dpkg);
7937 - (void) onIgnored:(id)control {
7938 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7939 [invocation setTarget:self];
7940 [invocation setSelector:@selector(_updateIgnored)];
7942 [delegate_ reloadDataWithInvocation:invocation];
7945 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7946 if (package_ == nil)
7949 switch ([indexPath section]) {
7950 case 0: return subscribedCell_;
7951 case 1: return ignoredCell_;
7960 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7961 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7962 [self setView:view];
7964 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7965 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7966 [(UITableView *) table_ setDataSource:self];
7967 [table_ setDelegate:self];
7968 [view addSubview:table_];
7970 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7971 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7972 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7974 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7975 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7976 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7978 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7979 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7980 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7981 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7983 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7984 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7985 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7986 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7989 - (void) viewDidLoad {
7990 [super viewDidLoad];
7992 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7995 - (void) releaseSubviews {
7997 subscribedCell_ = nil;
7999 ignoredSwitch_ = nil;
8000 subscribedSwitch_ = nil;
8002 [super releaseSubviews];
8005 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8006 if ((self = [super init]) != nil) {
8007 database_ = database;
8012 - (void) reloadData {
8015 package_ = [database_ packageWithName:name_];
8017 if (package_ != nil) {
8018 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8019 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8020 } // XXX: what now, G?
8022 [table_ reloadData];
8028 /* Installed Controller {{{ */
8029 @interface InstalledController : FilteredPackageListController {
8033 - (id) initWithDatabase:(Database *)database;
8034 - (void) queueStatusDidChange;
8038 @implementation InstalledController
8040 - (NSURL *) referrerURL {
8041 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8044 - (NSURL *) navigationURL {
8045 return [NSURL URLWithString:@"cydia://installed"];
8048 - (void) useRecent {
8051 @synchronized (self) {
8052 [self setFilter:[](Package *package) {
8053 return ![package uninstalled] && package->role_ < 7;
8056 [self setSorter:[](NSMutableArray *packages) {
8057 [packages radixSortUsingSelector:@selector(recent)];
8061 - (void) useFilter:(UISegmentedControl *)segmented {
8062 NSInteger selected([segmented selectedSegmentIndex]);
8064 return [self useRecent];
8065 bool simple(selected == 0);
8068 @synchronized (self) {
8069 [self setFilter:[=](Package *package) {
8070 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8073 [self setSorter:nullptr];
8076 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8078 return [super sectionsForPackages:packages];
8080 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8082 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8083 Section *section(nil);
8086 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8087 Package *package([packages objectAtIndex:offset]);
8089 time_t upgraded([package upgraded]);
8090 if (upgraded < 1168364520)
8093 upgraded -= upgraded % (60 * 60 * 24);
8095 if (section == nil || upgraded != last) {
8100 continue; // XXX: name = UCLocalize("...");
8102 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8106 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8107 [sections addObject:section];
8110 [section addToCount];
8113 CFRelease(formatter);
8117 - (id) initWithDatabase:(Database *)database {
8118 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8119 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8120 [segmented setSelectedSegmentIndex:0];
8121 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8122 [[self navigationItem] setTitleView:segmented];
8124 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8125 [self useFilter:segmented];
8127 [self queueStatusDidChange];
8132 - (void) queueButtonClicked {
8137 - (void) queueStatusDidChange {
8140 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8141 initWithTitle:UCLocalize("QUEUE")
8142 style:UIBarButtonItemStyleDone
8144 action:@selector(queueButtonClicked)
8147 [[self navigationItem] setRightBarButtonItem:nil];
8152 - (void) modeChanged:(UISegmentedControl *)segmented {
8153 [self useFilter:segmented];
8160 /* Source Cell {{{ */
8161 @interface SourceCell : CyteTableViewCell <
8162 CyteTableViewCellDelegate,
8165 _H<Source, 1> source_;
8168 _H<NSString> origin_;
8169 _H<NSString> label_;
8170 _H<UIActivityIndicatorView> indicator_;
8173 - (void) setSource:(Source *)source;
8174 - (void) setFetch:(NSNumber *)fetch;
8178 @implementation SourceCell
8180 - (void) _setImage:(NSArray *)data {
8181 if ([url_ isEqual:[data objectAtIndex:0]]) {
8182 icon_ = [data objectAtIndex:1];
8183 [content_ setNeedsDisplay];
8187 - (void) _setSource:(NSURL *) url {
8188 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8190 if (NSData *data = [NSURLConnection
8191 sendSynchronousRequest:[NSURLRequest
8193 cachePolicy:NSURLRequestUseProtocolCachePolicy
8197 returningResponse:NULL
8200 if (UIImage *image = [UIImage imageWithData:data])
8201 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8206 - (void) setSource:(Source *)source {
8208 [source_ setDelegate:self];
8210 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8212 icon_ = [UIImage imageNamed:@"unknown.png"];
8214 origin_ = [source name];
8215 label_ = [source rooturi];
8217 [content_ setNeedsDisplay];
8219 url_ = [source iconURL];
8220 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8223 - (void) setAllSource {
8225 [indicator_ stopAnimating];
8227 icon_ = [UIImage imageNamed:@"folder.png"];
8228 origin_ = UCLocalize("ALL_SOURCES");
8229 label_ = UCLocalize("ALL_SOURCES_EX");
8230 [content_ setNeedsDisplay];
8233 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8234 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8235 UIView *content([self contentView]);
8236 CGRect bounds([content bounds]);
8238 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8239 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8240 [content_ setBackgroundColor:[UIColor whiteColor]];
8241 [content addSubview:content_];
8243 [content_ setDelegate:self];
8244 [content_ setOpaque:YES];
8246 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8247 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8248 [content addSubview:indicator_];
8250 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8254 - (void) layoutSubviews {
8255 [super layoutSubviews];
8257 UIView *content([self contentView]);
8258 CGRect bounds([content bounds]);
8260 CGRect frame([indicator_ frame]);
8261 frame.origin.x = bounds.size.width - frame.size.width;
8262 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8264 if (kCFCoreFoundationVersionNumber < 800)
8265 frame.origin.x -= 8;
8266 [indicator_ setFrame:frame];
8269 - (NSString *) accessibilityLabel {
8273 - (void) drawContentRect:(CGRect)rect {
8274 bool highlighted(highlighted_);
8275 float width(rect.size.width);
8279 rect.size = [(UIImage *) icon_ size];
8281 while (rect.size.width > 32 || rect.size.height > 32) {
8282 rect.size.width /= 2;
8283 rect.size.height /= 2;
8286 rect.origin.x = 26 - rect.size.width / 2;
8287 rect.origin.y = 26 - rect.size.height / 2;
8289 [icon_ drawInRect:Retina(rect)];
8292 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8297 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8301 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8304 - (void) setFetch:(NSNumber *)fetch {
8305 if ([fetch boolValue])
8306 [indicator_ startAnimating];
8308 [indicator_ stopAnimating];
8313 /* Sources Controller {{{ */
8314 @interface SourcesController : CyteViewController <
8315 UITableViewDataSource,
8318 _transient Database *database_;
8321 _H<UITableView, 2> list_;
8322 _H<NSMutableArray> sources_;
8326 _H<UIProgressHUD> hud_;
8329 NSURLConnection *trivial_bz2_;
8330 NSURLConnection *trivial_gz_;
8335 - (id) initWithDatabase:(Database *)database;
8336 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8340 @implementation SourcesController
8342 - (void) _releaseConnection:(NSURLConnection *)connection {
8343 if (connection != nil) {
8344 [connection cancel];
8345 //[connection setDelegate:nil];
8346 [connection release];
8351 [self _releaseConnection:trivial_gz_];
8352 [self _releaseConnection:trivial_bz2_];
8357 - (NSURL *) navigationURL {
8358 return [NSURL URLWithString:@"cydia://sources"];
8361 - (void) viewDidAppear:(BOOL)animated {
8362 [super viewDidAppear:animated];
8363 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8366 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8370 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8372 return UCLocalize("INDIVIDUAL_SOURCES");
8376 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8379 case 1: return [sources_ count];
8384 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8385 @synchronized (database_) {
8386 if ([database_ era] != era_)
8388 if ([indexPath section] != 1)
8390 NSUInteger index([indexPath row]);
8391 if (index >= [sources_ count])
8393 return [sources_ objectAtIndex:index];
8396 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8397 static NSString *cellIdentifier = @"SourceCell";
8399 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8400 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8401 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8403 Source *source([self sourceAtIndexPath:indexPath]);
8405 [cell setAllSource];
8407 [cell setSource:source];
8412 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8413 SectionsController *controller([[[SectionsController alloc]
8414 initWithDatabase:database_
8415 source:[self sourceAtIndexPath:indexPath]
8418 [controller setDelegate:delegate_];
8419 [[self navigationController] pushViewController:controller animated:YES];
8422 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8423 if ([indexPath section] != 1)
8425 Source *source = [self sourceAtIndexPath:indexPath];
8426 return [source record] != nil;
8429 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8430 _assert([indexPath section] == 1);
8431 if (editingStyle == UITableViewCellEditingStyleDelete) {
8432 Source *source = [self sourceAtIndexPath:indexPath];
8433 if (source == nil) return;
8435 [Sources_ removeObjectForKey:[source key]];
8438 [delegate_ _saveConfig];
8439 [delegate_ reloadDataWithInvocation:nil];
8443 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8444 [self updateButtonsForEditingStatusAnimated:YES];
8448 [delegate_ addTrivialSource:href_];
8451 [delegate_ syncData];
8454 - (NSString *) getWarning {
8455 NSString *href(href_);
8456 NSRange colon([href rangeOfString:@"://"]);
8457 if (colon.location != NSNotFound)
8458 href = [href substringFromIndex:(colon.location + 3)];
8459 href = [href stringByAddingPercentEscapes];
8460 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8462 NSURL *url([NSURL URLWithString:href]);
8464 NSStringEncoding encoding;
8465 NSError *error(nil);
8467 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8468 return [warning length] == 0 ? nil : warning;
8472 - (void) _endConnection:(NSURLConnection *)connection {
8473 // XXX: the memory management in this method is horribly awkward
8475 NSURLConnection **field = NULL;
8476 if (connection == trivial_bz2_)
8477 field = &trivial_bz2_;
8478 else if (connection == trivial_gz_)
8479 field = &trivial_gz_;
8480 _assert(field != NULL);
8481 [connection release];
8485 trivial_bz2_ == nil &&
8488 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8490 [delegate_ releaseNetworkActivityIndicator];
8492 [delegate_ removeProgressHUD:hud_];
8496 if (warning != nil) {
8497 UIAlertView *alert = [[[UIAlertView alloc]
8498 initWithTitle:UCLocalize("SOURCE_WARNING")
8501 cancelButtonTitle:UCLocalize("CANCEL")
8503 UCLocalize("ADD_ANYWAY"),
8507 [alert setContext:@"warning"];
8508 [alert setNumberOfRows:1];
8511 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8517 } else if (error_ != nil) {
8518 UIAlertView *alert = [[[UIAlertView alloc]
8519 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8520 message:[error_ localizedDescription]
8522 cancelButtonTitle:UCLocalize("OK")
8523 otherButtonTitles:nil
8526 [alert setContext:@"urlerror"];
8531 UIAlertView *alert = [[[UIAlertView alloc]
8532 initWithTitle:UCLocalize("NOT_REPOSITORY")
8533 message:UCLocalize("NOT_REPOSITORY_EX")
8535 cancelButtonTitle:UCLocalize("OK")
8536 otherButtonTitles:nil
8539 [alert setContext:@"trivial"];
8549 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8550 switch ([response statusCode]) {
8556 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8557 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8559 [self _endConnection:connection];
8562 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8563 [self _endConnection:connection];
8566 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8567 NSURL *url([NSURL URLWithString:href]);
8569 NSMutableURLRequest *request = [NSMutableURLRequest
8571 cachePolicy:NSURLRequestUseProtocolCachePolicy
8575 [request setHTTPMethod:method];
8577 if (Machine_ != NULL)
8578 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8580 if (UniqueID_ != nil)
8581 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8583 if ([url isCydiaSecure]) {
8584 if (UniqueID_ != nil)
8585 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8588 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8591 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8592 NSString *context([alert context]);
8594 if ([context isEqualToString:@"source"]) {
8597 NSString *href = [[alert textField] text];
8599 static Pcre href_r("^http(s?)://[^# ]*$");
8600 if (!href_r(href)) {
8601 UIAlertView *alert = [[[UIAlertView alloc]
8602 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8603 message:UCLocalize("INVALID_URL_EX")
8605 cancelButtonTitle:UCLocalize("OK")
8606 otherButtonTitles:nil
8609 [alert setContext:@"badurl"];
8615 if (![href hasSuffix:@"/"])
8616 href_ = [href stringByAppendingString:@"/"];
8620 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8621 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8625 // XXX: this is stupid
8626 hud_ = [delegate_ addProgressHUD];
8627 [hud_ setText:UCLocalize("VERIFYING_URL")];
8628 [delegate_ retainNetworkActivityIndicator];
8637 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8638 } else if ([context isEqualToString:@"trivial"])
8639 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8640 else if ([context isEqualToString:@"urlerror"])
8641 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8642 else if ([context isEqualToString:@"warning"]) {
8645 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8654 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8658 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8659 BOOL editing([list_ isEditing]);
8662 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8663 initWithTitle:UCLocalize("ADD")
8664 style:UIBarButtonItemStylePlain
8666 action:@selector(addButtonClicked)
8667 ] autorelease] animated:animated];
8668 else if ([delegate_ updating])
8669 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8670 initWithTitle:UCLocalize("CANCEL")
8671 style:UIBarButtonItemStyleDone
8673 action:@selector(cancelButtonClicked)
8674 ] autorelease] animated:animated];
8676 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8677 initWithTitle:UCLocalize("REFRESH")
8678 style:UIBarButtonItemStylePlain
8680 action:@selector(refreshButtonClicked)
8681 ] autorelease] animated:animated];
8683 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8684 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8685 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8687 action:@selector(editButtonClicked)
8688 ] autorelease] animated:animated];
8692 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8693 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8694 [list_ setRowHeight:53];
8695 [(UITableView *) list_ setDataSource:self];
8696 [list_ setDelegate:self];
8697 [self setView:list_];
8700 - (void) viewDidLoad {
8701 [super viewDidLoad];
8703 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8704 [self updateButtonsForEditingStatusAnimated:NO];
8707 - (void) viewWillAppear:(BOOL)animated {
8708 [super viewWillAppear:animated];
8710 [list_ setEditing:NO];
8711 [self updateButtonsForEditingStatusAnimated:NO];
8714 - (void) releaseSubviews {
8719 [super releaseSubviews];
8722 - (id) initWithDatabase:(Database *)database {
8723 if ((self = [super init]) != nil) {
8724 database_ = database;
8728 - (void) reloadData {
8730 [self updateButtonsForEditingStatusAnimated:YES];
8732 @synchronized (database_) {
8733 era_ = [database_ era];
8735 sources_ = [NSMutableArray arrayWithCapacity:16];
8736 [sources_ addObjectsFromArray:[database_ sources]];
8738 [sources_ sortUsingSelector:@selector(compareByName:)];
8741 int count([sources_ count]);
8743 for (int i = 0; i != count; i++) {
8744 if ([[sources_ objectAtIndex:i] record] == nil)
8752 - (void) showAddSourcePrompt {
8753 UIAlertView *alert = [[[UIAlertView alloc]
8754 initWithTitle:UCLocalize("ENTER_APT_URL")
8757 cancelButtonTitle:UCLocalize("CANCEL")
8759 UCLocalize("ADD_SOURCE"),
8763 [alert setContext:@"source"];
8765 [alert setNumberOfRows:1];
8766 [alert addTextFieldWithValue:@"http://" label:@""];
8768 UITextInputTraits *traits = [[alert textField] textInputTraits];
8769 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8770 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8771 [traits setKeyboardType:UIKeyboardTypeURL];
8772 // XXX: UIReturnKeyDone
8773 [traits setReturnKeyType:UIReturnKeyNext];
8778 - (void) addButtonClicked {
8779 [self showAddSourcePrompt];
8782 - (void) refreshButtonClicked {
8783 if ([delegate_ requestUpdate])
8784 [self updateButtonsForEditingStatusAnimated:YES];
8787 - (void) cancelButtonClicked {
8788 [delegate_ cancelUpdate];
8791 - (void) editButtonClicked {
8792 [list_ setEditing:![list_ isEditing] animated:YES];
8793 [self updateButtonsForEditingStatusAnimated:YES];
8799 /* Stash Controller {{{ */
8800 @interface StashController : CyteViewController {
8801 _H<UIActivityIndicatorView> spinner_;
8802 _H<UILabel> status_;
8803 _H<UILabel> caption_;
8808 @implementation StashController
8811 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8812 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8813 [self setView:view];
8815 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8817 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8818 CGRect spinrect = [spinner_ frame];
8819 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8820 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8821 [spinner_ setFrame:spinrect];
8822 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8823 [view addSubview:spinner_];
8824 [spinner_ startAnimating];
8827 captrect.size.width = [[self view] frame].size.width;
8828 captrect.size.height = 40.0f;
8829 captrect.origin.x = 0;
8830 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8831 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8832 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8833 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8834 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8835 [caption_ setTextColor:[UIColor whiteColor]];
8836 [caption_ setBackgroundColor:[UIColor clearColor]];
8837 [caption_ setShadowColor:[UIColor blackColor]];
8838 [caption_ setTextAlignment:NSTextAlignmentCenter];
8839 [view addSubview:caption_];
8842 statusrect.size.width = [[self view] frame].size.width;
8843 statusrect.size.height = 30.0f;
8844 statusrect.origin.x = 0;
8845 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8846 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8847 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8848 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8849 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8850 [status_ setTextColor:[UIColor whiteColor]];
8851 [status_ setBackgroundColor:[UIColor clearColor]];
8852 [status_ setShadowColor:[UIColor blackColor]];
8853 [status_ setTextAlignment:NSTextAlignmentCenter];
8854 [view addSubview:status_];
8857 - (void) releaseSubviews {
8862 [super releaseSubviews];
8868 @interface CYURLCache : SDURLCache {
8873 @implementation CYURLCache
8875 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8878 else if ([event isEqualToString:@"no-cache"])
8880 else if ([event isEqualToString:@"store"])
8882 else if ([event isEqualToString:@"invalid"])
8884 else if ([event isEqualToString:@"memory"])
8886 else if ([event isEqualToString:@"disk"])
8888 else if ([event isEqualToString:@"miss"])
8891 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8895 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8896 if (NSURLResponse *response = [cached response])
8897 if (NSString *mime = [response MIMEType])
8898 if ([mime isEqualToString:@"text/cache-manifest"]) {
8899 NSURL *url([response URL]);
8902 NSLog(@"###: %@", [url absoluteString]);
8905 @synchronized (HostConfig_) {
8906 [CachedURLs_ addObject:url];
8910 [super storeCachedResponse:cached forRequest:request];
8915 @interface Cydia : UIApplication <
8916 ConfirmationControllerDelegate,
8920 _H<UIWindow> window_;
8921 _H<CydiaTabBarController> tabbar_;
8922 _H<CyteTabBarController> emulated_;
8924 _H<NSMutableArray> essential_;
8925 _H<NSMutableArray> broken_;
8927 Database *database_;
8929 _H<NSURL> starturl_;
8934 _H<StashController> stash_;
8943 @implementation Cydia
8945 - (void) lockSuspend {
8946 if (locked_++ == 0) {
8947 if ($SBSSetInterceptsMenuButtonForever != NULL)
8948 (*$SBSSetInterceptsMenuButtonForever)(true);
8950 [self setIdleTimerDisabled:YES];
8954 - (void) unlockSuspend {
8955 if (--locked_ == 0) {
8956 [self setIdleTimerDisabled:NO];
8958 if ($SBSSetInterceptsMenuButtonForever != NULL)
8959 (*$SBSSetInterceptsMenuButtonForever)(false);
8963 - (void) beginUpdate {
8964 [tabbar_ beginUpdate];
8967 - (void) cancelUpdate {
8968 [tabbar_ cancelUpdate];
8971 - (bool) requestUpdate {
8972 if (IsReachable("cydia.saurik.com")) {
8976 UIAlertView *alert = [[[UIAlertView alloc]
8977 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8978 message:@"Host Unreachable" // XXX: Localize
8980 cancelButtonTitle:UCLocalize("OK")
8981 otherButtonTitles:nil
8984 [alert setContext:@"norefresh"];
8992 return [tabbar_ updating];
8996 if ([broken_ count] != 0) {
8997 int count = [broken_ count];
8999 UIAlertView *alert = [[[UIAlertView alloc]
9000 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9001 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9003 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9005 UCLocalize("TEMPORARY_IGNORE"),
9009 [alert setContext:@"fixhalf"];
9010 [alert setNumberOfRows:2];
9012 } else if (!Ignored_ && [essential_ count] != 0) {
9013 int count = [essential_ count];
9015 UIAlertView *alert = [[[UIAlertView alloc]
9016 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9017 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9019 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9021 UCLocalize("UPGRADE_ESSENTIAL"),
9022 UCLocalize("COMPLETE_UPGRADE"),
9026 [alert setContext:@"upgrade"];
9031 - (void) returnToCydia {
9035 - (void) _saveConfig {
9036 @synchronized (database_) {
9043 NSString *error(nil);
9045 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9047 NSError *error(nil);
9048 _root(true) if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9049 NSLog(@"failure to save metadata data: %@", error);
9054 NSLog(@"failure to serialize metadata: %@", error);
9058 CydiaWriteSources();
9061 // Navigation controller for the queuing badge.
9062 - (UINavigationController *) queueNavigationController {
9063 NSArray *controllers = [tabbar_ viewControllers];
9064 return [controllers objectAtIndex:3];
9067 - (void) unloadData {
9068 [tabbar_ unloadData];
9071 - (void) _updateData {
9075 UINavigationController *navigation = [self queueNavigationController];
9077 id queuedelegate = nil;
9078 if ([[navigation viewControllers] count] > 0)
9079 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9081 [queuedelegate queueStatusDidChange];
9082 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9085 - (void) _refreshIfPossible:(NSDate *)update {
9086 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9088 bool recently = false;
9089 if (update != nil) {
9090 NSTimeInterval interval([update timeIntervalSinceNow]);
9091 if (interval <= 0 && interval > -(15*60))
9095 // Don't automatic refresh if:
9096 // - We already refreshed recently.
9097 // - We already auto-refreshed this launch.
9098 // - Auto-refresh is disabled.
9099 // - Cydia's server is not reachable
9100 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9101 // If we are cancelling, we need to make sure it knows it's already loaded.
9104 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9106 // We are going to load, so remember that.
9109 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9115 - (void) refreshIfPossible {
9116 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9119 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9120 _profile(reloadDataWithInvocation)
9121 @synchronized (self) {
9122 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9124 [hud setText:UCLocalize("RELOADING_DATA")];
9126 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9130 [essential_ removeAllObjects];
9131 [broken_ removeAllObjects];
9133 _profile(reloadDataWithInvocation$Essential)
9134 NSArray *packages([database_ packages]);
9135 for (Package *package in packages) {
9137 [broken_ addObject:package];
9138 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9139 if ([package essential] && [package installed] != nil)
9140 [essential_ addObject:package];
9146 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9149 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9150 [changesItem setBadgeValue:badge];
9151 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9152 [self setApplicationIconBadgeNumber:changes];
9155 [changesItem setBadgeValue:nil];
9156 [changesItem setAnimatedBadge:NO];
9157 [self setApplicationIconBadgeNumber:0];
9163 [self removeProgressHUD:hud];
9170 - (void) updateData {
9174 - (void) updateDataAndLoad {
9176 if ([database_ progressDelegate] == nil)
9182 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9185 - (void) disemulate {
9186 if (emulated_ == nil)
9189 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9190 [window_ setRootViewController:tabbar_];
9192 [window_ addSubview:[tabbar_ view]];
9193 [[emulated_ view] removeFromSuperview];
9197 [window_ setUserInteractionEnabled:YES];
9200 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9201 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9203 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9205 UIViewController *parent;
9206 if (emulated_ == nil)
9215 [parent presentModalViewController:navigation animated:YES];
9218 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9219 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9221 if (navigation != nil)
9222 [navigation pushViewController:progress animated:YES];
9224 [self presentModalViewController:progress force:YES];
9226 [progress invoke:invocation withTitle:title];
9230 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9231 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9234 - (void) repairWithInvocation:(NSInvocation *)invocation {
9236 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9240 - (void) repairWithSelector:(SEL)selector {
9241 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9244 - (void) reloadData {
9245 [self reloadDataWithInvocation:nil];
9246 if ([database_ progressDelegate] == nil)
9252 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9255 - (void) addSource:(NSDictionary *) source {
9256 CydiaAddSource(source);
9259 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9260 CydiaAddSource(href, distribution, sections);
9263 - (void) addTrivialSource:(NSString *)href {
9264 CydiaAddSource(href, @"./");
9267 - (void) updateValues {
9272 pkgProblemResolver *resolver = [database_ resolver];
9274 resolver->InstallProtect();
9275 if (!resolver->Resolve(true))
9280 // XXX: this is a really crappy way of doing this.
9281 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9282 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9283 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9284 if ([tabbar_ updating])
9285 [tabbar_ cancelUpdate];
9287 if (![database_ prepare])
9290 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9291 [page setDelegate:self];
9292 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9295 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9296 [tabbar_ presentModalViewController:confirm_ animated:YES];
9302 @synchronized (self) {
9307 - (void) clearPackage:(Package *)package {
9308 @synchronized (self) {
9315 - (void) installPackages:(NSArray *)packages {
9316 @synchronized (self) {
9317 for (Package *package in packages)
9324 - (void) installPackage:(Package *)package {
9325 @synchronized (self) {
9332 - (void) removePackage:(Package *)package {
9333 @synchronized (self) {
9340 - (void) distUpgrade {
9341 @synchronized (self) {
9342 if (![database_ upgrade])
9350 system("/usr/bin/uicache");
9355 UIProgressHUD *hud([self addProgressHUD]);
9356 [hud setText:UCLocalize("LOADING")];
9357 [self yieldToSelector:@selector(_uicache)];
9358 [self removeProgressHUD:hud];
9362 [database_ perform];
9363 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9364 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9367 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9370 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9371 [self unlockSuspend];
9374 - (void) retainNetworkActivityIndicator {
9375 if (activity_++ == 0)
9376 [self setNetworkActivityIndicatorVisible:YES];
9379 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9383 - (void) releaseNetworkActivityIndicator {
9384 if (--activity_ == 0)
9385 [self setNetworkActivityIndicatorVisible:NO];
9388 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9393 - (void) cancelAndClear:(bool)clear {
9394 @synchronized (self) {
9406 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9407 NSString *context([alert context]);
9409 if ([context isEqualToString:@"conffile"]) {
9410 FILE *input = [database_ input];
9411 if (button == [alert cancelButtonIndex])
9412 fprintf(input, "N\n");
9413 else if (button == [alert firstOtherButtonIndex])
9414 fprintf(input, "Y\n");
9417 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9418 } else if ([context isEqualToString:@"fixhalf"]) {
9419 if (button == [alert cancelButtonIndex]) {
9420 @synchronized (self) {
9421 _root(false) for (Package *broken in (id) broken_) {
9424 NSString *id = [broken id];
9425 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9426 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9427 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9428 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9434 } else if (button == [alert firstOtherButtonIndex]) {
9435 [broken_ removeAllObjects];
9439 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9440 } else if ([context isEqualToString:@"upgrade"]) {
9441 if (button == [alert firstOtherButtonIndex]) {
9442 @synchronized (self) {
9443 for (Package *essential in (id) essential_)
9444 [essential install];
9449 } else if (button == [alert firstOtherButtonIndex] + 1) {
9451 } else if (button == [alert cancelButtonIndex]) {
9455 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9459 - (void) system:(NSString *)command {
9460 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9463 system([command UTF8String]);
9469 - (void) applicationWillSuspend {
9471 [super applicationWillSuspend];
9474 - (BOOL) isSafeToSuspend {
9477 NSLog(@"isSafeToSuspend: locked_ != 0");
9482 if ([tabbar_ modalViewController] != nil)
9485 // Use external process status API internally.
9486 // This is probably a really bad idea.
9487 // XXX: what is the point of this? does this solve anything at all?
9488 uint64_t status = 0;
9490 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9491 notify_get_state(notify_token, &status);
9492 notify_cancel(notify_token);
9497 NSLog(@"isSafeToSuspend: status != 0");
9503 NSLog(@"isSafeToSuspend: -> true");
9508 - (void) applicationSuspend:(__GSEvent *)event {
9509 if ([self isSafeToSuspend])
9510 [super applicationSuspend:event];
9513 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9514 if ([self isSafeToSuspend])
9515 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9518 - (void) _setSuspended:(BOOL)value {
9519 if ([self isSafeToSuspend])
9520 [super _setSuspended:value];
9523 - (UIProgressHUD *) addProgressHUD {
9524 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9525 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9527 [window_ setUserInteractionEnabled:NO];
9529 UIViewController *target(tabbar_);
9530 if (UIViewController *modal = [target modalViewController])
9533 [hud showInView:[target view]];
9539 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9540 [self unlockSuspend];
9542 [hud removeFromSuperview];
9543 [window_ setUserInteractionEnabled:YES];
9546 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9547 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9550 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9551 NSString *scheme([[url scheme] lowercaseString]);
9552 if ([[url absoluteString] length] <= [scheme length] + 3)
9554 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9555 NSArray *components([path componentsSeparatedByString:@"/"]);
9557 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9558 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9559 if (controller != nil)
9560 [controller setDelegate:self];
9564 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9567 NSString *base([components objectAtIndex:0]);
9569 CyteViewController *controller = nil;
9571 if ([base isEqualToString:@"url"]) {
9572 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9573 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9574 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9575 } else if (!external && [components count] == 1) {
9576 if ([base isEqualToString:@"sources"]) {
9577 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9580 if ([base isEqualToString:@"home"]) {
9581 controller = [[[HomeController alloc] init] autorelease];
9584 if ([base isEqualToString:@"sections"]) {
9585 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9588 if ([base isEqualToString:@"search"]) {
9589 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9592 if ([base isEqualToString:@"changes"]) {
9593 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9596 if ([base isEqualToString:@"installed"]) {
9597 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9599 } else if ([components count] == 2) {
9600 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9602 if ([base isEqualToString:@"package"]) {
9603 controller = [self pageForPackage:argument withReferrer:referrer];
9606 if (!external && [base isEqualToString:@"search"]) {
9607 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9610 if (!external && [base isEqualToString:@"sections"]) {
9611 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9613 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9616 if (!external && [base isEqualToString:@"sources"]) {
9617 if ([argument isEqualToString:@"add"]) {
9618 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9619 [(SourcesController *)controller showAddSourcePrompt];
9621 Source *source([database_ sourceWithKey:argument]);
9622 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9626 if (!external && [base isEqualToString:@"launch"]) {
9627 [self launchApplicationWithIdentifier:argument suspended:NO];
9630 } else if (!external && [components count] == 3) {
9631 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9632 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9634 if ([base isEqualToString:@"package"]) {
9635 if ([arg2 isEqualToString:@"settings"]) {
9636 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9637 } else if ([arg2 isEqualToString:@"files"]) {
9638 if (Package *package = [database_ packageWithName:arg1]) {
9639 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9640 [(FileTable *)controller setPackage:package];
9645 if ([base isEqualToString:@"sections"]) {
9646 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9647 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9648 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9652 [controller setDelegate:self];
9656 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9657 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9660 [tabbar_ setUnselectedViewController:page];
9665 - (void) applicationOpenURL:(NSURL *)url {
9666 [super applicationOpenURL:url];
9671 [self openCydiaURL:url forExternal:YES];
9674 - (void) applicationWillResignActive:(UIApplication *)application {
9675 // Stop refreshing if you get a phone call or lock the device.
9676 if ([tabbar_ updating])
9677 [tabbar_ cancelUpdate];
9679 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9680 [super applicationWillResignActive:application];
9683 - (void) saveState {
9684 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9685 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9686 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9692 - (void) applicationWillTerminate:(UIApplication *)application {
9696 - (void) setConfigurationData:(NSString *)data {
9697 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9699 if (!conffile_r(data)) {
9700 lprintf("E:invalid conffile\n");
9704 NSString *ofile = conffile_r[1];
9705 //NSString *nfile = conffile_r[2];
9707 UIAlertView *alert = [[[UIAlertView alloc]
9708 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9709 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9711 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9713 UCLocalize("ACCEPT_NEW_COPY"),
9714 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9718 [alert setContext:@"conffile"];
9719 [alert setNumberOfRows:2];
9723 - (void) addStashController {
9725 stash_ = [[[StashController alloc] init] autorelease];
9726 [window_ addSubview:[stash_ view]];
9729 - (void) removeStashController {
9730 [[stash_ view] removeFromSuperview];
9732 [self unlockSuspend];
9736 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9737 UpdateExternalStatus(1);
9738 _root(true) [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9739 UpdateExternalStatus(0);
9741 [self removeStashController];
9743 pid_t pid(ExecFork());
9745 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9746 perror("launchctl stop");
9752 - (void) setupViewControllers {
9753 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9755 NSMutableArray *items;
9756 if (kCFCoreFoundationVersionNumber < 800) {
9757 items = [NSMutableArray arrayWithObjects:
9758 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9759 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9760 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9761 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9762 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9765 items = [NSMutableArray arrayWithObjects:
9766 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9767 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9768 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9769 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9770 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9774 NSMutableArray *controllers([NSMutableArray array]);
9775 for (UITabBarItem *item in items) {
9776 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9777 [controller setTabBarItem:item];
9778 [controllers addObject:controller];
9780 [tabbar_ setViewControllers:controllers];
9782 [tabbar_ setUpdateDelegate:self];
9785 - (void) _sendMemoryWarningNotification {
9786 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9787 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9789 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9792 - (void) _sendMemoryWarningNotifications {
9794 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9800 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9802 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9805 - (void) applicationDidFinishLaunching:(id)unused {
9806 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9809 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9810 [self setApplicationSupportsShakeToEdit:NO];
9812 @synchronized (HostConfig_) {
9813 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9816 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9817 initWithMemoryCapacity:524288
9818 diskCapacity:10485760
9819 diskPath:Cache("SDURLCache")
9822 [CydiaWebViewController _initialize];
9824 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9826 // this would disallow http{,s} URLs from accessing this data
9827 //[WebView registerURLSchemeAsLocal:@"cydia"];
9829 Font12_ = [UIFont systemFontOfSize:12];
9830 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9831 Font14_ = [UIFont systemFontOfSize:14];
9832 Font18_ = [UIFont systemFontOfSize:18];
9833 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9834 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9836 essential_ = [NSMutableArray arrayWithCapacity:4];
9837 broken_ = [NSMutableArray arrayWithCapacity:4];
9839 // XXX: I really need this thing... like, seriously... I'm sorry
9840 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9842 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9843 [window_ orderFront:self];
9844 [window_ makeKey:self];
9845 [window_ setHidden:NO];
9848 [self addStashController];
9849 // XXX: this would be much cleaner as a yieldToSelector:
9850 // that way the removeStashController could happen right here inline
9851 // we also could no longer require the useless stash_ field anymore
9852 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9857 int error(stat("/", &root));
9858 _assert(error != -1);
9860 #define Stash_(path) do { \
9861 struct stat folder; \
9862 int error(lstat((path), &folder)); \
9863 if (error != -1 && ( \
9864 folder.st_dev == root.st_dev && \
9865 S_ISDIR(folder.st_mode) \
9866 ) || error == -1 && ( \
9867 errno == ENOENT || \
9872 Stash_("/Applications");
9873 Stash_("/Library/Ringtones");
9874 Stash_("/Library/Wallpaper");
9875 //Stash_("/usr/bin");
9876 Stash_("/usr/include");
9877 Stash_("/usr/lib/pam");
9878 Stash_("/usr/share");
9879 //Stash_("/var/lib");
9881 database_ = [Database sharedInstance];
9882 [database_ setDelegate:self];
9884 [window_ setUserInteractionEnabled:NO];
9885 [self setupViewControllers];
9887 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9888 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9889 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9891 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9892 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9893 [emulated_ setSelectedIndex:0];
9895 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9896 [emulated_ concealTabBarSelection];
9898 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9899 [window_ setRootViewController:emulated_];
9901 [window_ addSubview:[emulated_ view]];
9903 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9907 - (NSArray *) defaultStartPages {
9908 NSMutableArray *standard = [NSMutableArray array];
9909 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9910 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9911 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9912 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9913 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9919 if ([emulated_ modalViewController] != nil)
9920 [emulated_ dismissModalViewControllerAnimated:YES];
9921 [window_ setUserInteractionEnabled:NO];
9923 [self reloadDataWithInvocation:nil];
9924 [self refreshIfPossible];
9927 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9928 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9929 int standardIndex = 0;
9930 NSArray *standard = [self defaultStartPages];
9937 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9938 if (valid && closed != nil) {
9939 NSTimeInterval interval([closed timeIntervalSinceNow]);
9940 // XXX: Is 30 minutes the optimal time here?
9941 if (interval <= -(30*60))
9945 if (valid && [saved count] != [standard count])
9949 for (unsigned int i = 0; i < [standard count]; i++) {
9950 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9951 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9952 // but it's good enough for now.
9953 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9960 NSArray *items = nil;
9962 [tabbar_ setSelectedIndex:savedIndex];
9965 [tabbar_ setSelectedIndex:standardIndex];
9969 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9970 NSArray *stack = [items objectAtIndex:tab];
9971 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9972 NSMutableArray *current = [NSMutableArray array];
9974 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9975 NSString *addr = [stack objectAtIndex:nav];
9976 NSURL *url = [NSURL URLWithString:addr];
9977 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9979 [current addObject:page];
9982 [navigation setViewControllers:current];
9985 // (Try to) show the startup URL.
9986 if (starturl_ != nil) {
9987 [self openCydiaURL:starturl_ forExternal:YES];
9992 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9993 if (item != nil && IsWildcat_) {
9994 [sheet showFromBarButtonItem:item animated:YES];
9996 [sheet showInView:window_];
10000 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10001 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10002 [progress setTitle:task];
10003 [progress addProgressEvent:event];
10006 - (void) addProgressEventForTask:(NSArray *)data {
10007 CydiaProgressEvent *event([data objectAtIndex:0]);
10008 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10009 [self addProgressEvent:event forTask:task];
10012 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10013 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10019 id Alloc_(id self, SEL selector) {
10020 id object = alloc_(self, selector);
10021 lprintf("[%s]A-%p\n", self->isa->name, object);
10026 id Dealloc_(id self, SEL selector) {
10027 id object = dealloc_(self, selector);
10028 lprintf("[%s]D-%p\n", self->isa->name, object);
10032 Class $NSURLConnection;
10034 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10035 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10037 NSURL *url([copy URL]);
10039 NSString *host([url host]);
10040 NSString *scheme([[url scheme] lowercaseString]);
10042 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10044 @synchronized (HostConfig_) {
10045 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10046 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10047 [copy setHTTPShouldUsePipelining:YES];
10049 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10050 if ([control isEqualToString:@"max-age=0"])
10051 if ([CachedURLs_ containsObject:url]) {
10053 NSLog(@"~~~: %@", url);
10056 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10058 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10059 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10060 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10064 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10070 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10071 CGSize size([[UIScreen mainScreen] bounds].size);
10072 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10073 if ([$WAKWindow hasLandscapeOrientation])
10074 std::swap(size.width, size.height);*/
10078 Class $NSUserDefaults;
10080 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10081 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10082 return Cache("LocalStorage");
10083 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10086 int main(int argc, char *argv[]) {
10089 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10093 UpdateExternalStatus(0);
10095 UIScreen *screen([UIScreen mainScreen]);
10096 if ([screen respondsToSelector:@selector(scale)])
10097 ScreenScale_ = [screen scale];
10101 UIDevice *device([UIDevice currentDevice]);
10102 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10103 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10104 if (idiom == UIUserInterfaceIdiomPad)
10108 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10110 Pcre pattern("^([0-9]+\\.[0-9]+)");
10112 if (pattern([device systemVersion]))
10113 Firmware_ = pattern[1];
10114 if (pattern(Cydia_))
10115 Major_ = pattern[1];
10117 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10119 HostConfig_ = [[[NSObject alloc] init] autorelease];
10120 @synchronized (HostConfig_) {
10121 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10122 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10123 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10124 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10125 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10128 NSString *ui(@"ui/ios");
10130 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10131 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10132 UI_ = CydiaURL(ui);
10134 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10136 /* Library Hacks {{{ */
10137 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10139 $WAKWindow = objc_getClass("WAKWindow");
10140 if ($WAKWindow != NULL)
10141 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10142 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10144 $NSURLConnection = objc_getClass("NSURLConnection");
10145 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10146 if (NSURLConnection$init$ != NULL) {
10147 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10148 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10151 $NSUserDefaults = objc_getClass("NSUserDefaults");
10152 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10153 if (NSUserDefaults$objectForKey$ != NULL) {
10154 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10155 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10158 /* Set Locale {{{ */
10159 Locale_ = CFLocaleCopyCurrent();
10160 Languages_ = [NSLocale preferredLanguages];
10162 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10163 //NSLog(@"%@", [Languages_ description]);
10166 if (Locale_ != NULL)
10167 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10168 else if (Languages_ != nil && [Languages_ count] != 0)
10169 lang = [[Languages_ objectAtIndex:0] UTF8String];
10171 // XXX: consider just setting to C and then falling through?
10174 if (lang != NULL) {
10175 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10176 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10179 NSLog(@"Setting Language: %s", lang);
10181 if (lang != NULL) {
10182 setenv("LANG", lang, true);
10183 std::setlocale(LC_ALL, lang);
10186 /* Index Collation {{{ */
10187 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10188 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10189 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10190 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10191 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10192 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10194 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10196 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10197 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10198 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})
10199 CollationOffset_.push_back(offset);
10200 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];
10201 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];
10204 CollationThumbs_ = [collation sectionIndexTitles];
10205 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10206 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10208 CollationTitles_ = [collation sectionTitles];
10209 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10211 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10212 if (&transform != NULL && transform != nil) {
10213 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10214 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10215 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10216 UErrorCode code(U_ZERO_ERROR);
10217 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10218 if (!U_SUCCESS(code))
10219 NSLog(@"%s", u_errorName(code));
10223 } @catch (NSException *e) {
10227 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10229 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];
10230 for (NSInteger offset(0); offset != 28; ++offset)
10231 CollationOffset_.push_back(offset);
10233 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];
10234 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];
10238 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10240 /* Parse Arguments {{{ */
10241 bool substrate(false);
10247 for (int argi(1); argi != argc; ++argi)
10248 if (strcmp(argv[argi], "--") == 0) {
10250 argv[argi] = argv[0];
10256 for (int argi(1); argi != arge; ++argi)
10257 if (strcmp(args[argi], "--substrate") == 0)
10260 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10264 App_ = [[NSBundle mainBundle] bundlePath];
10267 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10269 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10270 alloc_ = alloc->method_imp;
10271 alloc->method_imp = (IMP) &Alloc_;*/
10273 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10274 dealloc_ = dealloc->method_imp;
10275 dealloc->method_imp = (IMP) &Dealloc_;*/
10277 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10278 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10280 /* System Information {{{ */
10284 size = sizeof(maxproc);
10285 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10286 perror("sysctlbyname(\"kern.maxproc\", ?)");
10287 else if (maxproc < 64) {
10289 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10290 perror("sysctlbyname(\"kern.maxproc\", #)");
10293 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10294 char *osversion = new char[size];
10295 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10296 perror("sysctlbyname(\"kern.osversion\", ?)");
10298 System_ = [NSString stringWithUTF8String:osversion];
10300 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10301 char *machine = new char[size];
10302 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10303 perror("sysctlbyname(\"hw.machine\", ?)");
10305 Machine_ = machine;
10307 int64_t usermem(0);
10308 size = sizeof(usermem);
10309 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10312 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10313 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10314 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10316 UniqueID_ = UniqueIdentifier(device);
10318 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10319 Product_ = [info objectForKey:@"SafariProductVersion"];
10320 Safari_ = [info objectForKey:@"CFBundleVersion"];
10323 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10325 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10326 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10327 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10328 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10329 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10330 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10332 UserAgent_ = agent;
10334 /* Load Database {{{ */
10336 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10338 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10340 if (Metadata_ == NULL)
10341 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10343 Settings_ = [Metadata_ objectForKey:@"Settings"];
10345 Packages_ = [Metadata_ objectForKey:@"Packages"];
10347 Values_ = [Metadata_ objectForKey:@"Values"];
10348 Sections_ = [Metadata_ objectForKey:@"Sections"];
10349 Sources_ = [Metadata_ objectForKey:@"Sources"];
10351 Token_ = [Metadata_ objectForKey:@"Token"];
10353 Version_ = [Metadata_ objectForKey:@"Version"];
10356 if (Values_ == nil) {
10357 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10358 [Metadata_ setObject:Values_ forKey:@"Values"];
10361 if (Sections_ == nil) {
10362 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10363 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10366 if (Sources_ == nil) {
10367 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10368 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10371 if (Version_ == nil) {
10372 Version_ = [NSNumber numberWithUnsignedInt:0];
10373 [Metadata_ setObject:Version_ forKey:@"Version"];
10376 if ([Version_ unsignedIntValue] == 0) {
10377 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10378 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10379 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10380 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10382 Version_ = [NSNumber numberWithUnsignedInt:1];
10383 [Metadata_ setObject:Version_ forKey:@"Version"];
10385 [Metadata_ removeObjectForKey:@"LastUpdate"];
10390 _H<NSMutableArray> broken([NSMutableArray array]);
10391 for (NSString *key in (id) Sources_)
10392 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10393 [broken addObject:key];
10394 if ([broken count] != 0) {
10395 for (NSString *key in (id) broken)
10396 [Sources_ removeObjectForKey:key];
10401 CydiaWriteSources();
10404 _root(true) MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10407 if (Packages_ != nil) {
10409 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10413 [Metadata_ removeObjectForKey:@"Packages"];
10419 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10421 #define MobileSubstrate_(name) \
10422 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10423 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10424 if (handle == NULL) \
10425 NSLog(@"%s", dlerror()); \
10428 MobileSubstrate_(Activator)
10429 MobileSubstrate_(libstatusbar)
10430 MobileSubstrate_(SimulatedKeyEvents)
10431 MobileSubstrate_(WinterBoard)
10433 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10434 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10436 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10438 _root(true) if (access("/User", F_OK) != 0 || version != 6) {
10440 system("/usr/libexec/cydia/firmware.sh");
10444 if (access("/tmp/cydia.chk", F_OK) == 0) {
10445 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10446 _assert(errno == ENOENT);
10447 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10448 _assert(errno == ENOENT);
10451 /* APT Initialization {{{ */
10452 _assert(pkgInitConfig(*_config));
10453 _assert(pkgInitSystem(*_config, _system));
10456 _config->Set("APT::Acquire::Translation", lang);
10458 // XXX: this timeout might be important :(
10459 //_config->Set("Acquire::http::Timeout", 15);
10461 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10463 mkdir([Cache_ UTF8String], 0755);
10464 mkdir([Cache("archives") UTF8String], 0755);
10465 mkdir([Cache("archives/partial") UTF8String], 0755);
10466 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10468 mkdir([Cache("lists") UTF8String], 0755);
10469 mkdir([Cache("lists/partial") UTF8String], 0755);
10470 mkdir([Cache("periodic") UTF8String], 0755);
10471 _config->Set("Dir::State", [Cache_ UTF8String]);
10473 /* Color Choices {{{ */
10474 space_ = CGColorSpaceCreateDeviceRGB();
10476 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10477 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10478 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10479 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10480 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10481 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10482 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10483 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10484 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10485 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10487 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10488 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10490 /* UIKit Configuration {{{ */
10491 // XXX: I have a feeling this was important
10492 //UIKeyboardDisableAutomaticAppearance();
10495 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10497 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10498 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10499 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10501 PulseInterval_ = fast ? 50000 : 500000;
10503 Colon_ = UCLocalize("COLON_DELIMITED");
10504 Elision_ = UCLocalize("ELISION");
10505 Error_ = UCLocalize("ERROR");
10506 Warning_ = UCLocalize("WARNING");
10509 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10511 CGColorSpaceRelease(space_);
10512 CFRelease(Locale_);