1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include <CydiaSubstrate/CydiaSubstrate.h>
124 #include "Menes/Menes.h"
126 #include "CyteKit/PerlCompatibleRegEx.hpp"
127 #include "CyteKit/TableViewCell.h"
128 #include "CyteKit/WebScriptObject-Cyte.h"
129 #include "CyteKit/WebViewController.h"
130 #include "CyteKit/stringWithUTF8Bytes.h"
132 #include "Cydia/MIMEAddress.h"
133 #include "Cydia/LoadingViewController.h"
134 #include "Cydia/ProgressEvent.h"
136 #include "SDURLCache/SDURLCache.h"
143 #define _timestamp ({ \
145 gettimeofday(&tv, NULL); \
146 tv.tv_sec * 1000000 + tv.tv_usec; \
149 typedef std::vector<class ProfileTime *> TimeList;
159 ProfileTime(const char *name) :
163 times_.push_back(this);
166 void AddTime(uint64_t time) {
173 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
185 ProfileTimer(ProfileTime &time) :
192 time_.AddTime(_timestamp - start_);
197 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
199 std::cerr << "========" << std::endl;
202 #define _profile(name) { \
203 static ProfileTime name(#name); \
204 ProfileTimer _ ## name(name);
210 #define Cydia_ CYDIA_VERSION
212 #define lprintf(args...) fprintf(stderr, args)
215 #define TraceLogging (1 && !ForRelease)
216 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
217 #define ProfileTimes (0 && !ForRelease)
218 #define ForSaurik (0 && !ForRelease)
219 #define LogBrowser (0 && !ForRelease)
220 #define TrackResize (0 && !ForRelease)
221 #define ManualRefresh (1 && !ForRelease)
222 #define ShowInternals (0 && !ForRelease)
223 #define AlwaysReload (0 && !ForRelease)
224 #define TryIndexedCollation (0 && !ForRelease)
228 #define _trace(args...)
233 #define _profile(name) {
236 #define PrintTimes() do {} while (false)
239 // Hash Functions/Structures {{{
240 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
248 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
250 static _finline NSString *CydiaURL(NSString *path) {
252 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
253 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
254 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
255 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
256 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
258 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
261 static _finline void UpdateExternalStatus(uint64_t newStatus) {
263 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
264 notify_set_state(notify_token, newStatus);
265 notify_cancel(notify_token);
267 notify_post("com.saurik.Cydia.status");
270 static CGFloat CYStatusBarHeight(UIInterfaceOrientation orientation) {
271 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
272 return UIInterfaceOrientationIsPortrait(orientation) ? size.height : size.width;
275 /* NSForcedOrderingSearch doesn't work on the iPhone */
276 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
277 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
278 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
280 /* Insertion Sort {{{ */
282 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
283 const char *ptr = (const char *)list;
285 CFIndex half = count / 2;
286 const char *probe = ptr + elementSize * half;
287 CFComparisonResult cr = comparator(element, probe, context);
288 if (0 == cr) return (probe - (const char *)list) / elementSize;
289 ptr = (cr < 0) ? ptr : probe + elementSize;
290 count = (cr < 0) ? half : (half + (count & 1) - 1);
292 return (ptr - (const char *)list) / elementSize;
295 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
296 const char *ptr = (const char *)list;
298 CFIndex half = count / 2;
299 const char *probe = ptr + elementSize * half;
300 CFComparisonResult cr = comparator(element, probe, context);
301 if (0 == cr) return (probe - (const char *)list) / elementSize;
302 ptr = (cr < 0) ? ptr : probe + elementSize;
303 count = (cr < 0) ? half : (half + (count & 1) - 1);
305 return (ptr - (const char *)list) / elementSize;
308 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
309 if (range.length == 0)
311 const void **values(new const void *[range.length]);
312 CFArrayGetValues(array, range, values);
314 #if HistogramInsertionSort > 0
315 uint32_t total(0), *offsets(new uint32_t[range.length]);
318 for (CFIndex index(1); index != range.length; ++index) {
319 const void *value(values[index]);
320 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
321 CFIndex correct(index);
322 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
323 #if HistogramInsertionSort > 1
324 NSLog(@"%@ < %@", value, values[correct - 1]);
329 if (correct != index) {
330 size_t offset(index - correct);
331 #if HistogramInsertionSort
335 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
337 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
338 values[correct] = value;
342 CFArrayReplaceValues(array, range, values, range.length);
345 #if HistogramInsertionSort > 0
346 for (CFIndex index(0); index != range.length; ++index)
347 if (offsets[index] != 0)
348 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
349 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
356 /* Apple Bug Fixes {{{ */
357 @implementation UIWebDocumentView (Cydia)
359 - (void) _setScrollerOffset:(CGPoint)offset {
360 UIScroller *scroller([self _scroller]);
362 CGSize size([scroller contentSize]);
363 CGSize bounds([scroller bounds].size);
366 max.x = size.width - bounds.width;
367 max.y = size.height - bounds.height;
375 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
376 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
378 [scroller setOffset:offset];
384 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
385 size_t length([self length] - state->state);
388 else if (length > count)
390 for (size_t i(0); i != length; ++i)
391 objects[i] = [self item:state->state++];
392 state->itemsPtr = objects;
393 state->mutationsPtr = (unsigned long *) self;
397 /* Cydia NSString Additions {{{ */
398 @interface NSString (Cydia)
399 - (NSComparisonResult) compareByPath:(NSString *)other;
400 - (NSString *) stringByCachingURLWithCurrentCDN;
401 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
404 @implementation NSString (Cydia)
406 - (NSComparisonResult) compareByPath:(NSString *)other {
407 NSString *prefix = [self commonPrefixWithString:other options:0];
408 size_t length = [prefix length];
410 NSRange lrange = NSMakeRange(length, [self length] - length);
411 NSRange rrange = NSMakeRange(length, [other length] - length);
413 lrange = [self rangeOfString:@"/" options:0 range:lrange];
414 rrange = [other rangeOfString:@"/" options:0 range:rrange];
416 NSComparisonResult value;
418 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
419 value = NSOrderedSame;
420 else if (lrange.location == NSNotFound)
421 value = NSOrderedAscending;
422 else if (rrange.location == NSNotFound)
423 value = NSOrderedDescending;
425 value = NSOrderedSame;
427 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
428 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
429 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
430 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
432 NSComparisonResult result = [lpath compare:rpath];
433 return result == NSOrderedSame ? value : result;
436 - (NSString *) stringByCachingURLWithCurrentCDN {
438 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
439 withString:@"://cache.cydia.saurik.com/"
443 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
444 return [(id)CFURLCreateStringByAddingPercentEscapes(
449 kCFStringEncodingUTF8
456 /* C++ NSString Wrapper Cache {{{ */
457 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
458 return size == 0 ? NULL :
459 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
460 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
463 static _finline CFStringRef CYStringCreate(const char *data) {
464 return CYStringCreate(data, strlen(data));
473 _finline void clear_() {
474 if (cache_ != NULL) {
481 _finline bool empty() const {
485 _finline size_t size() const {
489 _finline char *data() const {
493 _finline void clear() {
498 _finline CYString() :
505 _finline ~CYString() {
509 void operator =(const CYString &rhs) {
513 if (rhs.cache_ == nil)
516 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
519 void copy(apr_pool_t *pool) {
520 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
521 memcpy(temp, data_, size_);
526 void set(apr_pool_t *pool, const char *data, size_t size) {
532 data_ = const_cast<char *>(data);
540 _finline void set(apr_pool_t *pool, const char *data) {
541 set(pool, data, data == NULL ? 0 : strlen(data));
544 _finline void set(apr_pool_t *pool, const std::string &rhs) {
545 set(pool, rhs.data(), rhs.size());
548 bool operator ==(const CYString &rhs) const {
549 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
552 _finline operator CFStringRef() {
554 cache_ = CYStringCreate(data_, size_);
558 _finline operator id() {
559 return (NSString *) static_cast<CFStringRef>(*this);
562 _finline operator const char *() {
563 return reinterpret_cast<const char *>(data_);
567 /* C++ NSString Algorithm Adapters {{{ */
569 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
572 struct NSStringMapHash :
573 std::unary_function<NSString *, size_t>
575 _finline size_t operator ()(NSString *value) const {
576 return CFStringHashNSString((CFStringRef) value);
580 struct NSStringMapLess :
581 std::binary_function<NSString *, NSString *, bool>
583 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
584 return [lhs compare:rhs] == NSOrderedAscending;
588 struct NSStringMapEqual :
589 std::binary_function<NSString *, NSString *, bool>
591 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
592 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
593 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
594 //[lhs isEqualToString:rhs];
599 /* CoreGraphics Primitives {{{ */
604 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
605 CGFloat color[] = {red, green, blue, alpha};
606 return CGColorCreate(space, color);
615 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
616 color_(Create_(space, red, green, blue, alpha))
618 Set(space, red, green, blue, alpha);
623 CGColorRelease(color_);
630 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
632 color_ = Create_(space, red, green, blue, alpha);
635 operator CGColorRef() {
641 /* Random Global Variables {{{ */
642 static const int PulseInterval_ = 50000;
644 static const NSString *UI_;
647 static bool RestartSubstrate_;
648 static NSArray *Finishes_;
650 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
651 #define NotifyConfig_ "/etc/notify.conf"
653 static bool Queuing_;
655 static CYColor Blue_;
656 static CYColor Blueish_;
657 static CYColor Black_;
659 static CYColor White_;
660 static CYColor Gray_;
661 static CYColor Green_;
662 static CYColor Purple_;
663 static CYColor Purplish_;
665 static UIColor *InstallingColor_;
666 static UIColor *RemovingColor_;
668 static NSString *App_;
670 static BOOL Advanced_;
671 static BOOL Ignored_;
673 static _H<UIFont> Font12_;
674 static _H<UIFont> Font12Bold_;
675 static _H<UIFont> Font14_;
676 static _H<UIFont> Font18Bold_;
677 static _H<UIFont> Font22Bold_;
679 static const char *Machine_ = NULL;
680 static NSString *System_ = nil;
681 static NSString *SerialNumber_ = nil;
682 static NSString *ChipID_ = nil;
683 static NSString *BBSNum_ = nil;
684 static _H<NSString> Token_;
685 static NSString *UniqueID_ = nil;
686 static NSString *PLMN_ = nil;
687 static NSString *Build_ = nil;
688 static NSString *Product_ = nil;
689 static NSString *Safari_ = nil;
691 static CFLocaleRef Locale_;
692 static NSArray *Languages_;
693 static CGColorSpaceRef space_;
695 static NSDictionary *SectionMap_;
696 static NSMutableDictionary *Metadata_;
697 static _transient NSMutableDictionary *Settings_;
698 static _transient NSString *Role_;
699 static _transient NSMutableDictionary *Packages_;
700 static _transient NSMutableDictionary *Values_;
701 static _transient NSMutableDictionary *Sections_;
702 static _transient NSMutableDictionary *Sources_;
703 static _transient NSNumber *Version_;
704 static _transient _H<NSString> CydiaSource_;
705 static bool Changed_;
709 static CGFloat ScreenScale_;
710 static NSString *Idiom_;
712 static _H<NSMutableDictionary> SessionData_;
713 static _H<NSObject> HostConfig_;
714 static _H<NSMutableSet> BridgedHosts_;
715 static _H<NSMutableSet> TokenHosts_;
716 static _H<NSMutableSet> InsecureHosts_;
717 static _H<NSMutableSet> PipelinedHosts_;
718 static _H<NSMutableSet> CachedURLs_;
720 static NSString *kCydiaProgressEventTypeError = @"Error";
721 static NSString *kCydiaProgressEventTypeInformation = @"Information";
722 static NSString *kCydiaProgressEventTypeStatus = @"Status";
723 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
726 static void AddSource(NSDictionary *source) {
727 [Sources_ setObject:source forKey:[NSString stringWithFormat:@"%@:%@:%@", [source objectForKey:@"Type"], [source objectForKey:@"URI"], [source objectForKey:@"Distribution"]]];
731 static void AddSource(NSString *href, NSString *distribution, NSArray *sections = nil) {
732 AddSource([NSMutableDictionary dictionaryWithObjectsAndKeys:
735 distribution, @"Distribution",
736 sections ?: [NSMutableArray array], @"Sections",
740 static void WriteSources() {
741 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
742 _assert(file != NULL);
744 fprintf(file, "deb http://%s/ tangelo main\n",
745 [CydiaSource_ UTF8String]
748 for (NSString *key in [Sources_ allKeys]) {
749 NSDictionary *source([Sources_ objectForKey:key]);
751 NSArray *sections([source objectForKey:@"Sections"] ?: [NSArray array]);
753 fprintf(file, "%s %s %s%s%s\n",
754 [[source objectForKey:@"Type"] UTF8String],
755 [[source objectForKey:@"URI"] UTF8String],
756 [[source objectForKey:@"Distribution"] UTF8String],
757 [sections count] == 0 ? "" : " ",
758 [[sections componentsJoinedByString:@" "] UTF8String]
765 /* Display Helpers {{{ */
766 inline float Interpolate(float begin, float end, float fraction) {
767 return (end - begin) * fraction + begin;
770 static _finline const char *StripVersion_(const char *version) {
771 const char *colon(strchr(version, ':'));
772 return colon == NULL ? version : colon + 1;
775 NSString *LocalizeSection(NSString *section) {
776 static Pcre title_r("^(.*?) \\((.*)\\)$");
777 if (title_r(section)) {
778 NSString *parent(title_r[1]);
779 NSString *child(title_r[2]);
781 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
782 LocalizeSection(parent),
783 LocalizeSection(child)
787 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
790 NSString *Simplify(NSString *title) {
791 const char *data = [title UTF8String];
792 size_t size = [title length];
794 static Pcre square_r("^\\[(.*)\\]$");
795 if (square_r(data, size))
796 return Simplify(square_r[1]);
798 static Pcre paren_r("^\\((.*)\\)$");
799 if (paren_r(data, size))
800 return Simplify(paren_r[1]);
802 static Pcre title_r("^(.*?) \\((.*)\\)$");
803 if (title_r(data, size))
804 return Simplify(title_r[1]);
810 NSString *GetLastUpdate() {
811 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
814 return UCLocalize("NEVER_OR_UNKNOWN");
816 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
817 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
819 CFRelease(formatter);
821 return [(NSString *) formatted autorelease];
824 bool isSectionVisible(NSString *section) {
825 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
826 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
827 return hidden == nil || ![hidden boolValue];
830 static NSObject *CYIOGetValue(const char *path, NSString *property) {
831 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
832 if (entry == MACH_PORT_NULL)
835 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
836 IOObjectRelease(entry);
840 return [(id) value autorelease];
843 static NSString *CYHex(NSData *data, bool reverse = false) {
847 size_t length([data length]);
848 uint8_t bytes[length];
849 [data getBytes:bytes];
851 char string[length * 2 + 1];
852 for (size_t i(0); i != length; ++i)
853 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
855 return [NSString stringWithUTF8String:string];
860 /* Delegate Prototypes {{{ */
863 @class CydiaProgressEvent;
865 @protocol DatabaseDelegate
866 - (void) repairWithSelector:(SEL)selector;
867 - (void) setConfigurationData:(NSString *)data;
868 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
871 @class CYPackageController;
873 @protocol CydiaDelegate
874 - (void) retainNetworkActivityIndicator;
875 - (void) releaseNetworkActivityIndicator;
876 - (void) clearPackage:(Package *)package;
877 - (void) installPackage:(Package *)package;
878 - (void) installPackages:(NSArray *)packages;
879 - (void) removePackage:(Package *)package;
880 - (void) beginUpdate;
882 - (void) distUpgrade;
886 - (void) addSource:(NSDictionary *)source;
887 - (void) addTrivialSource:(NSString *)href;
888 - (void) showSettings;
889 - (UIProgressHUD *) addProgressHUD;
890 - (void) removeProgressHUD:(UIProgressHUD *)hud;
891 - (CyteViewController *) pageForPackage:(NSString *)name;
892 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
893 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
897 /* Status Delegation {{{ */
899 public pkgAcquireStatus
902 _transient NSObject<ProgressDelegate> *delegate_;
912 void setDelegate(NSObject<ProgressDelegate> *delegate) {
913 delegate_ = delegate;
916 NSObject<ProgressDelegate> *getDelegate() const {
920 virtual bool MediaChange(std::string media, std::string drive) {
924 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
927 virtual void Fetch(pkgAcquire::ItemDesc &item) {
928 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
929 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
930 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
933 virtual void Done(pkgAcquire::ItemDesc &item) {
936 virtual void Fail(pkgAcquire::ItemDesc &item) {
938 item.Owner->Status == pkgAcquire::Item::StatIdle ||
939 item.Owner->Status == pkgAcquire::Item::StatDone
943 std::string &error(item.Owner->ErrorText);
947 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
948 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
951 virtual bool Pulse(pkgAcquire *Owner) {
952 bool value = pkgAcquireStatus::Pulse(Owner);
955 double(CurrentBytes + CurrentItems) /
956 double(TotalBytes + TotalItems)
959 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
960 [NSNumber numberWithDouble:percent], @"Percent",
962 [NSNumber numberWithDouble:CurrentBytes], @"Current",
963 [NSNumber numberWithDouble:TotalBytes], @"Total",
964 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
965 nil] waitUntilDone:YES];
967 if (value && ![delegate_ isProgressCancelled])
975 _finline bool WasCancelled() const {
979 virtual void Start() {
980 pkgAcquireStatus::Start();
981 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
984 virtual void Stop() {
985 pkgAcquireStatus::Stop();
986 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
987 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
991 /* Database Interface {{{ */
992 typedef std::map< unsigned long, _H<Source> > SourceMap;
994 @interface Database : NSObject {
1000 pkgCacheFile cache_;
1001 pkgDepCache::Policy *policy_;
1002 pkgRecords *records_;
1003 pkgProblemResolver *resolver_;
1004 pkgAcquire *fetcher_;
1006 SPtr<pkgPackageManager> manager_;
1007 pkgSourceList *list_;
1009 SourceMap sourceMap_;
1010 _H<NSMutableArray> sourceList_;
1012 CFMutableArrayRef packages_;
1014 _transient NSObject<DatabaseDelegate> *delegate_;
1015 _transient NSObject<ProgressDelegate> *progress_;
1023 std::map<const char *, _H<NSString> > sections_;
1026 + (Database *) sharedInstance;
1029 - (void) _readCydia:(NSNumber *)fd;
1030 - (void) _readStatus:(NSNumber *)fd;
1031 - (void) _readOutput:(NSNumber *)fd;
1035 - (Package *) packageWithName:(NSString *)name;
1037 - (pkgCacheFile &) cache;
1038 - (pkgDepCache::Policy *) policy;
1039 - (pkgRecords *) records;
1040 - (pkgProblemResolver *) resolver;
1041 - (pkgAcquire &) fetcher;
1042 - (pkgSourceList &) list;
1043 - (NSArray *) packages;
1044 - (NSArray *) sources;
1045 - (Source *) sourceWithKey:(NSString *)key;
1046 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1054 - (void) updateWithStatus:(Status &)status;
1056 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1058 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1059 - (NSObject<ProgressDelegate> *) progressDelegate;
1061 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1063 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1067 /* ProgressEvent Implementation {{{ */
1068 @implementation CydiaProgressEvent
1070 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1071 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1074 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1075 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1076 [event setPackage:package];
1080 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1081 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1083 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1084 NSArray *fields([description componentsSeparatedByString:@" "]);
1085 [event setItem:fields];
1087 if ([fields count] > 3) {
1088 [event setPackage:[fields objectAtIndex:2]];
1089 [event setVersion:[fields objectAtIndex:3]];
1092 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1097 + (NSArray *) _attributeKeys {
1098 return [NSArray arrayWithObjects:
1108 - (NSArray *) attributeKeys {
1109 return [[self class] _attributeKeys];
1112 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1113 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1116 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1117 if ((self = [super init]) != nil) {
1123 - (NSString *) message {
1127 - (NSString *) type {
1131 - (NSArray *) item {
1132 return (id) item_ ?: [NSNull null];
1135 - (void) setItem:(NSArray *)item {
1139 - (NSString *) package {
1140 return (id) package_ ?: [NSNull null];
1143 - (void) setPackage:(NSString *)package {
1147 - (NSString *) url {
1148 return (id) url_ ?: [NSNull null];
1151 - (void) setURL:(NSString *)url {
1155 - (void) setVersion:(NSString *)version {
1159 - (NSString *) version {
1160 return (id) version_ ?: [NSNull null];
1163 - (NSString *) compound:(NSString *)value {
1165 NSString *mode(nil); {
1166 NSString *type([self type]);
1167 if ([type isEqualToString:kCydiaProgressEventTypeError])
1168 mode = UCLocalize("ERROR");
1169 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1170 mode = UCLocalize("WARNING");
1174 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1180 - (NSString *) compoundMessage {
1181 return [self compound:[self message]];
1184 - (NSString *) compoundTitle {
1187 if (package_ == nil)
1189 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1190 title = [package name];
1194 return [self compound:title];
1200 // Cytore Definitions {{{
1201 struct PackageValue :
1204 Cytore::Offset<PackageValue> next_;
1206 uint32_t index_ : 23;
1207 uint32_t subscribed_ : 1;
1224 Cytore::Offset<PackageValue> packages_[1 << 16];
1227 static Cytore::File<MetaValue> MetaFile_;
1229 // Cytore Helper Functions {{{
1230 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1231 SplitHash nhash = { hashlittle(name, length) };
1233 PackageValue *metadata;
1235 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1236 offset: if (offset->IsNull()) {
1237 *offset = MetaFile_.New<PackageValue>(length + 1);
1238 metadata = &MetaFile_.Get(*offset);
1240 if (metadata == NULL) {
1244 metadata = new PackageValue();
1245 memset(metadata, 0, sizeof(*metadata));
1248 memcpy(metadata->name_, name, length + 1);
1249 metadata->nhash_ = nhash.u16[1];
1251 metadata = &MetaFile_.Get(*offset);
1253 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1254 offset = &metadata->next_;
1262 static void PackageImport(const void *key, const void *value, void *context) {
1263 bool &fail(*reinterpret_cast<bool *>(context));
1266 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1267 NSLog(@"failed to import package %@", key);
1271 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1272 NSDictionary *package((NSDictionary *) value);
1274 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1275 if ([subscribed boolValue] && !metadata->subscribed_)
1276 metadata->subscribed_ = true;
1278 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1279 time_t time([date timeIntervalSince1970]);
1280 if (metadata->first_ > time || metadata->first_ == 0)
1281 metadata->first_ = time;
1284 NSDate *date([package objectForKey:@"LastSeen"]);
1285 NSString *version([package objectForKey:@"LastVersion"]);
1287 if (date != nil && version != nil) {
1288 time_t time([date timeIntervalSince1970]);
1289 if (metadata->last_ < time || metadata->last_ == 0)
1290 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1291 size_t length(strlen(buffer));
1292 uint16_t vhash(hashlittle(buffer, length));
1294 size_t capped(std::min<size_t>(8, length));
1295 char *latest(buffer + length - capped);
1297 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1298 metadata->vhash_ = vhash;
1300 metadata->last_ = time;
1306 /* Source Class {{{ */
1307 @interface Source : NSObject {
1308 CYString depiction_;
1309 CYString description_;
1315 CYString distribution_;
1321 _H<NSString> authority_;
1323 CYString defaultIcon_;
1325 _H<NSDictionary> record_;
1329 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1331 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1333 - (NSString *) depictionForPackage:(NSString *)package;
1334 - (NSString *) supportForPackage:(NSString *)package;
1336 - (NSDictionary *) record;
1340 - (NSString *) distribution;
1341 - (NSString *) type;
1343 - (NSString *) base;
1346 - (NSString *) host;
1348 - (NSString *) name;
1349 - (NSString *) shortDescription;
1350 - (NSString *) label;
1351 - (NSString *) origin;
1352 - (NSString *) version;
1354 - (NSString *) defaultIcon;
1358 @implementation Source
1362 distribution_.clear();
1367 description_.clear();
1373 defaultIcon_.clear();
1380 + (NSString *) webScriptNameForSelector:(SEL)selector {
1382 else if (selector == @selector(addSection:))
1383 return @"addSection";
1384 else if (selector == @selector(removeSection:))
1385 return @"removeSection";
1386 else if (selector == @selector(remove))
1392 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1393 return [self webScriptNameForSelector:selector] == nil;
1396 + (NSArray *) _attributeKeys {
1397 return [NSArray arrayWithObjects:
1405 @"shortDescription",
1413 - (NSArray *) attributeKeys {
1414 return [[self class] _attributeKeys];
1417 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1418 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1421 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1424 trusted_ = index->IsTrusted();
1426 uri_.set(pool, index->GetURI());
1427 distribution_.set(pool, index->GetDist());
1428 type_.set(pool, index->GetType());
1430 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1431 if (dindex != NULL) {
1432 base_.set(pool, dindex->MetaIndexURI(""));
1435 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1438 pkgTagFile tags(&fd);
1440 pkgTagSection section;
1447 {"default-icon", &defaultIcon_},
1448 {"depiction", &depiction_},
1449 {"description", &description_},
1451 {"origin", &origin_},
1452 {"support", &support_},
1453 {"version", &version_},
1456 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1457 const char *start, *end;
1459 if (section.Find(names[i].name_, start, end)) {
1460 CYString &value(*names[i].value_);
1461 value.set(pool, start, end - start);
1467 record_ = [Sources_ objectForKey:[self key]];
1469 NSURL *url([NSURL URLWithString:uri_]);
1473 host_ = [host_ lowercaseString];
1478 authority_ = [url path];
1481 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1482 if ((self = [super init]) != nil) {
1483 [self setMetaIndex:index inPool:pool];
1487 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1488 NSDictionary *lhr = [self record];
1489 NSDictionary *rhr = [source record];
1492 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1494 NSString *lhs = [self name];
1495 NSString *rhs = [source name];
1497 if ([lhs length] != 0 && [rhs length] != 0) {
1498 unichar lhc = [lhs characterAtIndex:0];
1499 unichar rhc = [rhs characterAtIndex:0];
1501 if (isalpha(lhc) && !isalpha(rhc))
1502 return NSOrderedAscending;
1503 else if (!isalpha(lhc) && isalpha(rhc))
1504 return NSOrderedDescending;
1507 return [lhs compare:rhs options:LaxCompareOptions_];
1510 - (NSString *) depictionForPackage:(NSString *)package {
1511 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1514 - (NSString *) supportForPackage:(NSString *)package {
1515 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1518 - (NSArray *) sections {
1519 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1522 - (void) _addSection:(NSString *)section {
1525 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1526 if (![sections containsObject:section]) {
1527 [sections addObject:section];
1531 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1536 - (bool) addSection:(NSString *)section {
1540 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1544 - (void) _removeSection:(NSString *)section {
1548 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1549 if ([sections containsObject:section]) {
1550 [sections removeObject:section];
1555 - (bool) removeSection:(NSString *)section {
1559 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1564 [Sources_ removeObjectForKey:[self key]];
1569 bool value(record_ != nil);
1570 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1574 - (NSDictionary *) record {
1582 - (NSString *) uri {
1586 - (NSString *) distribution {
1587 return distribution_;
1590 - (NSString *) type {
1594 - (NSString *) base {
1598 - (NSString *) key {
1599 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1602 - (NSString *) host {
1606 - (NSString *) name {
1607 return origin_.empty() ? (id) authority_ : origin_;
1610 - (NSString *) shortDescription {
1611 return description_;
1614 - (NSString *) label {
1615 return label_.empty() ? (id) authority_ : label_;
1618 - (NSString *) origin {
1622 - (NSString *) version {
1626 - (NSString *) defaultIcon {
1627 return defaultIcon_;
1632 /* CydiaOperation Class {{{ */
1633 @interface CydiaOperation : NSObject {
1634 _H<NSString> operator_;
1635 _H<NSString> value_;
1638 - (NSString *) operator;
1639 - (NSString *) value;
1643 @implementation CydiaOperation
1645 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1646 if ((self = [super init]) != nil) {
1647 operator_ = [NSString stringWithUTF8String:_operator];
1648 value_ = [NSString stringWithUTF8String:value];
1652 + (NSArray *) _attributeKeys {
1653 return [NSArray arrayWithObjects:
1659 - (NSArray *) attributeKeys {
1660 return [[self class] _attributeKeys];
1663 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1664 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1667 - (NSString *) operator {
1671 - (NSString *) value {
1677 /* CydiaClause Class {{{ */
1678 @interface CydiaClause : NSObject {
1679 _H<NSString> package_;
1680 _H<CydiaOperation> version_;
1683 - (NSString *) package;
1684 - (CydiaOperation *) version;
1688 @implementation CydiaClause
1690 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1691 if ((self = [super init]) != nil) {
1692 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1694 if (const char *version = dep.TargetVer())
1695 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1697 version_ = (id) [NSNull null];
1701 + (NSArray *) _attributeKeys {
1702 return [NSArray arrayWithObjects:
1708 - (NSArray *) attributeKeys {
1709 return [[self class] _attributeKeys];
1712 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1713 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1716 - (NSString *) package {
1720 - (CydiaOperation *) version {
1726 /* CydiaRelation Class {{{ */
1727 @interface CydiaRelation : NSObject {
1728 _H<NSString> relationship_;
1729 _H<NSMutableArray> clauses_;
1732 - (NSString *) relationship;
1733 - (NSArray *) clauses;
1737 @implementation CydiaRelation
1739 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1740 if ((self = [super init]) != nil) {
1741 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1742 clauses_ = [NSMutableArray arrayWithCapacity:8];
1744 pkgCache::DepIterator start;
1745 pkgCache::DepIterator end;
1746 dep.GlobOr(start, end); // ++dep
1749 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1751 // yes, seriously. (wtf?)
1759 + (NSArray *) _attributeKeys {
1760 return [NSArray arrayWithObjects:
1766 - (NSArray *) attributeKeys {
1767 return [[self class] _attributeKeys];
1770 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1771 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1774 - (NSString *) relationship {
1775 return relationship_;
1778 - (NSArray *) clauses {
1782 - (void) addClause:(CydiaClause *)clause {
1783 [clauses_ addObject:clause];
1788 /* Package Class {{{ */
1789 struct ParsedPackage {
1794 CYString depiction_;
1804 @interface Package : NSObject {
1807 uint32_t essential_ : 1;
1808 uint32_t obsolete_ : 1;
1809 uint32_t ignored_ : 1;
1815 _transient Database *database_;
1817 pkgCache::VerIterator version_;
1818 pkgCache::PkgIterator iterator_;
1819 pkgCache::VerFileIterator file_;
1825 CYString installed_;
1827 const char *section_;
1828 _transient NSString *section$_;
1832 PackageValue *metadata_;
1833 ParsedPackage *parsed_;
1835 _H<NSMutableArray> tags_;
1838 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1839 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1841 - (pkgCache::PkgIterator) iterator;
1844 - (NSString *) section;
1845 - (NSString *) simpleSection;
1847 - (NSString *) longSection;
1848 - (NSString *) shortSection;
1852 - (MIMEAddress *) maintainer;
1854 - (NSString *) longDescription;
1855 - (NSString *) shortDescription;
1858 - (PackageValue *) metadata;
1861 - (bool) subscribed;
1862 - (bool) setSubscribed:(bool)subscribed;
1866 - (NSString *) latest;
1867 - (NSString *) installed;
1868 - (BOOL) uninstalled;
1871 - (BOOL) upgradableAndEssential:(BOOL)essential;
1874 - (BOOL) unfiltered;
1878 - (BOOL) halfConfigured;
1879 - (BOOL) halfInstalled;
1881 - (NSString *) mode;
1884 - (NSString *) name;
1886 - (NSString *) homepage;
1887 - (NSString *) depiction;
1888 - (MIMEAddress *) author;
1890 - (NSString *) support;
1892 - (NSArray *) files;
1893 - (NSArray *) warnings;
1894 - (NSArray *) applications;
1896 - (Source *) source;
1899 - (BOOL) matches:(NSArray *)query;
1901 - (bool) hasSupportingRole;
1902 - (BOOL) hasTag:(NSString *)tag;
1903 - (NSString *) primaryPurpose;
1904 - (NSArray *) purposes;
1905 - (bool) isCommercial;
1907 - (void) setIndex:(size_t)index;
1909 - (CYString &) cyname;
1911 - (uint32_t) compareBySection:(NSArray *)sections;
1916 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1917 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1918 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1919 - (bool) isVisibleInSection:(NSString *)section;
1920 - (bool) isVisibleInSource:(Source *)source;
1924 uint32_t PackageChangesRadix(Package *self, void *) {
1929 uint32_t timestamp : 30;
1930 uint32_t ignored : 1;
1931 uint32_t upgradable : 1;
1935 bool upgradable([self upgradableAndEssential:YES]);
1936 value.bits.upgradable = upgradable ? 1 : 0;
1939 value.bits.timestamp = 0;
1940 value.bits.ignored = [self ignored] ? 0 : 1;
1941 value.bits.upgradable = 1;
1943 value.bits.timestamp = [self seen] >> 2;
1944 value.bits.ignored = 0;
1945 value.bits.upgradable = 0;
1948 return _not(uint32_t) - value.key;
1951 uint32_t PackagePrefixRadix(Package *self, void *context) {
1952 size_t offset(reinterpret_cast<size_t>(context));
1953 CYString &name([self cyname]);
1955 size_t size(name.size());
1958 char *text(name.data());
1961 if (!isdigit(text[0]))
1965 while (size != digits && isdigit(text[digits]))
1973 if (offset == 0 && zeros != 0) {
1974 memset(data, '0', zeros);
1975 memcpy(data + zeros, text, 4 - zeros);
1977 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1978 if (size <= offset - zeros)
1981 text += offset - zeros;
1982 size -= offset - zeros;
1985 memcpy(data, text, 4);
1987 memcpy(data, text, size);
1988 memset(data + size, 0, 4 - size);
1991 for (size_t i(0); i != 4; ++i)
1992 if (isalpha(data[i]))
2000 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2002 /* XXX: ntohl may be more honest */
2003 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2006 CYString &(*PackageName)(Package *self, SEL sel);
2008 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2009 _profile(PackageNameCompare)
2010 CYString &lhi(PackageName(lhs, @selector(cyname)));
2011 CYString &rhi(PackageName(rhs, @selector(cyname)));
2012 CFStringRef lhn(lhi), rhn(rhi);
2015 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2016 else if (rhn == NULL)
2017 return NSOrderedDescending;
2019 _profile(PackageNameCompare$NumbersLast)
2020 if (!lhi.empty() && !rhi.empty()) {
2021 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2022 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2023 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2024 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2025 return lha ? NSOrderedAscending : NSOrderedDescending;
2029 CFIndex length = CFStringGetLength(lhn);
2031 _profile(PackageNameCompare$Compare)
2032 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2037 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2038 return PackageNameCompare(*lhs, *rhs, context);
2041 struct PackageNameOrdering :
2042 std::binary_function<Package *, Package *, bool>
2044 _finline bool operator ()(Package *lhs, Package *rhs) const {
2045 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2049 @implementation Package
2051 - (NSString *) description {
2052 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2056 if (parsed_ != NULL)
2061 + (NSString *) webScriptNameForSelector:(SEL)selector {
2063 else if (selector == @selector(clear))
2065 else if (selector == @selector(getField:))
2067 else if (selector == @selector(hasTag:))
2069 else if (selector == @selector(install))
2071 else if (selector == @selector(remove))
2077 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2078 return [self webScriptNameForSelector:selector] == nil;
2081 + (NSArray *) _attributeKeys {
2082 return [NSArray arrayWithObjects:
2101 @"shortDescription",
2114 - (NSArray *) attributeKeys {
2115 return [[self class] _attributeKeys];
2118 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2119 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2122 - (NSArray *) relations {
2123 @synchronized (database_) {
2124 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2125 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2126 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2130 - (NSString *) getField:(NSString *)name {
2131 @synchronized (database_) {
2132 if ([database_ era] != era_ || file_.end())
2135 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2137 const char *start, *end;
2138 if (!parser.Find([name UTF8String], start, end))
2139 return (NSString *) [NSNull null];
2141 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2145 if (parsed_ != NULL)
2147 @synchronized (database_) {
2148 if ([database_ era] != era_ || file_.end())
2151 ParsedPackage *parsed(new ParsedPackage);
2154 _profile(Package$parse)
2155 pkgRecords::Parser *parser;
2157 _profile(Package$parse$Lookup)
2158 parser = &[database_ records]->Lookup(file_);
2163 _profile(Package$parse$Find)
2168 {"icon", &parsed->icon_},
2169 {"depiction", &parsed->depiction_},
2170 {"homepage", &parsed->homepage_},
2171 {"website", &website},
2172 {"bugs", &parsed->bugs_},
2173 {"support", &parsed->support_},
2174 {"sponsor", &parsed->sponsor_},
2175 {"author", &parsed->author_},
2178 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2179 const char *start, *end;
2181 if (parser->Find(names[i].name_, start, end)) {
2182 CYString &value(*names[i].value_);
2183 _profile(Package$parse$Value)
2184 value.set(pool_, start, end - start);
2190 _profile(Package$parse$Tagline)
2191 const char *start, *end;
2192 if (parser->ShortDesc(start, end)) {
2193 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2196 while (stop != start && stop[-1] == '\r')
2198 parsed->tagline_.set(pool_, start, stop - start);
2202 _profile(Package$parse$Retain)
2203 if (parsed->homepage_.empty())
2204 parsed->homepage_ = website;
2205 if (parsed->homepage_ == parsed->depiction_)
2206 parsed->homepage_.clear();
2211 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2212 if ((self = [super init]) != nil) {
2213 _profile(Package$initWithVersion)
2216 database_ = database;
2217 era_ = [database era];
2221 pkgCache::PkgIterator iterator(version.ParentPkg());
2222 iterator_ = iterator;
2224 _profile(Package$initWithVersion$Version)
2225 if (!version_.end())
2226 file_ = version_.FileList();
2228 pkgCache &cache([database_ cache]);
2229 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2233 _profile(Package$initWithVersion$Cache)
2234 name_.set(NULL, iterator.Display());
2236 latest_.set(NULL, StripVersion_(version_.VerStr()));
2238 pkgCache::VerIterator current(iterator.CurrentVer());
2240 installed_.set(NULL, StripVersion_(current.VerStr()));
2243 _profile(Package$initWithVersion$Tags)
2244 pkgCache::TagIterator tag(iterator.TagList());
2246 tags_ = [NSMutableArray arrayWithCapacity:8];
2248 const char *name(tag.Name());
2249 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2251 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2252 if (strcmp(name + 6, "enduser") == 0)
2254 else if (strcmp(name + 6, "hacker") == 0)
2256 else if (strcmp(name + 6, "developer") == 0)
2258 else if (strcmp(name + 6, "cydia") == 0)
2264 if (strncmp(name, "cydia::", 7) == 0) {
2265 if (strcmp(name + 7, "essential") == 0)
2267 else if (strcmp(name + 7, "obsolete") == 0)
2272 } while (!tag.end());
2276 _profile(Package$initWithVersion$Metadata)
2277 const char *mixed(iterator.Name());
2278 size_t size(strlen(mixed));
2279 char lower[size + 1];
2281 for (size_t i(0); i != size; ++i)
2282 lower[i] = mixed[i] | 0x20;
2285 PackageValue *metadata(PackageFind(lower, size));
2286 metadata_ = metadata;
2288 id_.set(NULL, metadata->name_, size);
2290 const char *latest(version_.VerStr());
2291 size_t length(strlen(latest));
2293 uint16_t vhash(hashlittle(latest, length));
2295 size_t capped(std::min<size_t>(8, length));
2296 latest = latest + length - capped;
2298 if (metadata->first_ == 0)
2299 metadata->first_ = now_;
2301 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2302 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2303 metadata->vhash_ = vhash;
2304 metadata->last_ = now_;
2305 } else if (metadata->last_ == 0)
2306 metadata->last_ = metadata->first_;
2309 _profile(Package$initWithVersion$Section)
2310 section_ = iterator.Section();
2313 _profile(Package$initWithVersion$Flags)
2314 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2315 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2320 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2321 pkgCache::VerIterator version;
2323 _profile(Package$packageWithIterator$GetCandidateVer)
2324 version = [database policy]->GetCandidateVer(iterator);
2332 _profile(Package$packageWithIterator$Allocate)
2333 package = [Package allocWithZone:zone];
2336 _profile(Package$packageWithIterator$Initialize)
2338 initWithVersion:version
2345 _profile(Package$packageWithIterator$Autorelease)
2346 package = [package autorelease];
2352 - (pkgCache::PkgIterator) iterator {
2356 - (NSString *) section {
2357 if (section$_ == nil) {
2358 if (section_ == NULL)
2361 _profile(Package$section$mappedSectionForPointer)
2362 section$_ = [database_ mappedSectionForPointer:section_];
2367 - (NSString *) simpleSection {
2368 if (NSString *section = [self section])
2369 return Simplify(section);
2374 - (NSString *) longSection {
2375 return LocalizeSection([self section]);
2378 - (NSString *) shortSection {
2379 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2382 - (NSString *) uri {
2385 pkgIndexFile *index;
2386 pkgCache::PkgFileIterator file(file_.File());
2387 if (![database_ list].FindIndex(file, index))
2389 return [NSString stringWithUTF8String:iterator_->Path];
2390 //return [NSString stringWithUTF8String:file.Site()];
2391 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2395 - (MIMEAddress *) maintainer {
2396 @synchronized (database_) {
2397 if ([database_ era] != era_ || file_.end())
2400 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2401 const std::string &maintainer(parser->Maintainer());
2402 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2406 @synchronized (database_) {
2407 if ([database_ era] != era_ || version_.end())
2410 return version_->InstalledSize;
2413 - (NSString *) longDescription {
2414 @synchronized (database_) {
2415 if ([database_ era] != era_ || file_.end())
2418 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2419 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2421 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2422 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2423 if ([lines count] < 2)
2426 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2427 for (size_t i(1), e([lines count]); i != e; ++i) {
2428 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2429 [trimmed addObject:trim];
2432 return [trimmed componentsJoinedByString:@"\n"];
2435 - (NSString *) shortDescription {
2436 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2440 _profile(Package$index)
2441 CFStringRef name((CFStringRef) [self name]);
2442 if (CFStringGetLength(name) == 0)
2444 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2445 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2447 return toupper(character);
2451 - (PackageValue *) metadata {
2456 PackageValue *metadata([self metadata]);
2457 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2460 - (bool) subscribed {
2461 return [self metadata]->subscribed_;
2464 - (bool) setSubscribed:(bool)subscribed {
2465 PackageValue *metadata([self metadata]);
2466 if (metadata->subscribed_ == subscribed)
2468 metadata->subscribed_ = subscribed;
2476 - (NSString *) latest {
2480 - (NSString *) installed {
2484 - (BOOL) uninstalled {
2485 return installed_.empty();
2489 return !version_.end();
2492 - (BOOL) upgradableAndEssential:(BOOL)essential {
2493 _profile(Package$upgradableAndEssential)
2494 pkgCache::VerIterator current(iterator_.CurrentVer());
2496 return essential && essential_;
2498 return !version_.end() && version_ != current;
2502 - (BOOL) essential {
2507 return [database_ cache][iterator_].InstBroken();
2510 - (BOOL) unfiltered {
2511 _profile(Package$unfiltered$obsolete)
2512 if (_unlikely(obsolete_))
2516 _profile(Package$unfiltered$hasSupportingRole)
2517 if (_unlikely(![self hasSupportingRole]))
2525 if (![self unfiltered])
2530 _profile(Package$visible$section)
2531 section = [self section];
2534 _profile(Package$visible$isSectionVisible)
2535 if (!isSectionVisible(section))
2543 unsigned char current(iterator_->CurrentState);
2544 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2547 - (BOOL) halfConfigured {
2548 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2551 - (BOOL) halfInstalled {
2552 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2556 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2557 return state.Mode != pkgDepCache::ModeKeep;
2560 - (NSString *) mode {
2561 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2563 switch (state.Mode) {
2564 case pkgDepCache::ModeDelete:
2565 if ((state.iFlags & pkgDepCache::Purge) != 0)
2569 case pkgDepCache::ModeKeep:
2570 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2571 return @"REINSTALL";
2572 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2576 case pkgDepCache::ModeInstall:
2577 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2578 return @"REINSTALL";
2579 else*/ switch (state.Status) {
2581 return @"DOWNGRADE";
2587 return @"NEW_INSTALL";
2598 - (NSString *) name {
2599 return name_.empty() ? id_ : name_;
2602 - (UIImage *) icon {
2603 NSString *section = [self simpleSection];
2606 if (parsed_ != NULL)
2607 if (NSString *href = parsed_->icon_)
2608 if ([href hasPrefix:@"file:///"])
2609 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2610 if (icon == nil) if (section != nil)
2611 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2612 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2613 if ([dicon hasPrefix:@"file:///"])
2614 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2616 icon = [UIImage applicationImageNamed:@"unknown.png"];
2620 - (NSString *) homepage {
2621 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2624 - (NSString *) depiction {
2625 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2628 - (MIMEAddress *) sponsor {
2629 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2632 - (MIMEAddress *) author {
2633 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2636 - (NSString *) support {
2637 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2640 - (NSArray *) files {
2641 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2642 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2645 fin.open([path UTF8String]);
2650 while (std::getline(fin, line))
2651 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2656 - (NSString *) state {
2657 @synchronized (database_) {
2658 if ([database_ era] != era_ || file_.end())
2661 switch (iterator_->CurrentState) {
2662 case pkgCache::State::NotInstalled:
2663 return @"NotInstalled";
2664 case pkgCache::State::UnPacked:
2666 case pkgCache::State::HalfConfigured:
2667 return @"HalfConfigured";
2668 case pkgCache::State::HalfInstalled:
2669 return @"HalfInstalled";
2670 case pkgCache::State::ConfigFiles:
2671 return @"ConfigFiles";
2672 case pkgCache::State::Installed:
2673 return @"Installed";
2674 case pkgCache::State::TriggersAwaited:
2675 return @"TriggersAwaited";
2676 case pkgCache::State::TriggersPending:
2677 return @"TriggersPending";
2680 return (NSString *) [NSNull null];
2683 - (NSString *) selection {
2684 @synchronized (database_) {
2685 if ([database_ era] != era_ || file_.end())
2688 switch (iterator_->SelectedState) {
2689 case pkgCache::State::Unknown:
2691 case pkgCache::State::Install:
2693 case pkgCache::State::Hold:
2695 case pkgCache::State::DeInstall:
2696 return @"DeInstall";
2697 case pkgCache::State::Purge:
2701 return (NSString *) [NSNull null];
2704 - (NSArray *) warnings {
2705 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2706 const char *name(iterator_.Name());
2708 size_t length(strlen(name));
2709 if (length < 2) invalid:
2710 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2711 else for (size_t i(0); i != length; ++i)
2713 /* XXX: technically this is not allowed */
2714 (name[i] < 'A' || name[i] > 'Z') &&
2715 (name[i] < 'a' || name[i] > 'z') &&
2716 (name[i] < '0' || name[i] > '9') &&
2717 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2720 if (strcmp(name, "cydia") != 0) {
2723 bool _private = false;
2726 bool repository = [[self section] isEqualToString:@"Repositories"];
2728 if (NSArray *files = [self files])
2729 for (NSString *file in files)
2730 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2732 else if (!user && [file isEqualToString:@"/User"])
2734 else if (!_private && [file isEqualToString:@"/private"])
2736 else if (!stash && [file isEqualToString:@"/var/stash"])
2739 /* XXX: this is not sensitive enough. only some folders are valid. */
2740 if (cydia && !repository)
2741 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2743 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2745 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2747 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2750 return [warnings count] == 0 ? nil : warnings;
2753 - (NSArray *) applications {
2754 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2756 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2758 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2759 if (NSArray *files = [self files])
2760 for (NSString *file in files)
2761 if (application_r(file)) {
2762 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2763 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2764 if ([id isEqualToString:me])
2767 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2769 display = application_r[1];
2771 NSString *bundle([file stringByDeletingLastPathComponent]);
2772 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2773 if (icon == nil || [icon length] == 0)
2775 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2777 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2778 [applications addObject:application];
2780 [application addObject:id];
2781 [application addObject:display];
2782 [application addObject:url];
2785 return [applications count] == 0 ? nil : applications;
2788 - (Source *) source {
2789 if (source_ == nil) {
2790 @synchronized (database_) {
2791 if ([database_ era] != era_ || file_.end())
2792 source_ = (Source *) [NSNull null];
2794 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2798 return source_ == (Source *) [NSNull null] ? nil : source_;
2805 - (BOOL) matches:(NSArray *)query {
2806 if (query == nil || [query count] == 0)
2817 string = [self name];
2818 length = [string length];
2820 for (NSString *term in query) {
2821 range = [string rangeOfString:term options:MatchCompareOptions_];
2822 if (range.location != NSNotFound)
2823 rank_ -= 6 * 1000000 / length;
2828 length = [string length];
2830 for (NSString *term in query) {
2831 range = [string rangeOfString:term options:MatchCompareOptions_];
2832 if (range.location != NSNotFound)
2833 rank_ -= 6 * 1000000 / length;
2837 string = [self shortDescription];
2838 length = [string length];
2839 NSUInteger stop(std::min<NSUInteger>(length, 100));
2841 for (NSString *term in query) {
2842 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2843 if (range.location != NSNotFound)
2844 rank_ -= 2 * 100000;
2850 - (bool) hasSupportingRole {
2855 if ([Role_ isEqualToString:@"User"])
2859 if ([Role_ isEqualToString:@"Hacker"])
2863 if ([Role_ isEqualToString:@"Developer"])
2868 - (NSArray *) tags {
2872 - (BOOL) hasTag:(NSString *)tag {
2873 return tags_ == nil ? NO : [tags_ containsObject:tag];
2876 - (NSString *) primaryPurpose {
2877 for (NSString *tag in (NSArray *) tags_)
2878 if ([tag hasPrefix:@"purpose::"])
2879 return [tag substringFromIndex:9];
2883 - (NSArray *) purposes {
2884 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2885 for (NSString *tag in (NSArray *) tags_)
2886 if ([tag hasPrefix:@"purpose::"])
2887 [purposes addObject:[tag substringFromIndex:9]];
2888 return [purposes count] == 0 ? nil : purposes;
2891 - (bool) isCommercial {
2892 return [self hasTag:@"cydia::commercial"];
2895 - (void) setIndex:(size_t)index {
2896 if (metadata_->index_ != index)
2897 metadata_->index_ = index;
2900 - (CYString &) cyname {
2901 return name_.empty() ? id_ : name_;
2904 - (uint32_t) compareBySection:(NSArray *)sections {
2905 NSString *section([self section]);
2906 for (size_t i(0), e([sections count]); i != e; ++i) {
2907 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2911 return _not(uint32_t);
2915 @synchronized (database_) {
2916 pkgProblemResolver *resolver = [database_ resolver];
2917 resolver->Clear(iterator_);
2919 pkgCacheFile &cache([database_ cache]);
2920 cache->SetReInstall(iterator_, false);
2921 cache->MarkKeep(iterator_, false);
2925 @synchronized (database_) {
2926 pkgProblemResolver *resolver = [database_ resolver];
2927 resolver->Clear(iterator_);
2928 resolver->Protect(iterator_);
2930 pkgCacheFile &cache([database_ cache]);
2931 cache->SetReInstall(iterator_, false);
2932 cache->MarkInstall(iterator_, false);
2934 pkgDepCache::StateCache &state((*cache)[iterator_]);
2935 if (!state.Install())
2936 cache->SetReInstall(iterator_, true);
2940 @synchronized (database_) {
2941 pkgProblemResolver *resolver = [database_ resolver];
2942 resolver->Clear(iterator_);
2943 resolver->Remove(iterator_);
2944 resolver->Protect(iterator_);
2946 pkgCacheFile &cache([database_ cache]);
2947 cache->SetReInstall(iterator_, false);
2948 cache->MarkDelete(iterator_, true);
2951 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2952 _profile(Package$isUnfilteredAndSearchedForBy)
2955 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2956 value &= [self unfiltered];
2959 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2960 value &= [self matches:query];
2967 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2968 if ([search length] == 0)
2971 _profile(Package$isUnfilteredAndSelectedForBy)
2974 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2975 value &= [self unfiltered];
2978 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2979 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2986 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2987 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2990 - (bool) isVisibleInSection:(NSString *)name {
2991 NSString *section([self section]);
2995 section == nil && [name length] == 0 ||
2996 [name isEqualToString:section]
2997 ) && [self visible];
3000 - (bool) isVisibleInSource:(Source *)source {
3001 return [self source] == source && [self visible];
3006 /* Section Class {{{ */
3007 @interface Section : NSObject {
3012 _H<NSString> localized_;
3015 - (NSComparisonResult) compareByLocalized:(Section *)section;
3016 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3017 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3018 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3019 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3020 - (NSString *) name;
3027 - (void) addToCount;
3029 - (void) setCount:(size_t)count;
3030 - (NSString *) localized;
3034 @implementation Section
3036 - (NSComparisonResult) compareByLocalized:(Section *)section {
3037 NSString *lhs(localized_);
3038 NSString *rhs([section localized]);
3040 /*if ([lhs length] != 0 && [rhs length] != 0) {
3041 unichar lhc = [lhs characterAtIndex:0];
3042 unichar rhc = [rhs characterAtIndex:0];
3044 if (isalpha(lhc) && !isalpha(rhc))
3045 return NSOrderedAscending;
3046 else if (!isalpha(lhc) && isalpha(rhc))
3047 return NSOrderedDescending;
3050 return [lhs compare:rhs options:LaxCompareOptions_];
3053 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3054 if ((self = [self initWithName:name localize:NO]) != nil) {
3055 if (localized != nil)
3056 localized_ = localized;
3060 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3061 return [self initWithName:name row:0 localize:localize];
3064 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3065 if ((self = [super init]) != nil) {
3070 localized_ = LocalizeSection(name_);
3074 /* XXX: localize the index thingees */
3075 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3076 if ((self = [super init]) != nil) {
3077 name_ = [NSString stringWithCharacters:&index length:1];
3083 - (NSString *) name {
3103 - (void) addToCount {
3107 - (void) setCount:(size_t)count {
3111 - (NSString *) localized {
3118 static NSString *Colon_;
3120 static NSString *Error_;
3121 static NSString *Warning_;
3123 class CydiaLogCleaner :
3124 public pkgArchiveCleaner
3127 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3132 /* Database Implementation {{{ */
3133 @implementation Database
3135 + (Database *) sharedInstance {
3136 static _H<Database> instance;
3137 if (instance == nil)
3138 instance = [[[Database alloc] init] autorelease];
3146 - (void) releasePackages {
3147 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3148 CFArrayRemoveAllValues(packages_);
3152 // XXX: actually implement this thing
3154 [self releasePackages];
3155 apr_pool_destroy(pool_);
3156 NSRecycleZone(zone_);
3160 - (void) _readCydia:(NSNumber *)fd {
3161 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3162 std::istream is(&ib);
3165 static Pcre finish_r("^finish:([^:]*)$");
3167 while (std::getline(is, line)) {
3168 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3170 const char *data(line.c_str());
3171 size_t size = line.size();
3172 lprintf("C:%s\n", data);
3174 if (finish_r(data, size)) {
3175 NSString *finish = finish_r[1];
3176 int index = [Finishes_ indexOfObject:finish];
3177 if (index != INT_MAX && index > Finish_)
3187 - (void) _readStatus:(NSNumber *)fd {
3188 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3189 std::istream is(&ib);
3192 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3193 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3195 while (std::getline(is, line)) {
3196 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3198 const char *data(line.c_str());
3199 size_t size(line.size());
3200 lprintf("S:%s\n", data);
3202 if (conffile_r(data, size)) {
3203 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3204 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3205 } else if (strncmp(data, "status: ", 8) == 0) {
3206 // status: <package>: {unpacked,half-configured,installed}
3207 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3208 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3209 } else if (strncmp(data, "processing: ", 12) == 0) {
3210 // processing: configure: config-test
3211 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3212 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3213 } else if (pmstatus_r(data, size)) {
3214 std::string type([pmstatus_r[1] UTF8String]);
3216 NSString *package = pmstatus_r[2];
3217 if ([package isEqualToString:@"dpkg-exec"])
3220 float percent([pmstatus_r[3] floatValue]);
3221 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3223 NSString *string = pmstatus_r[4];
3225 if (type == "pmerror") {
3226 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3227 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3228 } else if (type == "pmstatus") {
3229 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3230 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3231 } else if (type == "pmconffile")
3232 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3234 lprintf("E:unknown pmstatus\n");
3236 lprintf("E:unknown status\n");
3244 - (void) _readOutput:(NSNumber *)fd {
3245 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3246 std::istream is(&ib);
3249 while (std::getline(is, line)) {
3250 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3252 lprintf("O:%s\n", line.c_str());
3254 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3255 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3267 - (Package *) packageWithName:(NSString *)name {
3268 @synchronized (self) {
3269 if (static_cast<pkgDepCache *>(cache_) == NULL)
3271 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3272 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3276 if ((self = [super init]) != nil) {
3283 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3284 apr_pool_create(&pool_, NULL);
3286 size_t capacity(MetaFile_->active_);
3292 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3293 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3297 _assert(pipe(fds) != -1);
3300 _config->Set("APT::Keep-Fds::", cydiafd_);
3301 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3304 detachNewThreadSelector:@selector(_readCydia:)
3306 withObject:[NSNumber numberWithInt:fds[0]]
3309 _assert(pipe(fds) != -1);
3313 detachNewThreadSelector:@selector(_readStatus:)
3315 withObject:[NSNumber numberWithInt:fds[0]]
3318 _assert(pipe(fds) != -1);
3319 _assert(dup2(fds[0], 0) != -1);
3320 _assert(close(fds[0]) != -1);
3322 input_ = fdopen(fds[1], "a");
3324 _assert(pipe(fds) != -1);
3325 _assert(dup2(fds[1], 1) != -1);
3326 _assert(close(fds[1]) != -1);
3329 detachNewThreadSelector:@selector(_readOutput:)
3331 withObject:[NSNumber numberWithInt:fds[0]]
3336 - (pkgCacheFile &) cache {
3340 - (pkgDepCache::Policy *) policy {
3344 - (pkgRecords *) records {
3348 - (pkgProblemResolver *) resolver {
3352 - (pkgAcquire &) fetcher {
3356 - (pkgSourceList &) list {
3360 - (NSArray *) packages {
3361 return (NSArray *) packages_;
3364 - (NSArray *) sources {
3368 - (Source *) sourceWithKey:(NSString *)key {
3369 for (Source *source in [self sources]) {
3370 if ([[source key] isEqualToString:key])
3375 - (bool) popErrorWithTitle:(NSString *)title {
3378 while (!_error->empty()) {
3380 bool warning(!_error->PopMessage(error));
3385 size_t size(error.size());
3386 if (size == 0 || error[size - 1] != '\n')
3388 error.resize(size - 1);
3391 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3393 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3399 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3400 return [self popErrorWithTitle:title] || !success;
3403 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3404 @synchronized (self) {
3407 [self releasePackages];
3410 [sourceList_ removeAllObjects];
3430 apr_pool_clear(pool_);
3432 NSRecycleZone(zone_);
3433 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3435 int chk(creat("/tmp/cydia.chk", 0644));
3439 if (invocation != nil)
3440 [invocation invoke];
3442 NSString *title(UCLocalize("DATABASE"));
3445 OpProgress progress;
3446 while (!cache_.Open(progress, true)) { pop:
3448 bool warning(!_error->PopMessage(error));
3449 lprintf("cache_.Open():[%s]\n", error.c_str());
3451 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3452 [delegate_ repairWithSelector:@selector(configure)];
3453 else if (error == "The package lists or status file could not be parsed or opened.")
3454 [delegate_ repairWithSelector:@selector(update)];
3455 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3456 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3457 // else if (error == "Malformed Status line")
3458 // else if (error == "The list of sources could not be read.")
3460 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3470 unlink("/tmp/cydia.chk");
3472 now_ = [[NSDate date] timeIntervalSince1970];
3474 policy_ = new pkgDepCache::Policy();
3475 records_ = new pkgRecords(cache_);
3476 resolver_ = new pkgProblemResolver(cache_);
3477 fetcher_ = new pkgAcquire(&status_);
3480 list_ = new pkgSourceList();
3481 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3484 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3485 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3489 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3492 if (cache_->BrokenCount() != 0) {
3493 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3496 if (cache_->BrokenCount() != 0) {
3497 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3501 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3505 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3506 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3507 [sourceList_ addObject:object];
3509 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3510 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3511 // XXX: this could be more intelligent
3512 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3513 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3515 sourceMap_[cached->ID] = object;
3520 /*std::vector<Package *> packages;
3521 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3526 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3527 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3528 //packages.push_back(package);
3529 CFArrayAppendValue(packages_, CFRetain(package));
3533 /*if (packages.empty())
3534 packages_ = [[NSArray alloc] init];
3536 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3539 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3540 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3541 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3549 /*if (!packages.empty())
3550 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3551 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3553 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3555 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3557 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3561 size_t count(CFArrayGetCount(packages_));
3562 MetaFile_->active_ = count;
3564 for (size_t index(0); index != count; ++index)
3565 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3572 @synchronized (self) {
3574 resolver_ = new pkgProblemResolver(cache_);
3576 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3577 if (!cache_[iterator].Keep())
3578 cache_->MarkKeep(iterator, false);
3579 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3580 cache_->SetReInstall(iterator, false);
3583 - (void) configure {
3584 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3586 system([dpkg UTF8String]);
3591 // XXX: I don't remember this condition
3596 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3598 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3600 if ([self popErrorWithTitle:title])
3604 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3606 CydiaLogCleaner cleaner;
3607 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3614 fetcher_->Shutdown();
3616 pkgRecords records(cache_);
3618 lock_ = new FileFd();
3619 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3621 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3623 if ([self popErrorWithTitle:title])
3627 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3630 manager_ = (_system->CreatePM(cache_));
3631 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3638 bool substrate(RestartSubstrate_);
3639 RestartSubstrate_ = false;
3641 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3643 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3645 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3647 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3648 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3651 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3653 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3655 [self popErrorWithTitle:title];
3659 bool failed = false;
3660 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3661 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3663 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3669 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3677 RestartSubstrate_ = true;
3680 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3682 if (_error->PendingError()) {
3687 if (result == pkgPackageManager::Failed) {
3692 if (result != pkgPackageManager::Completed) {
3697 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3699 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3701 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3702 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3705 if (![before isEqualToArray:after])
3710 NSString *title(UCLocalize("UPGRADE"));
3711 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3717 [self updateWithStatus:status_];
3720 - (void) updateWithStatus:(Status &)status {
3721 NSString *title(UCLocalize("REFRESHING_DATA"));
3724 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3728 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3729 if ([self popErrorWithTitle:title])
3732 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3734 bool success(ListUpdate(status, list, PulseInterval_));
3735 if (status.WasCancelled())
3738 [self popErrorWithTitle:title forOperation:success];
3739 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3743 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3746 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3747 delegate_ = delegate;
3750 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3751 progress_ = delegate;
3752 status_.setDelegate(delegate);
3755 - (NSObject<ProgressDelegate> *) progressDelegate {
3759 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3760 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3761 return i == sourceMap_.end() ? nil : i->second;
3764 - (NSString *) mappedSectionForPointer:(const char *)section {
3765 _H<NSString> *mapped;
3767 _profile(Database$mappedSectionForPointer$Cache)
3768 mapped = §ions_[section];
3771 if (*mapped == NULL) {
3772 size_t length(strlen(section));
3773 char spaced[length + 1];
3775 _profile(Database$mappedSectionForPointer$Replace)
3776 for (size_t index(0); index != length; ++index)
3777 spaced[index] = section[index] == '_' ? ' ' : section[index];
3778 spaced[length] = '\0';
3783 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3784 string = [NSString stringWithUTF8String:spaced];
3787 _profile(Database$mappedSectionForPointer$Map)
3788 string = [SectionMap_ objectForKey:string] ?: string;
3798 static _H<NSMutableSet> Diversions_;
3800 @interface Diversion : NSObject {
3803 _H<NSString> format_;
3808 @implementation Diversion
3810 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3811 if ((self = [super init]) != nil) {
3812 pattern_ = [from UTF8String];
3818 - (NSString *) divert:(NSString *)url {
3819 return !pattern_(url) ? nil : pattern_->*format_;
3822 + (NSURL *) divertURL:(NSURL *)url {
3824 NSString *href([url absoluteString]);
3826 for (Diversion *diversion in (id) Diversions_)
3827 if (NSString *diverted = [diversion divert:href]) {
3829 NSLog(@"div: %@", diverted);
3831 url = [NSURL URLWithString:diverted];
3838 - (NSString *) key {
3842 - (NSUInteger) hash {
3846 - (BOOL) isEqual:(Diversion *)object {
3847 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3852 @interface CydiaObject : NSObject {
3853 _H<IndirectDelegate> indirect_;
3854 _transient id delegate_;
3857 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3861 @interface CydiaWebViewController : CyteWebViewController {
3862 _H<CydiaObject> cydia_;
3865 + (void) addDiversion:(Diversion *)diversion;
3869 /* Web Scripting {{{ */
3870 @implementation CydiaObject
3872 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3873 if ((self = [super init]) != nil) {
3874 indirect_ = indirect;
3878 - (void) setDelegate:(id)delegate {
3879 delegate_ = delegate;
3882 + (NSArray *) _attributeKeys {
3883 return [NSArray arrayWithObjects:
3900 - (NSArray *) attributeKeys {
3901 return [[self class] _attributeKeys];
3904 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3905 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3908 - (NSString *) version {
3912 - (NSString *) device {
3913 return [[UIDevice currentDevice] uniqueIdentifier];
3916 - (NSString *) firmware {
3917 return [[UIDevice currentDevice] systemVersion];
3920 - (NSString *) hostname {
3921 return [[UIDevice currentDevice] name];
3924 - (NSString *) idiom {
3925 return (id) Idiom_ ?: [NSNull null];
3928 - (NSString *) plmn {
3929 return (id) PLMN_ ?: [NSNull null];
3932 - (NSString *) bbsnum {
3933 return (id) BBSNum_ ?: [NSNull null];
3936 - (NSString *) ecid {
3937 return (id) ChipID_ ?: [NSNull null];
3940 - (NSString *) serial {
3941 return SerialNumber_;
3944 - (NSString *) role {
3945 return (id) Role_ ?: [NSNull null];
3948 - (NSString *) model {
3949 return [NSString stringWithUTF8String:Machine_];
3952 - (NSString *) token {
3953 return (id) Token_ ?: [NSNull null];
3956 + (NSString *) webScriptNameForSelector:(SEL)selector {
3958 else if (selector == @selector(addBridgedHost:))
3959 return @"addBridgedHost";
3960 else if (selector == @selector(addInsecureHost:))
3961 return @"addInsecureHost";
3962 else if (selector == @selector(addInternalRedirect::))
3963 return @"addInternalRedirect";
3964 else if (selector == @selector(addPipelinedHost:scheme:))
3965 return @"addPipelinedHost";
3966 else if (selector == @selector(addSource:::))
3967 return @"addSource";
3968 else if (selector == @selector(addTokenHost:))
3969 return @"addTokenHost";
3970 else if (selector == @selector(addTrivialSource:))
3971 return @"addTrivialSource";
3972 else if (selector == @selector(close))
3974 else if (selector == @selector(du:))
3976 else if (selector == @selector(stringWithFormat:arguments:))
3978 else if (selector == @selector(getAllSources))
3979 return @"getAllSourcs";
3980 else if (selector == @selector(getKernelNumber:))
3981 return @"getKernelNumber";
3982 else if (selector == @selector(getKernelString:))
3983 return @"getKernelString";
3984 else if (selector == @selector(getInstalledPackages))
3985 return @"getInstalledPackages";
3986 else if (selector == @selector(getIORegistryEntry::))
3987 return @"getIORegistryEntry";
3988 else if (selector == @selector(getLocaleIdentifier))
3989 return @"getLocaleIdentifier";
3990 else if (selector == @selector(getPreferredLanguages))
3991 return @"getPreferredLanguages";
3992 else if (selector == @selector(getPackageById:))
3993 return @"getPackageById";
3994 else if (selector == @selector(getMetadataKeys))
3995 return @"getMetadataKeys";
3996 else if (selector == @selector(getMetadataValue:))
3997 return @"getMetadataValue";
3998 else if (selector == @selector(getSessionValue:))
3999 return @"getSessionValue";
4000 else if (selector == @selector(installPackages:))
4001 return @"installPackages";
4002 else if (selector == @selector(localizedStringForKey:value:table:))
4004 else if (selector == @selector(popViewController:))
4005 return @"popViewController";
4006 else if (selector == @selector(refreshSources))
4007 return @"refreshSources";
4008 else if (selector == @selector(removeButton))
4009 return @"removeButton";
4010 else if (selector == @selector(saveConfig))
4011 return @"saveConfig";
4012 else if (selector == @selector(setCydiaSource:))
4013 return @"setCydiaSource";
4014 else if (selector == @selector(setMetadataValue::))
4015 return @"setMetadataValue";
4016 else if (selector == @selector(setSessionValue::))
4017 return @"setSessionValue";
4018 else if (selector == @selector(substitutePackageNames:))
4019 return @"substitutePackageNames";
4020 else if (selector == @selector(scrollToBottom:))
4021 return @"scrollToBottom";
4022 else if (selector == @selector(setAllowsNavigationAction:))
4023 return @"setAllowsNavigationAction";
4024 else if (selector == @selector(setBadgeValue:))
4025 return @"setBadgeValue";
4026 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4027 return @"setButtonImage";
4028 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4029 return @"setButtonTitle";
4030 else if (selector == @selector(setHidesBackButton:))
4031 return @"setHidesBackButton";
4032 else if (selector == @selector(setHidesNavigationBar:))
4033 return @"setHidesNavigationBar";
4034 else if (selector == @selector(setNavigationBarStyle:))
4035 return @"setNavigationBarStyle";
4036 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4037 return @"setNavigationBarTintColor";
4038 else if (selector == @selector(setPasteboardString:))
4039 return @"setPasteboardString";
4040 else if (selector == @selector(setPasteboardURL:))
4041 return @"setPasteboardURL";
4042 else if (selector == @selector(setToken:))
4044 else if (selector == @selector(setViewportWidth:))
4045 return @"setViewportWidth";
4046 else if (selector == @selector(statfs:))
4048 else if (selector == @selector(supports:))
4050 else if (selector == @selector(unload))
4056 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4057 return [self webScriptNameForSelector:selector] == nil;
4060 - (BOOL) supports:(NSString *)feature {
4061 return [feature isEqualToString:@"window.open"];
4065 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4068 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4069 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4072 - (NSNumber *) getKernelNumber:(NSString *)name {
4073 const char *string([name UTF8String]);
4076 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4077 return (id) [NSNull null];
4079 if (size != sizeof(int))
4080 return (id) [NSNull null];
4083 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4084 return (id) [NSNull null];
4086 return [NSNumber numberWithInt:value];
4089 - (NSString *) getKernelString:(NSString *)name {
4090 const char *string([name UTF8String]);
4093 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4094 return (id) [NSNull null];
4096 char value[size + 1];
4097 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4098 return (id) [NSNull null];
4100 // XXX: just in case you request something ludicrous
4103 return [NSString stringWithCString:value];
4106 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4107 NSObject *value(CYIOGetValue([path UTF8String], entry));
4110 if ([value isKindOfClass:[NSData class]])
4111 value = CYHex((NSData *) value);
4116 - (void) _setCydiaSource:(NSString *)source {
4117 @synchronized (HostConfig_) {
4118 CydiaSource_ = source;
4119 [Metadata_ setObject:source forKey:@"CydiaSource"];
4125 - (void) setCydiaSource:(NSString *)source {
4126 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4129 - (NSString *) cydiaSource {
4130 @synchronized (HostConfig_) {
4131 return (id) CydiaSource_ ?: [NSNull null];
4135 - (NSArray *) getMetadataKeys {
4136 @synchronized (Values_) {
4137 return [Values_ allKeys];
4140 - (id) getMetadataValue:(NSString *)key {
4141 @synchronized (Values_) {
4142 return [Values_ objectForKey:key];
4145 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4146 @synchronized (Values_) {
4147 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4148 [Values_ removeObjectForKey:key];
4150 [Values_ setObject:value forKey:key];
4152 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4155 - (id) getSessionValue:(NSString *)key {
4156 @synchronized (SessionData_) {
4157 return [SessionData_ objectForKey:key];
4160 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4161 @synchronized (SessionData_) {
4162 if (value == (id) [WebUndefined undefined])
4163 [SessionData_ removeObjectForKey:key];
4165 [SessionData_ setObject:value forKey:key];
4168 - (void) addBridgedHost:(NSString *)host {
4169 @synchronized (HostConfig_) {
4170 [BridgedHosts_ addObject:host];
4173 - (void) addInsecureHost:(NSString *)host {
4174 @synchronized (HostConfig_) {
4175 [InsecureHosts_ addObject:host];
4178 - (void) addTokenHost:(NSString *)host {
4179 @synchronized (HostConfig_) {
4180 [TokenHosts_ addObject:host];
4183 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4184 @synchronized (HostConfig_) {
4185 if (scheme != (id) [WebUndefined undefined])
4186 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4188 [PipelinedHosts_ addObject:host];
4191 - (void) popViewController:(NSNumber *)value {
4192 if (value == (id) [WebUndefined undefined])
4193 value = [NSNumber numberWithBool:YES];
4194 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4197 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4198 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4200 for (NSString *section in sections)
4201 [array addObject:section];
4203 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4206 distribution, @"Distribution",
4208 nil] waitUntilDone:NO];
4211 - (void) addTrivialSource:(NSString *)href {
4212 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4215 - (void) refreshSources {
4216 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4219 - (void) saveConfig {
4220 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4223 - (NSArray *) getAllSources {
4224 return [[Database sharedInstance] sources];
4227 - (NSArray *) getInstalledPackages {
4228 Database *database([Database sharedInstance]);
4229 @synchronized (database) {
4230 NSArray *packages([database packages]);
4231 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4232 for (Package *package in packages)
4233 if (![package uninstalled])
4234 [installed addObject:package];
4238 - (Package *) getPackageById:(NSString *)id {
4239 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4243 return (Package *) [NSNull null];
4246 - (NSString *) getLocaleIdentifier {
4247 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4250 - (NSArray *) getPreferredLanguages {
4254 - (NSArray *) statfs:(NSString *)path {
4257 if (path == nil || statfs([path UTF8String], &stat) == -1)
4260 return [NSArray arrayWithObjects:
4261 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4262 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4263 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4267 - (NSNumber *) du:(NSString *)path {
4268 NSNumber *value(nil);
4271 _assert(pipe(fds) != -1);
4273 pid_t pid(ExecFork());
4275 _assert(dup2(fds[1], 1) != -1);
4276 _assert(close(fds[0]) != -1);
4277 _assert(close(fds[1]) != -1);
4278 /* XXX: this should probably not use du */
4279 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4284 _assert(close(fds[1]) != -1);
4286 if (FILE *du = fdopen(fds[0], "r")) {
4288 while (fgets(line, sizeof(line), du) != NULL) {
4289 size_t length(strlen(line));
4290 while (length != 0 && line[length - 1] == '\n')
4291 line[--length] = '\0';
4292 if (char *tab = strchr(line, '\t')) {
4294 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4299 } else _assert(close(fds[0]));
4303 if (waitpid(pid, &status, 0) == -1)
4306 else _assert(false);
4312 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4315 - (void) installPackages:(NSArray *)packages {
4316 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4319 - (NSString *) substitutePackageNames:(NSString *)message {
4320 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4321 for (size_t i(0), e([words count]); i != e; ++i) {
4322 NSString *word([words objectAtIndex:i]);
4323 if (Package *package = [[Database sharedInstance] packageWithName:word])
4324 [words replaceObjectAtIndex:i withObject:[package name]];
4327 return [words componentsJoinedByString:@" "];
4330 - (void) removeButton {
4331 [indirect_ removeButton];
4334 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4335 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4338 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4339 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4342 - (void) setBadgeValue:(id)value {
4343 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4346 - (void) setAllowsNavigationAction:(NSString *)value {
4347 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4350 - (void) setHidesBackButton:(NSString *)value {
4351 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4354 - (void) setHidesNavigationBar:(NSString *)value {
4355 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4358 - (void) setNavigationBarStyle:(NSString *)value {
4359 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4362 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4363 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4364 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4365 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4368 - (void) setPasteboardString:(NSString *)value {
4369 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4372 - (void) setPasteboardURL:(NSString *)value {
4373 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4376 - (void) _setToken:(NSString *)token {
4380 [Metadata_ removeObjectForKey:@"Token"];
4382 [Metadata_ setObject:Token_ forKey:@"Token"];
4387 - (void) setToken:(NSString *)token {
4388 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4391 - (void) scrollToBottom:(NSNumber *)animated {
4392 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4395 - (void) setViewportWidth:(float)width {
4396 [indirect_ setViewportWidthOnMainThread:width];
4399 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4400 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4401 unsigned count([arguments count]);
4403 for (unsigned i(0); i != count; ++i)
4404 values[i] = [arguments objectAtIndex:i];
4405 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4408 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4409 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4411 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4413 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4419 @interface NSURL (CydiaSecure)
4422 @implementation NSURL (CydiaSecure)
4424 - (bool) isCydiaSecure {
4425 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4428 @synchronized (HostConfig_) {
4429 if ([InsecureHosts_ containsObject:[self host]])
4438 /* Cydia Browser Controller {{{ */
4439 @implementation CydiaWebViewController
4441 - (NSURL *) navigationURL {
4442 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4445 + (void) initialize {
4446 Diversions_ = [NSMutableSet setWithCapacity:0];
4449 + (void) addDiversion:(Diversion *)diversion {
4450 [Diversions_ addObject:diversion];
4453 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4454 [super webView:view didClearWindowObject:window forFrame:frame];
4456 WebDataSource *source([frame dataSource]);
4457 NSURLResponse *response([source response]);
4458 NSURL *url([response URL]);
4459 NSString *scheme([[url scheme] lowercaseString]);
4461 bool bridged(false);
4463 @synchronized (HostConfig_) {
4464 if ([scheme isEqualToString:@"file"])
4466 else if ([scheme isEqualToString:@"https"])
4467 if ([BridgedHosts_ containsObject:[url host]])
4472 [window setValue:cydia_ forKey:@"cydia"];
4475 - (void) _setupMail:(MFMailComposeViewController *)controller {
4476 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4478 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4479 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4482 - (NSURL *) URLWithURL:(NSURL *)url {
4483 return [Diversion divertURL:url];
4486 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4487 NSURL *url([request URL]);
4488 NSString *host([url host]);
4490 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4492 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4493 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4494 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4495 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4498 @synchronized (HostConfig_) {
4499 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4502 if ([url isCydiaSecure] && token) {
4503 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4504 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4510 - (void) setDelegate:(id)delegate {
4511 [super setDelegate:delegate];
4512 [cydia_ setDelegate:delegate];
4515 - (NSString *) applicationNameForUserAgent {
4516 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4519 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4521 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4522 if (Product_ != nil)
4523 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4529 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4530 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4538 @interface NSObject (CydiaScript)
4539 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4542 @implementation NSObject (CydiaScript)
4544 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4550 @implementation NSArray (CydiaScript)
4552 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4553 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4554 for (size_t i(0), e([self count]); i != e; ++i)
4555 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4561 @implementation NSDictionary (CydiaScript)
4563 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4564 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4566 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4573 /* Confirmation Controller {{{ */
4574 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4575 if (!iterator.end())
4576 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4577 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4579 pkgCache::PkgIterator package(dep.TargetPkg());
4582 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4589 @protocol ConfirmationControllerDelegate
4590 - (void) cancelAndClear:(bool)clear;
4591 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4595 @interface ConfirmationController : CydiaWebViewController {
4596 _transient Database *database_;
4598 _H<UIAlertView> essential_;
4600 _H<NSDictionary> changes_;
4601 _H<NSMutableArray> issues_;
4602 _H<NSDictionary> sizes_;
4607 - (id) initWithDatabase:(Database *)database;
4611 @implementation ConfirmationController
4615 RestartSubstrate_ = true;
4616 [delegate_ confirmWithNavigationController:[self navigationController]];
4619 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4620 NSString *context([alert context]);
4622 if ([context isEqualToString:@"remove"]) {
4623 if (button == [alert cancelButtonIndex])
4624 [self dismissModalViewControllerAnimated:YES];
4625 else if (button == [alert firstOtherButtonIndex]) {
4629 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4630 } else if ([context isEqualToString:@"unable"]) {
4631 [self dismissModalViewControllerAnimated:YES];
4632 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4634 [super alertView:alert clickedButtonAtIndex:button];
4638 - (void) _doContinue {
4639 [self dismissModalViewControllerAnimated:YES];
4640 [delegate_ cancelAndClear:NO];
4643 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4644 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4648 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4649 [super webView:view didClearWindowObject:window forFrame:frame];
4651 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4652 (id) changes_, @"changes",
4653 (id) issues_, @"issues",
4654 (id) sizes_, @"sizes",
4656 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4659 - (id) initWithDatabase:(Database *)database {
4660 if ((self = [super init]) != nil) {
4661 database_ = database;
4663 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4664 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4665 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4666 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4667 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4671 pkgCacheFile &cache([database_ cache]);
4672 NSArray *packages([database_ packages]);
4673 pkgDepCache::Policy *policy([database_ policy]);
4675 issues_ = [NSMutableArray arrayWithCapacity:4];
4677 for (Package *package in packages) {
4678 pkgCache::PkgIterator iterator([package iterator]);
4679 NSString *name([package id]);
4681 if ([package broken]) {
4682 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4684 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4686 reasons, @"reasons",
4689 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4693 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4694 pkgCache::DepIterator start;
4695 pkgCache::DepIterator end;
4696 dep.GlobOr(start, end); // ++dep
4698 if (!cache->IsImportantDep(end))
4700 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4703 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4705 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4706 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4707 clauses, @"clauses",
4711 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4713 pkgCache::PkgIterator target(start.TargetPkg());
4714 if (target->ProvidesList != 0)
4715 reason = @"missing";
4717 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4719 reason = @"installed";
4720 installed = [NSString stringWithUTF8String:ver.VerStr()];
4721 } else if (!cache[target].CandidateVerIter(cache).end())
4722 reason = @"uninstalled";
4723 else if (target->ProvidesList == 0)
4724 reason = @"uninstallable";
4726 reason = @"virtual";
4729 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4730 [NSString stringWithUTF8String:start.CompType()], @"operator",
4731 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4734 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4735 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4736 version, @"version",
4738 installed, @"installed",
4741 // yes, seriously. (wtf?)
4749 pkgDepCache::StateCache &state(cache[iterator]);
4751 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4753 if (state.NewInstall())
4754 [installs addObject:name];
4755 // XXX: else if (state.Install())
4756 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4757 [reinstalls addObject:name];
4758 // XXX: move before previous if
4759 else if (state.Upgrade())
4760 [upgrades addObject:name];
4761 else if (state.Downgrade())
4762 [downgrades addObject:name];
4763 else if (!state.Delete())
4764 // XXX: _assert(state.Keep());
4766 else if (special_r(name))
4767 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4768 [NSNull null], @"package",
4769 [NSArray arrayWithObjects:
4770 [NSDictionary dictionaryWithObjectsAndKeys:
4771 @"Conflicts", @"relationship",
4772 [NSArray arrayWithObjects:
4773 [NSDictionary dictionaryWithObjectsAndKeys:
4775 [NSNull null], @"version",
4776 @"installed", @"reason",
4783 if ([package essential])
4785 [removes addObject:name];
4788 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4789 substrate_ |= DepSubstrate(iterator.CurrentVer());
4794 else if (Advanced_) {
4795 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4797 essential_ = [[[UIAlertView alloc]
4798 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4799 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4801 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4803 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4807 [essential_ setContext:@"remove"];
4809 essential_ = [[[UIAlertView alloc]
4810 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4811 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4813 cancelButtonTitle:UCLocalize("OKAY")
4814 otherButtonTitles:nil
4817 [essential_ setContext:@"unable"];
4820 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4821 installs, @"installs",
4822 reinstalls, @"reinstalls",
4823 upgrades, @"upgrades",
4824 downgrades, @"downgrades",
4825 removes, @"removes",
4828 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4829 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4830 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4833 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4837 - (UIBarButtonItem *) leftButton {
4838 return [[[UIBarButtonItem alloc]
4839 initWithTitle:UCLocalize("CANCEL")
4840 style:UIBarButtonItemStylePlain
4842 action:@selector(cancelButtonClicked)
4847 - (void) applyRightButton {
4848 if ([issues_ count] == 0 && ![self isLoading])
4849 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4850 initWithTitle:UCLocalize("CONFIRM")
4851 style:UIBarButtonItemStyleDone
4853 action:@selector(confirmButtonClicked)
4856 [[self navigationItem] setRightBarButtonItem:nil];
4860 - (void) cancelButtonClicked {
4861 [self dismissModalViewControllerAnimated:YES];
4862 [delegate_ cancelAndClear:YES];
4866 - (void) confirmButtonClicked {
4867 if (essential_ != nil)
4877 /* Progress Data {{{ */
4878 @interface CydiaProgressData : NSObject {
4879 _transient id delegate_;
4888 _H<NSMutableArray> events_;
4889 _H<NSString> title_;
4891 _H<NSString> status_;
4892 _H<NSString> finish_;
4897 @implementation CydiaProgressData
4899 + (NSArray *) _attributeKeys {
4900 return [NSArray arrayWithObjects:
4912 - (NSArray *) attributeKeys {
4913 return [[self class] _attributeKeys];
4916 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4917 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4921 if ((self = [super init]) != nil) {
4922 events_ = [NSMutableArray arrayWithCapacity:32];
4926 - (void) setDelegate:(id)delegate {
4927 delegate_ = delegate;
4930 - (void) setPercent:(float)value {
4934 - (NSNumber *) percent {
4935 return [NSNumber numberWithFloat:percent_];
4938 - (void) setCurrent:(float)value {
4942 - (NSNumber *) current {
4943 return [NSNumber numberWithFloat:current_];
4946 - (void) setTotal:(float)value {
4950 - (NSNumber *) total {
4951 return [NSNumber numberWithFloat:total_];
4954 - (void) setSpeed:(float)value {
4958 - (NSNumber *) speed {
4959 return [NSNumber numberWithFloat:speed_];
4962 - (NSArray *) events {
4966 - (void) removeAllEvents {
4967 [events_ removeAllObjects];
4970 - (void) addEvent:(CydiaProgressEvent *)event {
4971 [events_ addObject:event];
4974 - (void) setTitle:(NSString *)text {
4978 - (NSString *) title {
4982 - (void) setFinish:(NSString *)text {
4986 - (NSString *) finish {
4987 return (id) finish_ ?: [NSNull null];
4990 - (void) setRunning:(bool)running {
4994 - (NSNumber *) running {
4995 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5000 /* Progress Controller {{{ */
5001 @interface ProgressController : CydiaWebViewController <
5004 _transient Database *database_;
5005 _H<CydiaProgressData, 1> progress_;
5009 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5011 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5013 - (void) setTitle:(NSString *)title;
5014 - (void) setCancellable:(bool)cancellable;
5018 @implementation ProgressController
5021 [database_ setProgressDelegate:nil];
5025 - (UIBarButtonItem *) leftButton {
5026 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5027 initWithTitle:UCLocalize("CANCEL")
5028 style:UIBarButtonItemStylePlain
5030 action:@selector(cancel)
5031 ] autorelease] : nil;
5034 - (void) updateCancel {
5035 [super applyLeftButton];
5038 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5039 if ((self = [super init]) != nil) {
5040 database_ = database;
5041 delegate_ = delegate;
5043 [database_ setProgressDelegate:self];
5045 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5046 [progress_ setDelegate:self];
5048 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5050 [scroller_ setBackgroundColor:[UIColor blackColor]];
5052 [[self navigationItem] setHidesBackButton:YES];
5054 [self updateCancel];
5058 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5059 [super webView:view didClearWindowObject:window forFrame:frame];
5060 [window setValue:progress_ forKey:@"cydiaProgress"];
5063 - (void) updateProgress {
5064 [self dispatchEvent:@"CydiaProgressUpdate"];
5067 - (void) viewWillAppear:(BOOL)animated {
5068 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5069 [super viewWillAppear:animated];
5073 UpdateExternalStatus(0);
5080 [delegate_ terminateWithSuccess];
5081 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5082 [delegate_ suspendWithAnimation:YES];
5084 [delegate_ suspend];*/
5096 system("/usr/bin/sbreload");
5102 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5103 SBReboot(SBSSpringBoardServerPort());
5105 reboot2(RB_AUTOBOOT);
5112 - (void) setTitle:(NSString *)title {
5113 [progress_ setTitle:title];
5114 [self updateProgress];
5117 - (UIBarButtonItem *) rightButton {
5118 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5119 initWithTitle:UCLocalize("CLOSE")
5120 style:UIBarButtonItemStylePlain
5122 action:@selector(close)
5126 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5127 UpdateExternalStatus(1);
5129 [progress_ setRunning:true];
5130 [self setTitle:title];
5131 // implicit updateProgress
5133 SHA1SumValue notifyconf; {
5135 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5138 MMap mmap(file, MMap::ReadOnly);
5140 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5141 notifyconf = sha1.Result();
5145 SHA1SumValue springlist; {
5147 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5150 MMap mmap(file, MMap::ReadOnly);
5152 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5153 springlist = sha1.Result();
5157 if (invocation != nil) {
5158 [invocation yieldToSelector:@selector(invoke)];
5159 [self setTitle:@"COMPLETE"];
5164 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5167 MMap mmap(file, MMap::ReadOnly);
5169 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5170 if (!(notifyconf == sha1.Result()))
5177 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5180 MMap mmap(file, MMap::ReadOnly);
5182 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5183 if (!(springlist == sha1.Result()))
5189 if (RestartSubstrate_)
5193 RestartSubstrate_ = false;
5196 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5197 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5198 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5199 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5200 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5204 system("su -c /usr/bin/uicache mobile");
5207 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5209 [progress_ setRunning:false];
5210 [self updateProgress];
5212 [self applyRightButton];
5215 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5216 [progress_ addEvent:event];
5217 [self updateProgress];
5220 - (bool) isProgressCancelled {
5221 return cancel_ == 2;
5226 [self updateCancel];
5229 - (void) setCancellable:(bool)cancellable {
5230 unsigned cancel(cancel_);
5234 else if (cancel_ == 0)
5237 if (cancel != cancel_)
5238 [self updateCancel];
5241 - (void) setProgressCancellable:(NSNumber *)cancellable {
5242 [self setCancellable:[cancellable boolValue]];
5245 - (void) setProgressPercent:(NSNumber *)percent {
5246 [progress_ setPercent:[percent floatValue]];
5247 [self updateProgress];
5250 - (void) setProgressStatus:(NSDictionary *)status {
5251 if (status == nil) {
5252 [progress_ setCurrent:0];
5253 [progress_ setTotal:0];
5254 [progress_ setSpeed:0];
5256 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5258 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5259 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5260 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5263 [self updateProgress];
5269 /* Package Cell {{{ */
5270 @interface PackageCell : CyteTableViewCell <
5271 CyteTableViewCellDelegate
5275 _H<NSString> description_;
5277 _H<NSString> source_;
5279 _H<Package> package_;
5280 _H<UIImage> placard_;
5284 - (PackageCell *) init;
5285 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5287 - (void) drawContentRect:(CGRect)rect;
5291 @implementation PackageCell
5293 - (PackageCell *) init {
5294 CGRect frame(CGRectMake(0, 0, 320, 74));
5295 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5296 UIView *content([self contentView]);
5297 CGRect bounds([content bounds]);
5299 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5300 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5301 [content addSubview:content_];
5303 [content_ setDelegate:self];
5304 [content_ setOpaque:YES];
5308 - (NSString *) accessibilityLabel {
5309 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5312 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5313 summarized_ = summary;
5325 Source *source = [package source];
5327 icon_ = [package icon];
5329 if (NSString *name = [package name])
5330 name_ = [NSString stringWithString:name];
5332 NSString *description(nil);
5334 if (description == nil && IsWildcat_)
5335 description = [package longDescription];
5336 if (description == nil)
5337 description = [package shortDescription];
5339 if (description != nil)
5340 description_ = [NSString stringWithString:description];
5342 commercial_ = [package isCommercial];
5346 NSString *label = nil;
5347 bool trusted = false;
5349 if (source != nil) {
5350 label = [source label];
5351 trusted = [source trusted];
5352 } else if ([[package id] isEqualToString:@"firmware"])
5353 label = UCLocalize("APPLE");
5355 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5357 NSString *from(label);
5359 NSString *section = [package simpleSection];
5360 if (section != nil && ![section isEqualToString:label]) {
5361 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5362 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5365 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5367 if (NSString *purpose = [package primaryPurpose])
5368 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5373 if (NSString *mode = [package_ mode]) {
5374 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5375 color = RemovingColor_;
5376 //placard = @"removing";
5378 color = InstallingColor_;
5379 //placard = @"installing";
5382 // XXX: the removing/installing placards are not @2x
5385 color = [UIColor whiteColor];
5387 if ([package installed] != nil)
5388 placard = @"installed";
5393 [content_ setBackgroundColor:color];
5396 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5398 [self setNeedsDisplay];
5399 [content_ setNeedsDisplay];
5402 - (void) drawSummaryContentRect:(CGRect)rect {
5403 bool highlighted(highlighted_);
5404 float width([self bounds].size.width);
5408 rect.size = [(UIImage *) icon_ size];
5410 rect.size.width /= 4;
5411 rect.size.height /= 4;
5413 rect.origin.x = 14 - rect.size.width / 4;
5414 rect.origin.y = 14 - rect.size.height / 4;
5416 [icon_ drawInRect:rect];
5419 if (badge_ != nil) {
5421 rect.size = [(UIImage *) badge_ size];
5423 rect.size.width /= 4;
5424 rect.size.height /= 4;
5426 rect.origin.x = 20 - rect.size.width / 4;
5427 rect.origin.y = 20 - rect.size.height / 4;
5429 [badge_ drawInRect:rect];
5436 UISetColor(commercial_ ? Purple_ : Black_);
5437 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5439 if (placard_ != nil)
5440 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5443 - (void) drawNormalContentRect:(CGRect)rect {
5444 bool highlighted(highlighted_);
5445 float width([self bounds].size.width);
5449 rect.size = [(UIImage *) icon_ size];
5451 rect.size.width /= 2;
5452 rect.size.height /= 2;
5454 rect.origin.x = 25 - rect.size.width / 2;
5455 rect.origin.y = 25 - rect.size.height / 2;
5457 [icon_ drawInRect:rect];
5460 if (badge_ != nil) {
5462 rect.size = [(UIImage *) badge_ size];
5464 rect.size.width /= 2;
5465 rect.size.height /= 2;
5467 rect.origin.x = 36 - rect.size.width / 2;
5468 rect.origin.y = 36 - rect.size.height / 2;
5470 [badge_ drawInRect:rect];
5477 UISetColor(commercial_ ? Purple_ : Black_);
5478 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5479 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5482 UISetColor(commercial_ ? Purplish_ : Gray_);
5483 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5485 if (placard_ != nil)
5486 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5489 - (void) drawContentRect:(CGRect)rect {
5491 [self drawSummaryContentRect:rect];
5493 [self drawNormalContentRect:rect];
5498 /* Section Cell {{{ */
5499 @interface SectionCell : CyteTableViewCell <
5500 CyteTableViewCellDelegate
5502 _H<NSString> basic_;
5503 _H<NSString> section_;
5505 _H<NSString> count_;
5507 _H<UISwitch> switch_;
5511 - (void) setSection:(Section *)section editing:(BOOL)editing;
5515 @implementation SectionCell
5517 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5518 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5519 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5520 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5521 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5523 UIView *content([self contentView]);
5524 CGRect bounds([content bounds]);
5526 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5527 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5528 [content addSubview:content_];
5529 [content_ setBackgroundColor:[UIColor whiteColor]];
5531 [content_ setDelegate:self];
5535 - (void) onSwitch:(id)sender {
5536 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5537 if (metadata == nil) {
5538 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5539 [Sections_ setObject:metadata forKey:basic_];
5542 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5546 - (void) setSection:(Section *)section editing:(BOOL)editing {
5547 if (editing != editing_) {
5549 [switch_ removeFromSuperview];
5551 [self addSubview:switch_];
5560 if (section == nil) {
5561 name_ = UCLocalize("ALL_PACKAGES");
5564 basic_ = [section name];
5565 section_ = [section localized];
5567 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5568 count_ = [NSString stringWithFormat:@"%d", [section count]];
5571 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5574 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5575 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5577 [content_ setNeedsDisplay];
5580 - (void) setFrame:(CGRect)frame {
5581 [super setFrame:frame];
5583 CGRect rect([switch_ frame]);
5584 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5587 - (NSString *) accessibilityLabel {
5591 - (void) drawContentRect:(CGRect)rect {
5592 bool highlighted(highlighted_ && !editing_);
5594 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5599 float width(rect.size.width);
5605 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5607 CGSize size = [count_ sizeWithFont:Font14_];
5611 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5617 /* File Table {{{ */
5618 @interface FileTable : CyteViewController <
5619 UITableViewDataSource,
5622 _transient Database *database_;
5623 _H<Package> package_;
5625 _H<NSMutableArray> files_;
5626 _H<UITableView, 2> list_;
5629 - (id) initWithDatabase:(Database *)database;
5630 - (void) setPackage:(Package *)package;
5634 @implementation FileTable
5636 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5637 return files_ == nil ? 0 : [files_ count];
5640 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5644 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5645 static NSString *reuseIdentifier = @"Cell";
5647 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5649 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5650 [cell setFont:[UIFont systemFontOfSize:16]];
5652 [cell setText:[files_ objectAtIndex:indexPath.row]];
5653 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5658 - (NSURL *) navigationURL {
5659 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5663 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5665 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5666 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5667 [list_ setRowHeight:24.0f];
5668 [(UITableView *) list_ setDataSource:self];
5669 [list_ setDelegate:self];
5670 [[self view] addSubview:list_];
5673 - (void) viewDidLoad {
5674 [super viewDidLoad];
5676 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5679 - (void) releaseSubviews {
5682 [super releaseSubviews];
5685 - (id) initWithDatabase:(Database *)database {
5686 if ((self = [super init]) != nil) {
5687 database_ = database;
5689 files_ = [NSMutableArray arrayWithCapacity:32];
5693 - (void) setPackage:(Package *)package {
5697 [files_ removeAllObjects];
5699 if (package != nil) {
5701 name_ = [package id];
5703 if (NSArray *files = [package files])
5704 [files_ addObjectsFromArray:files];
5706 if ([files_ count] != 0) {
5707 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5708 [files_ removeObjectAtIndex:0];
5709 [files_ sortUsingSelector:@selector(compareByPath:)];
5711 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5712 [stack addObject:@"/"];
5714 for (int i(0), e([files_ count]); i != e; ++i) {
5715 NSString *file = [files_ objectAtIndex:i];
5716 while (![file hasPrefix:[stack lastObject]])
5717 [stack removeLastObject];
5718 NSString *directory = [stack lastObject];
5719 [stack addObject:[file stringByAppendingString:@"/"]];
5720 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5721 ([stack count] - 2) * 3, "",
5722 [file substringFromIndex:[directory length]]
5731 - (void) reloadData {
5734 [self setPackage:[database_ packageWithName:name_]];
5739 /* Package Controller {{{ */
5740 @interface CYPackageController : CydiaWebViewController <
5741 UIActionSheetDelegate
5743 _transient Database *database_;
5744 _H<Package> package_;
5747 _H<NSMutableArray> buttons_;
5748 _H<UIBarButtonItem> button_;
5751 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5755 @implementation CYPackageController
5757 - (NSURL *) navigationURL {
5758 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5761 /* XXX: this is not safe at all... localization of /fail/ */
5762 - (void) _clickButtonWithName:(NSString *)name {
5763 if ([name isEqualToString:UCLocalize("CLEAR")])
5764 [delegate_ clearPackage:package_];
5765 else if ([name isEqualToString:UCLocalize("INSTALL")])
5766 [delegate_ installPackage:package_];
5767 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5768 [delegate_ installPackage:package_];
5769 else if ([name isEqualToString:UCLocalize("REMOVE")])
5770 [delegate_ removePackage:package_];
5771 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5772 [delegate_ installPackage:package_];
5773 else _assert(false);
5776 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5777 NSString *context([sheet context]);
5779 if ([context isEqualToString:@"modify"]) {
5780 if (button != [sheet cancelButtonIndex]) {
5781 NSString *buttonName = [buttons_ objectAtIndex:button];
5782 [self _clickButtonWithName:buttonName];
5785 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5789 - (bool) _allowJavaScriptPanel {
5794 - (void) _customButtonClicked {
5795 int count([buttons_ count]);
5800 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5802 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5803 [buttons addObjectsFromArray:buttons_];
5805 UIActionSheet *sheet = [[[UIActionSheet alloc]
5808 cancelButtonTitle:nil
5809 destructiveButtonTitle:nil
5810 otherButtonTitles:nil
5813 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5815 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5816 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5818 [sheet setContext:@"modify"];
5820 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5824 // We don't want to allow non-commercial packages to do custom things to the install button,
5825 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5826 - (void) customButtonClicked {
5828 [super customButtonClicked];
5830 [self _customButtonClicked];
5833 - (void) reloadButtonClicked {
5834 // Don't reload a commerical package by tapping the loading button,
5835 // but if it's not an Install button, we should forward it on.
5836 if (![package_ uninstalled])
5837 [self _customButtonClicked];
5840 - (void) applyLoadingTitle {
5841 // Don't show "Loading" as the title. Ever.
5844 - (UIBarButtonItem *) rightButton {
5849 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5850 if ((self = [super init]) != nil) {
5851 database_ = database;
5852 buttons_ = [NSMutableArray arrayWithCapacity:4];
5853 name_ = [NSString stringWithString:name];
5854 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5858 - (void) reloadData {
5861 package_ = [database_ packageWithName:name_];
5863 [buttons_ removeAllObjects];
5865 if (package_ != nil) {
5866 [(Package *) package_ parse];
5868 commercial_ = [package_ isCommercial];
5870 if ([package_ mode] != nil)
5871 [buttons_ addObject:UCLocalize("CLEAR")];
5872 if ([package_ source] == nil);
5873 else if ([package_ upgradableAndEssential:NO])
5874 [buttons_ addObject:UCLocalize("UPGRADE")];
5875 else if ([package_ uninstalled])
5876 [buttons_ addObject:UCLocalize("INSTALL")];
5878 [buttons_ addObject:UCLocalize("REINSTALL")];
5879 if (![package_ uninstalled])
5880 [buttons_ addObject:UCLocalize("REMOVE")];
5884 switch ([buttons_ count]) {
5885 case 0: title = nil; break;
5886 case 1: title = [buttons_ objectAtIndex:0]; break;
5887 default: title = UCLocalize("MODIFY"); break;
5890 button_ = [[[UIBarButtonItem alloc]
5892 style:UIBarButtonItemStylePlain
5894 action:@selector(customButtonClicked)
5898 - (bool) isLoading {
5899 return commercial_ ? [super isLoading] : false;
5905 /* Package List Controller {{{ */
5906 @interface PackageListController : CyteViewController <
5907 UITableViewDataSource,
5910 _transient Database *database_;
5912 _H<NSArray> packages_;
5913 _H<NSMutableArray> sections_;
5914 _H<UITableView, 2> list_;
5915 _H<NSMutableArray> index_;
5916 _H<NSMutableDictionary> indices_;
5917 _H<NSString> title_;
5918 unsigned reloading_;
5921 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5922 - (void) setDelegate:(id)delegate;
5923 - (void) resetCursor;
5928 @implementation PackageListController
5930 - (bool) isSummarized {
5934 - (bool) showsSections {
5938 - (void) deselectWithAnimation:(BOOL)animated {
5939 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5942 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5943 CGRect base = [[self view] bounds];
5944 base.size.height -= bounds.size.height;
5945 base.origin = [list_ frame].origin;
5947 [UIView beginAnimations:nil context:NULL];
5948 [UIView setAnimationBeginsFromCurrentState:YES];
5949 [UIView setAnimationCurve:curve];
5950 [UIView setAnimationDuration:duration];
5951 [list_ setFrame:base];
5952 [UIView commitAnimations];
5955 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5956 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5959 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5960 [self resizeForKeyboardBounds:bounds duration:0];
5963 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5964 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5965 *curve = UIViewAnimationCurveEaseInOut;
5967 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5969 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5972 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5975 - (void) keyboardWillShow:(NSNotification *)notification {
5978 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5979 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5981 NSTimeInterval duration;
5982 UIViewAnimationCurve curve;
5983 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5985 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
5986 UIViewController *base = self;
5987 while ([base parentViewController] != nil)
5988 base = [base parentViewController];
5989 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5990 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5992 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5993 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5995 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5998 - (void) keyboardWillHide:(NSNotification *)notification {
5999 NSTimeInterval duration;
6000 UIViewAnimationCurve curve;
6001 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6003 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6006 - (void) viewWillAppear:(BOOL)animated {
6007 [super viewWillAppear:animated];
6009 [self resizeForKeyboardBounds:CGRectZero];
6010 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6011 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6014 - (void) viewWillDisappear:(BOOL)animated {
6015 [super viewWillDisappear:animated];
6017 [self resizeForKeyboardBounds:CGRectZero];
6018 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6019 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6022 - (void) viewDidAppear:(BOOL)animated {
6023 [super viewDidAppear:animated];
6024 [self deselectWithAnimation:animated];
6027 - (void) didSelectPackage:(Package *)package {
6028 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6029 [view setDelegate:delegate_];
6030 [[self navigationController] pushViewController:view animated:YES];
6033 #if TryIndexedCollation
6034 + (BOOL) hasIndexedCollation {
6035 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6039 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6040 NSInteger count([sections_ count]);
6041 return count == 0 ? 1 : count;
6044 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6045 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6047 return [[sections_ objectAtIndex:section] name];
6050 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6051 if ([sections_ count] == 0)
6053 return [[sections_ objectAtIndex:section] count];
6056 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6057 @synchronized (database_) {
6058 if ([database_ era] != era_)
6061 Section *section([sections_ objectAtIndex:[path section]]);
6062 NSInteger row([path row]);
6063 Package *package([packages_ objectAtIndex:([section row] + row)]);
6064 return [[package retain] autorelease];
6067 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6068 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6070 cell = [[[PackageCell alloc] init] autorelease];
6071 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
6075 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6076 Package *package([self packageAtIndexPath:path]);
6077 package = [database_ packageWithName:[package id]];
6078 [self didSelectPackage:package];
6081 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6082 if (![self showsSections])
6088 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6089 #if TryIndexedCollation
6090 if ([[self class] hasIndexedCollation]) {
6091 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6098 - (void) updateHeight {
6099 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6102 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6103 if ((self = [super init]) != nil) {
6104 database_ = database;
6105 title_ = [title copy];
6106 [[self navigationItem] setTitle:title_];
6108 #if TryIndexedCollation
6109 if ([[self class] hasIndexedCollation])
6110 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6113 index_ = [NSMutableArray arrayWithCapacity:32];
6115 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6117 packages_ = [NSArray array];
6118 sections_ = [NSMutableArray arrayWithCapacity:16];
6123 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6125 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6126 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6127 [[self view] addSubview:list_];
6129 // XXX: is 20 the most optimal number here?
6130 [list_ setSectionIndexMinimumDisplayRowCount:20];
6132 [(UITableView *) list_ setDataSource:self];
6133 [list_ setDelegate:self];
6135 [self updateHeight];
6138 - (void) releaseSubviews {
6141 [super releaseSubviews];
6144 - (void) setDelegate:(id)delegate {
6145 delegate_ = delegate;
6148 - (bool) shouldYield {
6152 - (bool) shouldBlock {
6156 - (NSMutableArray *) _reloadPackages {
6157 @synchronized (database_) {
6158 era_ = [database_ era];
6159 NSArray *packages([database_ packages]);
6161 return [NSMutableArray arrayWithArray:packages];
6164 - (void) _reloadData {
6165 if (reloading_ != 0) {
6172 if ([self shouldYield]) {
6176 if (![self shouldBlock])
6179 hud = [delegate_ addProgressHUD];
6180 [hud setText:UCLocalize("LOADING")];
6184 packages = [self yieldToSelector:@selector(_reloadPackages)];
6187 [delegate_ removeProgressHUD:hud];
6188 } while (reloading_ == 2);
6192 packages = [self _reloadPackages];
6195 packages_ = packages;
6197 [indices_ removeAllObjects];
6198 [sections_ removeAllObjects];
6200 Section *section = nil;
6202 #if TryIndexedCollation
6203 if ([[self class] hasIndexedCollation]) {
6204 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6205 NSArray *titles = [collation sectionIndexTitles];
6208 _profile(PackageTable$reloadData$Section)
6209 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6213 _profile(PackageTable$reloadData$Section$Package)
6214 package = [packages_ objectAtIndex:offset];
6215 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6218 while (secidx < index) {
6221 _profile(PackageTable$reloadData$Section$Allocate)
6222 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6225 _profile(PackageTable$reloadData$Section$Add)
6226 [sections_ addObject:section];
6230 [section addToCount];
6236 [index_ removeAllObjects];
6238 bool sectioned([self showsSections]);
6240 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6241 [sections_ addObject:section];
6244 _profile(PackageTable$reloadData$Section)
6245 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6249 _profile(PackageTable$reloadData$Section$Package)
6250 package = [packages_ objectAtIndex:offset];
6251 index = [package index];
6254 if (sectioned && (section == nil || [section index] != index)) {
6255 _profile(PackageTable$reloadData$Section$Allocate)
6256 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6259 [index_ addObject:[section name]];
6260 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6262 _profile(PackageTable$reloadData$Section$Add)
6263 [sections_ addObject:section];
6267 [section addToCount];
6272 [self updateHeight];
6274 _profile(PackageTable$reloadData$List)
6275 [(UITableView *) list_ setDataSource:self];
6280 - (void) reloadData {
6282 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6285 - (void) resetCursor {
6286 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6289 - (void) clearData {
6290 [self updateHeight];
6292 [list_ setDataSource:nil];
6300 /* Filtered Package List Controller {{{ */
6301 @interface FilteredPackageListController : PackageListController {
6304 _H<NSObject> object_;
6307 - (void) setObject:(id)object;
6308 - (void) setObject:(id)object forFilter:(SEL)filter;
6311 - (void) setFilter:(SEL)filter;
6313 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6317 @implementation FilteredPackageListController
6323 - (void) setFilter:(SEL)filter {
6324 @synchronized (self) {
6327 /* XXX: this is an unsafe optimization of doomy hell */
6328 Method method(class_getInstanceMethod([Package class], filter));
6329 _assert(method != NULL);
6330 imp_ = method_getImplementation(method);
6331 _assert(imp_ != NULL);
6334 - (void) setObject:(id)object {
6335 @synchronized (self) {
6339 - (void) setObject:(id)object forFilter:(SEL)filter {
6340 @synchronized (self) {
6341 [self setFilter:filter];
6342 [self setObject:object];
6345 - (NSMutableArray *) _reloadPackages {
6346 @synchronized (database_) {
6347 era_ = [database_ era];
6348 NSArray *packages([database_ packages]);
6350 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6354 _H<NSObject> object;
6356 @synchronized (self) {
6362 _profile(PackageTable$reloadData$Filter)
6363 for (Package *package in packages)
6364 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6365 [filtered addObject:package];
6371 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6372 if ((self = [super initWithDatabase:database title:title]) != nil) {
6373 [self setFilter:filter];
6374 [self setObject:object];
6381 /* Home Controller {{{ */
6382 @interface HomeController : CydiaWebViewController {
6387 @implementation HomeController
6390 if ((self = [super init]) != nil) {
6391 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6396 - (NSURL *) navigationURL {
6397 return [NSURL URLWithString:@"cydia://home"];
6400 - (void) aboutButtonClicked {
6401 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6403 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6404 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6405 [alert setCancelButtonIndex:0];
6408 @"Copyright \u00a9 2008-2011\n"
6411 "Jay Freeman (saurik)\n"
6412 "saurik@saurik.com\n"
6413 "http://www.saurik.com/"
6419 - (UIBarButtonItem *) leftButton {
6420 return [[[UIBarButtonItem alloc]
6421 initWithTitle:UCLocalize("ABOUT")
6422 style:UIBarButtonItemStylePlain
6424 action:@selector(aboutButtonClicked)
6430 /* Manage Controller {{{ */
6431 @interface ManageController : CydiaWebViewController {
6434 - (void) queueStatusDidChange;
6438 @implementation ManageController
6441 if ((self = [super init]) != nil) {
6442 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6446 - (NSURL *) navigationURL {
6447 return [NSURL URLWithString:@"cydia://manage"];
6450 - (UIBarButtonItem *) leftButton {
6451 return [[[UIBarButtonItem alloc]
6452 initWithTitle:UCLocalize("SETTINGS")
6453 style:UIBarButtonItemStylePlain
6455 action:@selector(settingsButtonClicked)
6459 - (void) settingsButtonClicked {
6460 [delegate_ showSettings];
6463 - (void) queueButtonClicked {
6467 - (UIBarButtonItem *) customButton {
6468 return Queuing_ ? [[[UIBarButtonItem alloc]
6469 initWithTitle:UCLocalize("QUEUE")
6470 style:UIBarButtonItemStyleDone
6472 action:@selector(queueButtonClicked)
6473 ] autorelease] : [super customButton];
6476 - (void) queueStatusDidChange {
6477 [self applyRightButton];
6480 - (bool) isLoading {
6481 return !Queuing_ && [super isLoading];
6487 /* Refresh Bar {{{ */
6488 @interface RefreshBar : UINavigationBar {
6489 _H<UIProgressIndicator> indicator_;
6490 _H<UITextLabel> prompt_;
6491 _H<UIProgressBar> progress_;
6492 _H<UINavigationButton> cancel_;
6497 @implementation RefreshBar
6499 - (void) positionViews {
6500 CGRect frame = [cancel_ frame];
6501 frame.size = [cancel_ sizeThatFits:frame.size];
6502 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6503 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6504 [cancel_ setFrame:frame];
6506 CGSize prgsize = {75, 100};
6508 [self frame].size.width - prgsize.width - 10,
6509 ([self frame].size.height - prgsize.height) / 2
6511 [progress_ setFrame:prgrect];
6513 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6514 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6515 CGRect indrect = {{indoffset, indoffset}, indsize};
6516 [indicator_ setFrame:indrect];
6518 CGSize prmsize = {215, indsize.height + 4};
6520 indoffset * 2 + indsize.width,
6521 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6523 [prompt_ setFrame:prmrect];
6526 - (void) setFrame:(CGRect)frame {
6527 [super setFrame:frame];
6528 [self positionViews];
6531 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6532 if ((self = [super initWithFrame:frame]) != nil) {
6533 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6535 [self setBarStyle:UIBarStyleBlack];
6537 UIBarStyle barstyle([self _barStyle:NO]);
6538 bool ugly(barstyle == UIBarStyleDefault);
6540 UIProgressIndicatorStyle style = ugly ?
6541 UIProgressIndicatorStyleMediumBrown :
6542 UIProgressIndicatorStyleMediumWhite;
6544 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6545 [(UIProgressIndicator *) indicator_ setStyle:style];
6546 [indicator_ startAnimation];
6547 [self addSubview:indicator_];
6549 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6550 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6551 [prompt_ setBackgroundColor:[UIColor clearColor]];
6552 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6553 [self addSubview:prompt_];
6555 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6556 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6557 [(UIProgressBar *) progress_ setStyle:0];
6558 [self addSubview:progress_];
6560 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6561 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6562 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6563 [cancel_ setBarStyle:barstyle];
6565 [self positionViews];
6569 - (void) setCancellable:(bool)cancellable {
6571 [self addSubview:cancel_];
6573 [cancel_ removeFromSuperview];
6577 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6578 [progress_ setProgress:0];
6582 [self setCancellable:NO];
6585 - (void) setPrompt:(NSString *)prompt {
6586 [prompt_ setText:prompt];
6589 - (void) setProgress:(float)progress {
6590 [progress_ setProgress:progress];
6596 /* Cydia Navigation Controller Interface {{{ */
6597 @interface UINavigationController (Cydia)
6599 - (NSArray *) navigationURLCollection;
6600 - (void) unloadData;
6605 /* Cydia Tab Bar Controller {{{ */
6606 @interface CYTabBarController : UITabBarController <
6607 UITabBarControllerDelegate,
6610 _transient Database *database_;
6611 _H<RefreshBar, 1> refreshbar_;
6615 // XXX: ok, "updatedelegate_"?...
6616 _transient NSObject<CydiaDelegate> *updatedelegate_;
6618 _H<UIViewController> remembered_;
6619 _transient UIViewController *transient_;
6622 - (NSArray *) navigationURLCollection;
6623 - (void) dropBar:(BOOL)animated;
6624 - (void) beginUpdate;
6625 - (void) raiseBar:(BOOL)animated;
6627 - (void) unloadData;
6631 @implementation CYTabBarController
6633 - (void) setUnselectedViewController:(UIViewController *)transient {
6634 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6635 if (transient != nil) {
6636 if (transient_ == nil)
6637 remembered_ = [controllers objectAtIndex:0];
6638 transient_ = transient;
6639 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6640 [controllers replaceObjectAtIndex:0 withObject:transient_];
6641 [self setSelectedIndex:0];
6642 [self setViewControllers:controllers];
6643 [self concealTabBarSelection];
6644 } else if (remembered_ != nil) {
6645 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6646 transient_ = transient;
6647 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6649 [self setViewControllers:controllers];
6650 [self revealTabBarSelection];
6654 - (UIViewController *) unselectedViewController {
6658 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6659 if ([self unselectedViewController])
6660 [self setUnselectedViewController:nil];
6663 - (NSArray *) navigationURLCollection {
6664 NSMutableArray *items([NSMutableArray array]);
6666 // XXX: Should this deal with transient view controllers?
6667 for (id navigation in [self viewControllers]) {
6668 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6670 [items addObject:stack];
6676 - (void) unloadData {
6679 for (UINavigationController *controller in [self viewControllers])
6680 [controller unloadData];
6682 if (UIViewController *selected = [self selectedViewController])
6683 [selected reloadData];
6685 if (UIViewController *unselected = [self unselectedViewController]) {
6686 [unselected unloadData];
6687 [unselected reloadData];
6692 [[NSNotificationCenter defaultCenter] removeObserver:self];
6697 - (id) initWithDatabase:(Database *)database {
6698 if ((self = [super init]) != nil) {
6699 database_ = database;
6700 [self setDelegate:self];
6702 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6703 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6705 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6709 - (void) setUpdate:(NSDate *)date {
6713 - (void) beginUpdate {
6714 [(RefreshBar *) refreshbar_ start];
6717 [updatedelegate_ retainNetworkActivityIndicator];
6721 detachNewThreadSelector:@selector(performUpdate)
6727 - (void) performUpdate {
6728 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6731 status.setDelegate(self);
6732 [database_ updateWithStatus:status];
6735 performSelectorOnMainThread:@selector(completeUpdate)
6743 - (void) stopUpdateWithSelector:(SEL)selector {
6745 [updatedelegate_ releaseNetworkActivityIndicator];
6747 [self raiseBar:YES];
6750 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6753 - (void) completeUpdate {
6756 [self stopUpdateWithSelector:@selector(reloadData)];
6759 - (void) cancelUpdate {
6760 [self stopUpdateWithSelector:@selector(updateData)];
6763 - (void) cancelPressed {
6764 [self cancelUpdate];
6771 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6772 [refreshbar_ setPrompt:[event compoundMessage]];
6775 - (bool) isProgressCancelled {
6779 - (void) setProgressCancellable:(NSNumber *)cancellable {
6780 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6783 - (void) setProgressPercent:(NSNumber *)percent {
6784 [refreshbar_ setProgress:[percent floatValue]];
6787 - (void) setProgressStatus:(NSDictionary *)status {
6789 [self setProgressPercent:[status objectForKey:@"Percent"]];
6792 - (void) setUpdateDelegate:(id)delegate {
6793 updatedelegate_ = delegate;
6796 - (UIView *) transitionView {
6797 if ([self respondsToSelector:@selector(_transitionView)])
6798 return [self _transitionView];
6800 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6803 - (void) dropBar:(BOOL)animated {
6808 UIView *transition([self transitionView]);
6809 [[self view] addSubview:refreshbar_];
6811 CGRect barframe([refreshbar_ frame]);
6813 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6814 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6816 barframe.origin.y = 0;
6818 [refreshbar_ setFrame:barframe];
6821 [UIView beginAnimations:nil context:NULL];
6823 CGRect viewframe = [transition frame];
6824 viewframe.origin.y += barframe.size.height;
6825 viewframe.size.height -= barframe.size.height;
6826 [transition setFrame:viewframe];
6829 [UIView commitAnimations];
6831 // Ensure bar has the proper width for our view, it might have changed
6832 barframe.size.width = viewframe.size.width;
6833 [refreshbar_ setFrame:barframe];
6836 - (void) raiseBar:(BOOL)animated {
6841 UIView *transition([self transitionView]);
6842 [refreshbar_ removeFromSuperview];
6844 CGRect barframe([refreshbar_ frame]);
6847 [UIView beginAnimations:nil context:NULL];
6849 CGRect viewframe = [transition frame];
6850 viewframe.origin.y -= barframe.size.height;
6851 viewframe.size.height += barframe.size.height;
6852 [transition setFrame:viewframe];
6855 [UIView commitAnimations];
6858 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6859 bool dropped(dropped_);
6864 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6870 - (void) statusBarFrameChanged:(NSNotification *)notification {
6880 /* Cydia Navigation Controller Implementation {{{ */
6881 @implementation UINavigationController (Cydia)
6883 - (NSArray *) navigationURLCollection {
6884 NSMutableArray *stack([NSMutableArray array]);
6886 for (CyteViewController *controller in [self viewControllers]) {
6887 NSString *url = [[controller navigationURL] absoluteString];
6889 [stack addObject:url];
6895 - (void) reloadData {
6898 if (UIViewController *visible = [self visibleViewController])
6899 [visible reloadData];
6902 - (void) unloadData {
6903 for (CyteViewController *page in [self viewControllers])
6912 /* Cydia:// Protocol {{{ */
6913 @interface CydiaURLProtocol : NSURLProtocol {
6918 @implementation CydiaURLProtocol
6920 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6921 NSURL *url([request URL]);
6925 NSString *scheme([[url scheme] lowercaseString]);
6926 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6928 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6934 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6938 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6939 id<NSURLProtocolClient> client([self client]);
6941 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6943 NSData *data(UIImagePNGRepresentation(icon));
6945 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6946 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6947 [client URLProtocol:self didLoadData:data];
6948 [client URLProtocolDidFinishLoading:self];
6952 - (void) startLoading {
6953 id<NSURLProtocolClient> client([self client]);
6954 NSURLRequest *request([self request]);
6956 NSURL *url([request URL]);
6957 NSString *href([url absoluteString]);
6958 NSString *scheme([[url scheme] lowercaseString]);
6962 if ([scheme isEqualToString:@"cydia"])
6963 path = [href substringFromIndex:8];
6964 else if ([scheme isEqualToString:@"about"])
6965 path = [href substringFromIndex:12];
6966 else _assert(false);
6968 NSRange slash([path rangeOfString:@"/"]);
6971 if (slash.location == NSNotFound) {
6975 command = [path substringToIndex:slash.location];
6976 path = [path substringFromIndex:(slash.location + 1)];
6979 Database *database([Database sharedInstance]);
6981 if ([command isEqualToString:@"package-icon"]) {
6984 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6985 Package *package([database packageWithName:path]);
6989 UIImage *icon([package icon]);
6990 [self _returnPNGWithImage:icon forRequest:request];
6991 } else if ([command isEqualToString:@"source-icon"]) {
6994 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6995 NSString *source(Simplify(path));
6996 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6998 icon = [UIImage applicationImageNamed:@"unknown.png"];
6999 [self _returnPNGWithImage:icon forRequest:request];
7000 } else if ([command isEqualToString:@"uikit-image"]) {
7003 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7004 UIImage *icon(_UIImageWithName(path));
7005 [self _returnPNGWithImage:icon forRequest:request];
7006 } else if ([command isEqualToString:@"section-icon"]) {
7009 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7010 NSString *section(Simplify(path));
7011 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7013 icon = [UIImage applicationImageNamed:@"unknown.png"];
7014 [self _returnPNGWithImage:icon forRequest:request];
7016 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7020 - (void) stopLoading {
7026 /* Section Controller {{{ */
7027 @interface SectionController : FilteredPackageListController {
7028 _H<NSString> section_;
7031 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7035 @implementation SectionController
7037 - (NSURL *) navigationURL {
7038 NSString *name = section_;
7042 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7045 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7048 title = UCLocalize("ALL_PACKAGES");
7049 else if (![name isEqual:@""])
7050 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7052 title = UCLocalize("NO_SECTION");
7054 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7061 /* Sections Controller {{{ */
7062 @interface SectionsController : CyteViewController <
7063 UITableViewDataSource,
7066 _transient Database *database_;
7067 _H<NSMutableArray> sections_;
7068 _H<NSMutableArray> filtered_;
7069 _H<UITableView, 2> list_;
7072 - (id) initWithDatabase:(Database *)database;
7073 - (void) editButtonClicked;
7077 @implementation SectionsController
7079 - (NSURL *) navigationURL {
7080 return [NSURL URLWithString:@"cydia://sections"];
7083 - (void) updateNavigationItem {
7084 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7085 if ([sections_ count] == 0) {
7086 [[self navigationItem] setRightBarButtonItem:nil];
7088 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7089 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7091 action:@selector(editButtonClicked)
7092 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7096 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7097 [super setEditing:editing animated:animated];
7102 [delegate_ updateData];
7104 [self updateNavigationItem];
7107 - (void) viewDidAppear:(BOOL)animated {
7108 [super viewDidAppear:animated];
7109 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7112 - (void) viewWillDisappear:(BOOL)animated {
7113 [super viewWillDisappear:animated];
7114 if ([self isEditing]) [self setEditing:NO];
7117 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7118 Section *section = nil;
7119 int index = [indexPath row];
7120 if (![self isEditing]) {
7123 section = [filtered_ objectAtIndex:index];
7125 section = [sections_ objectAtIndex:index];
7130 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7131 if ([self isEditing])
7132 return [sections_ count];
7134 return [filtered_ count] + 1;
7137 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7141 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7142 static NSString *reuseIdentifier = @"SectionCell";
7144 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7146 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7148 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7153 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7154 if ([self isEditing])
7157 Section *section = [self sectionAtIndexPath:indexPath];
7159 SectionController *controller = [[[SectionController alloc]
7160 initWithDatabase:database_
7161 section:[section name]
7163 [controller setDelegate:delegate_];
7165 [[self navigationController] pushViewController:controller animated:YES];
7169 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7171 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7172 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7173 [list_ setRowHeight:45.0f];
7174 [(UITableView *) list_ setDataSource:self];
7175 [list_ setDelegate:self];
7176 [[self view] addSubview:list_];
7179 - (void) viewDidLoad {
7180 [super viewDidLoad];
7182 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7185 - (void) releaseSubviews {
7188 [super releaseSubviews];
7191 - (id) initWithDatabase:(Database *)database {
7192 if ((self = [super init]) != nil) {
7193 database_ = database;
7195 sections_ = [NSMutableArray arrayWithCapacity:16];
7196 filtered_ = [NSMutableArray arrayWithCapacity:16];
7200 - (void) reloadData {
7203 NSArray *packages = [database_ packages];
7205 [sections_ removeAllObjects];
7206 [filtered_ removeAllObjects];
7208 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7211 for (Package *package in packages) {
7212 NSString *name([package section]);
7213 NSString *key(name == nil ? @"" : name);
7217 _profile(SectionsView$reloadData$Section)
7218 section = [sections objectForKey:key];
7219 if (section == nil) {
7220 _profile(SectionsView$reloadData$Section$Allocate)
7221 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7222 [sections setObject:section forKey:key];
7227 [section addToCount];
7229 _profile(SectionsView$reloadData$Filter)
7230 if (![package valid] || ![package visible])
7238 [sections_ addObjectsFromArray:[sections allValues]];
7240 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7242 for (Section *section in (id) sections_) {
7243 size_t count([section row]);
7247 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7248 [section setCount:count];
7249 [filtered_ addObject:section];
7252 [self updateNavigationItem];
7257 - (void) editButtonClicked {
7258 [self setEditing:![self isEditing] animated:YES];
7264 /* Changes Controller {{{ */
7265 @interface ChangesController : CyteViewController <
7266 UITableViewDataSource,
7269 _transient Database *database_;
7271 _H<NSArray> packages_;
7272 _H<NSMutableArray> sections_;
7273 _H<UITableView, 2> list_;
7277 - (id) initWithDatabase:(Database *)database;
7281 @implementation ChangesController
7283 - (NSURL *) navigationURL {
7284 return [NSURL URLWithString:@"cydia://changes"];
7287 - (void) viewDidAppear:(BOOL)animated {
7288 [super viewDidAppear:animated];
7289 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7292 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7293 NSInteger count([sections_ count]);
7294 return count == 0 ? 1 : count;
7297 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7298 if ([sections_ count] == 0)
7300 return [[sections_ objectAtIndex:section] name];
7303 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7304 if ([sections_ count] == 0)
7306 return [[sections_ objectAtIndex:section] count];
7309 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7310 @synchronized (database_) {
7311 if ([database_ era] != era_)
7314 NSUInteger sectionIndex([path section]);
7315 if (sectionIndex >= [sections_ count])
7317 Section *section([sections_ objectAtIndex:sectionIndex]);
7318 NSInteger row([path row]);
7319 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7322 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7323 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7325 cell = [[[PackageCell alloc] init] autorelease];
7326 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7330 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7331 Package *package([self packageAtIndexPath:path]);
7332 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7333 [view setDelegate:delegate_];
7334 [[self navigationController] pushViewController:view animated:YES];
7338 - (void) refreshButtonClicked {
7339 [delegate_ beginUpdate];
7340 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7343 - (void) upgradeButtonClicked {
7344 [delegate_ distUpgrade];
7345 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7349 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7351 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7352 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7353 [list_ setRowHeight:73];
7354 [(UITableView *) list_ setDataSource:self];
7355 [list_ setDelegate:self];
7356 [[self view] addSubview:list_];
7359 - (void) viewDidLoad {
7360 [super viewDidLoad];
7362 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7365 - (void) releaseSubviews {
7368 [super releaseSubviews];
7371 - (id) initWithDatabase:(Database *)database {
7372 if ((self = [super init]) != nil) {
7373 database_ = database;
7375 packages_ = [NSArray array];
7376 sections_ = [NSMutableArray arrayWithCapacity:16];
7380 - (NSMutableArray *) _reloadPackages {
7381 @synchronized (database_) {
7382 era_ = [database_ era];
7383 NSArray *packages([database_ packages]);
7385 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7388 _profile(ChangesController$_reloadPackages$Filter)
7389 for (Package *package in packages)
7390 if ([package upgradableAndEssential:YES] || [package visible])
7391 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7394 _profile(ChangesController$_reloadPackages$radixSort)
7395 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7402 - (void) _reloadData {
7407 UIProgressHUD *hud([delegate_ addProgressHUD]);
7408 [hud setText:UCLocalize("LOADING")];
7409 //NSLog(@"HUD:%@::%@", delegate_, hud);
7410 packages = [self yieldToSelector:@selector(_reloadPackages)];
7411 [delegate_ removeProgressHUD:hud];
7413 packages = [self _reloadPackages];
7416 @synchronized (database_) {
7417 if (era_ != [database_ era])
7420 packages_ = packages;
7421 [sections_ removeAllObjects];
7423 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7424 Section *ignored = nil;
7425 Section *section = nil;
7429 bool unseens = false;
7431 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7433 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7434 Package *package = [packages_ objectAtIndex:offset];
7436 BOOL uae = [package upgradableAndEssential:YES];
7440 time_t seen([package seen]);
7442 if (section == nil || last != seen) {
7446 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7449 _profile(ChangesController$reloadData$Allocate)
7450 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7451 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7452 [sections_ addObject:section];
7456 [section addToCount];
7457 } else if ([package ignored]) {
7458 if (ignored == nil) {
7459 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7461 [ignored addToCount];
7464 [upgradable addToCount];
7469 CFRelease(formatter);
7472 Section *last = [sections_ lastObject];
7473 size_t count = [last count];
7474 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7475 [sections_ removeLastObject];
7478 if ([ignored count] != 0)
7479 [sections_ insertObject:ignored atIndex:0];
7481 [sections_ insertObject:upgradable atIndex:0];
7485 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7486 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7487 style:UIBarButtonItemStylePlain
7489 action:@selector(upgradeButtonClicked)
7490 ] autorelease]) animated:YES];
7492 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7493 initWithTitle:UCLocalize("REFRESH")
7494 style:UIBarButtonItemStylePlain
7496 action:@selector(refreshButtonClicked)
7497 ] autorelease]) animated:YES];
7502 - (void) reloadData {
7504 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7509 /* Search Controller {{{ */
7510 @interface SearchController : FilteredPackageListController <
7513 _H<UISearchBar, 1> search_;
7517 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7518 - (void) reloadData;
7522 @implementation SearchController
7524 - (NSURL *) navigationURL {
7525 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7526 return [NSURL URLWithString:@"cydia://search"];
7528 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7531 - (void) useSearch {
7532 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7537 - (void) viewWillAppear:(BOOL)animated {
7538 [super viewWillAppear:animated];
7540 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7544 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7545 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7550 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7551 [search_ resignFirstResponder];
7555 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7556 [search_ setText:@""];
7557 [self searchBarButtonClicked:searchBar];
7560 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7561 [self searchBarButtonClicked:searchBar];
7564 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7565 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7569 - (bool) shouldYield {
7573 - (bool) shouldBlock {
7574 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7577 - (bool) isSummarized {
7578 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7581 - (bool) showsSections {
7585 - (NSMutableArray *) _reloadPackages {
7586 NSMutableArray *packages([super _reloadPackages]);
7587 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7588 [packages radixSortUsingSelector:@selector(rank)];
7592 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7593 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7594 search_ = [[[UISearchBar alloc] init] autorelease];
7595 [search_ setDelegate:self];
7598 [search_ setText:query];
7602 - (void) viewDidAppear:(BOOL)animated {
7603 [super viewDidAppear:animated];
7605 if (!searchloaded_) {
7606 searchloaded_ = YES;
7607 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7608 [search_ layoutSubviews];
7609 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7611 UITextField *textField;
7612 if ([search_ respondsToSelector:@selector(searchField)])
7613 textField = [search_ searchField];
7615 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7617 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7618 [textField setEnablesReturnKeyAutomatically:NO];
7619 [[self navigationItem] setTitleView:textField];
7623 - (void) reloadData {
7624 id object([search_ text]);
7625 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7626 object = [object componentsSeparatedByString:@" "];
7628 [self setObject:object];
7634 - (void) didSelectPackage:(Package *)package {
7635 [search_ resignFirstResponder];
7636 [super didSelectPackage:package];
7641 /* Package Settings Controller {{{ */
7642 @interface PackageSettingsController : CyteViewController <
7643 UITableViewDataSource,
7646 _transient Database *database_;
7648 _H<Package> package_;
7649 _H<UITableView, 2> table_;
7650 _H<UISwitch> subscribedSwitch_;
7651 _H<UISwitch> ignoredSwitch_;
7652 _H<UITableViewCell> subscribedCell_;
7653 _H<UITableViewCell> ignoredCell_;
7656 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7660 @implementation PackageSettingsController
7662 - (NSURL *) navigationURL {
7663 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7666 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7667 if (package_ == nil)
7670 if ([package_ installed] == nil)
7676 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7677 if (package_ == nil)
7680 // both sections contain just one item right now.
7684 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7688 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7690 return UCLocalize("SHOW_ALL_CHANGES_EX");
7692 return UCLocalize("IGNORE_UPGRADES_EX");
7695 - (void) onSubscribed:(id)control {
7696 bool value([control isOn]);
7697 if (package_ == nil)
7699 if ([package_ setSubscribed:value])
7700 [delegate_ updateData];
7703 - (void) _updateIgnored {
7704 const char *package([name_ UTF8String]);
7705 bool on([ignoredSwitch_ isOn]);
7707 pid_t pid(ExecFork());
7709 FILE *dpkg(popen("dpkg --set-selections", "w"));
7710 fwrite(package, strlen(package), 1, dpkg);
7713 fwrite(" hold\n", 6, 1, dpkg);
7715 fwrite(" install\n", 9, 1, dpkg);
7725 int result(waitpid(pid, &status, 0));
7728 _assert(result == pid);
7734 - (void) onIgnored:(id)control {
7735 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7736 [invocation setTarget:self];
7737 [invocation setSelector:@selector(_updateIgnored)];
7739 [delegate_ reloadDataWithInvocation:invocation];
7742 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7743 if (package_ == nil)
7746 switch ([indexPath section]) {
7747 case 0: return subscribedCell_;
7748 case 1: return ignoredCell_;
7757 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7759 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7760 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7761 [(UITableView *) table_ setDataSource:self];
7762 [table_ setDelegate:self];
7763 [[self view] addSubview:table_];
7765 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7766 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7767 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7769 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7770 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7771 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7773 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7774 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7775 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7776 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7778 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7779 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7780 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7781 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7784 - (void) viewDidLoad {
7785 [super viewDidLoad];
7787 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7790 - (void) releaseSubviews {
7792 subscribedCell_ = nil;
7794 ignoredSwitch_ = nil;
7795 subscribedSwitch_ = nil;
7797 [super releaseSubviews];
7800 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7801 if ((self = [super init]) != nil) {
7802 database_ = database;
7807 - (void) reloadData {
7810 package_ = [database_ packageWithName:name_];
7812 if (package_ != nil) {
7813 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7814 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7815 } // XXX: what now, G?
7817 [table_ reloadData];
7823 /* Installed Controller {{{ */
7824 @interface InstalledController : FilteredPackageListController {
7828 - (id) initWithDatabase:(Database *)database;
7830 - (void) updateRoleButton;
7831 - (void) queueStatusDidChange;
7835 @implementation InstalledController
7837 - (NSURL *) navigationURL {
7838 return [NSURL URLWithString:@"cydia://installed"];
7841 - (id) initWithDatabase:(Database *)database {
7842 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7843 [self updateRoleButton];
7844 [self queueStatusDidChange];
7849 - (void) queueButtonClicked {
7854 - (void) queueStatusDidChange {
7858 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7859 initWithTitle:UCLocalize("QUEUE")
7860 style:UIBarButtonItemStyleDone
7862 action:@selector(queueButtonClicked)
7865 [[self navigationItem] setLeftBarButtonItem:nil];
7871 - (void) updateRoleButton {
7872 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7873 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7874 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7875 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7877 action:@selector(roleButtonClicked)
7881 - (void) roleButtonClicked {
7882 [self setObject:[NSNumber numberWithBool:expert_]];
7886 [self updateRoleButton];
7892 /* Source Cell {{{ */
7893 @interface SourceCell : CyteTableViewCell <
7894 CyteTableViewCellDelegate
7897 _H<NSString> origin_;
7898 _H<NSString> label_;
7901 - (void) setSource:(Source *)source;
7905 @implementation SourceCell
7907 - (void) _setImage:(UIImage *)image {
7909 [content_ setNeedsDisplay];
7912 - (void) _setSource:(Source *)source {
7913 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7915 if (NSString *base = [source base])
7916 if ([base length] != 0) {
7917 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7919 if (NSData *data = [NSURLConnection
7920 sendSynchronousRequest:[NSURLRequest
7922 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7926 returningResponse:NULL
7929 if (UIImage *image = [UIImage imageWithData:data])
7930 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7936 - (void) setSource:(Source *)source {
7937 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7939 origin_ = [source name];
7940 label_ = [source uri];
7942 [content_ setNeedsDisplay];
7944 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7947 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7948 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7949 UIView *content([self contentView]);
7950 CGRect bounds([content bounds]);
7952 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7953 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7954 [content_ setBackgroundColor:[UIColor whiteColor]];
7955 [content addSubview:content_];
7957 [content_ setDelegate:self];
7958 [content_ setOpaque:YES];
7962 - (NSString *) accessibilityLabel {
7966 - (void) drawContentRect:(CGRect)rect {
7967 bool highlighted(highlighted_);
7968 float width(rect.size.width);
7971 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7978 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7982 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7987 /* Source Controller {{{ */
7988 @interface SourceController : FilteredPackageListController {
7989 _transient Source *source_;
7993 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7997 @implementation SourceController
7999 - (NSURL *) navigationURL {
8000 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8003 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8004 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8006 key_ = [source key];
8010 - (void) reloadData {
8011 source_ = [database_ sourceWithKey:key_];
8012 key_ = [source_ key];
8013 [self setObject:source_];
8015 [[self navigationItem] setTitle:[source_ label]];
8022 /* Sources Controller {{{ */
8023 @interface SourcesController : CyteViewController <
8024 UITableViewDataSource,
8027 _transient Database *database_;
8028 _H<UITableView, 2> list_;
8029 _H<NSMutableArray> sources_;
8033 _H<UIProgressHUD> hud_;
8036 //NSURLConnection *installer_;
8037 NSURLConnection *trivial_;
8038 NSURLConnection *trivial_bz2_;
8039 NSURLConnection *trivial_gz_;
8040 //NSURLConnection *automatic_;
8045 - (id) initWithDatabase:(Database *)database;
8046 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8050 @implementation SourcesController
8052 - (void) _releaseConnection:(NSURLConnection *)connection {
8053 if (connection != nil) {
8054 [connection cancel];
8055 //[connection setDelegate:nil];
8056 [connection release];
8061 //[self _releaseConnection:installer_];
8062 [self _releaseConnection:trivial_];
8063 [self _releaseConnection:trivial_gz_];
8064 [self _releaseConnection:trivial_bz2_];
8065 //[self _releaseConnection:automatic_];
8070 - (NSURL *) navigationURL {
8071 return [NSURL URLWithString:@"cydia://sources"];
8074 - (void) viewDidAppear:(BOOL)animated {
8075 [super viewDidAppear:animated];
8076 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8079 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8080 return offset_ == 0 ? 1 : 2;
8083 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8084 switch (section + (offset_ == 0 ? 1 : 0)) {
8085 case 0: return UCLocalize("ENTERED_BY_USER");
8086 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8092 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8093 int count = [sources_ count];
8095 case 0: return (offset_ == 0 ? count : offset_);
8096 case 1: return count - offset_;
8102 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8104 switch (indexPath.section) {
8105 case 0: idx = indexPath.row; break;
8106 case 1: idx = indexPath.row + offset_; break;
8110 return [sources_ objectAtIndex:idx];
8113 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8114 static NSString *cellIdentifier = @"SourceCell";
8116 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8117 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8118 [cell setSource:[self sourceAtIndexPath:indexPath]];
8119 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8124 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8125 Source *source = [self sourceAtIndexPath:indexPath];
8127 SourceController *controller = [[[SourceController alloc]
8128 initWithDatabase:database_
8132 [controller setDelegate:delegate_];
8134 [[self navigationController] pushViewController:controller animated:YES];
8137 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8138 Source *source = [self sourceAtIndexPath:indexPath];
8139 return [source record] != nil;
8142 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8143 if (editingStyle == UITableViewCellEditingStyleDelete) {
8144 Source *source = [self sourceAtIndexPath:indexPath];
8145 [Sources_ removeObjectForKey:[source key]];
8146 [delegate_ syncData];
8151 [delegate_ addTrivialSource:href_];
8152 [delegate_ syncData];
8155 - (NSString *) getWarning {
8156 NSString *href(href_);
8157 NSRange colon([href rangeOfString:@"://"]);
8158 if (colon.location != NSNotFound)
8159 href = [href substringFromIndex:(colon.location + 3)];
8160 href = [href stringByAddingPercentEscapes];
8161 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8162 href = [href stringByCachingURLWithCurrentCDN];
8164 NSURL *url([NSURL URLWithString:href]);
8166 NSStringEncoding encoding;
8167 NSError *error(nil);
8169 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8170 return [warning length] == 0 ? nil : warning;
8174 - (void) _endConnection:(NSURLConnection *)connection {
8175 // XXX: the memory management in this method is horribly awkward
8177 NSURLConnection **field = NULL;
8178 if (connection == trivial_)
8180 else if (connection == trivial_bz2_)
8181 field = &trivial_bz2_;
8182 else if (connection == trivial_gz_)
8183 field = &trivial_gz_;
8184 _assert(field != NULL);
8185 [connection release];
8190 trivial_bz2_ == nil &&
8193 [delegate_ releaseNetworkActivityIndicator];
8195 [delegate_ removeProgressHUD:hud_];
8201 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8204 UIAlertView *alert = [[[UIAlertView alloc]
8205 initWithTitle:UCLocalize("SOURCE_WARNING")
8208 cancelButtonTitle:UCLocalize("CANCEL")
8210 UCLocalize("ADD_ANYWAY"),
8214 [alert setContext:@"warning"];
8215 [alert setNumberOfRows:1];
8219 } else if (error_ != nil) {
8220 UIAlertView *alert = [[[UIAlertView alloc]
8221 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8222 message:[error_ localizedDescription]
8224 cancelButtonTitle:UCLocalize("OK")
8225 otherButtonTitles:nil
8228 [alert setContext:@"urlerror"];
8231 UIAlertView *alert = [[[UIAlertView alloc]
8232 initWithTitle:UCLocalize("NOT_REPOSITORY")
8233 message:UCLocalize("NOT_REPOSITORY_EX")
8235 cancelButtonTitle:UCLocalize("OK")
8236 otherButtonTitles:nil
8239 [alert setContext:@"trivial"];
8248 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8249 switch ([response statusCode]) {
8255 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8256 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8258 [self _endConnection:connection];
8261 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8262 [self _endConnection:connection];
8265 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8266 NSURL *url([NSURL URLWithString:href]);
8268 NSMutableURLRequest *request = [NSMutableURLRequest
8270 cachePolicy:NSURLRequestUseProtocolCachePolicy
8271 timeoutInterval:120.0
8274 [request setHTTPMethod:method];
8276 if (Machine_ != NULL)
8277 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8279 if ([url isCydiaSecure]) {
8280 if (UniqueID_ != nil)
8281 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8284 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8287 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8288 NSString *context([alert context]);
8290 if ([context isEqualToString:@"source"]) {
8293 NSString *href = [[alert textField] text];
8295 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8297 if (![href hasSuffix:@"/"])
8298 href_ = [href stringByAppendingString:@"/"];
8302 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8303 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8304 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8305 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8309 // XXX: this is stupid
8310 hud_ = [delegate_ addProgressHUD];
8311 [hud_ setText:UCLocalize("VERIFYING_URL")];
8312 [delegate_ retainNetworkActivityIndicator];
8321 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8322 } else if ([context isEqualToString:@"trivial"])
8323 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8324 else if ([context isEqualToString:@"urlerror"])
8325 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8326 else if ([context isEqualToString:@"warning"]) {
8340 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8345 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8347 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8348 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8349 [list_ setRowHeight:56];
8350 [(UITableView *) list_ setDataSource:self];
8351 [list_ setDelegate:self];
8352 [[self view] addSubview:list_];
8355 - (void) viewDidLoad {
8356 [super viewDidLoad];
8358 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8359 [self updateButtonsForEditingStatus:NO animated:NO];
8362 - (void) releaseSubviews {
8365 [super releaseSubviews];
8368 - (id) initWithDatabase:(Database *)database {
8369 if ((self = [super init]) != nil) {
8370 database_ = database;
8371 sources_ = [NSMutableArray arrayWithCapacity:16];
8375 - (void) reloadData {
8379 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8382 [sources_ removeAllObjects];
8383 [sources_ addObjectsFromArray:[database_ sources]];
8385 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8388 int count([sources_ count]);
8390 for (int i = 0; i != count; i++) {
8391 if ([[sources_ objectAtIndex:i] record] == nil)
8396 [list_ setEditing:NO];
8397 [self updateButtonsForEditingStatus:NO animated:NO];
8401 - (void) showAddSourcePrompt {
8402 UIAlertView *alert = [[[UIAlertView alloc]
8403 initWithTitle:UCLocalize("ENTER_APT_URL")
8406 cancelButtonTitle:UCLocalize("CANCEL")
8408 UCLocalize("ADD_SOURCE"),
8412 [alert setContext:@"source"];
8414 [alert setNumberOfRows:1];
8415 [alert addTextFieldWithValue:@"http://" label:@""];
8417 UITextInputTraits *traits = [[alert textField] textInputTraits];
8418 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8419 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8420 [traits setKeyboardType:UIKeyboardTypeURL];
8421 // XXX: UIReturnKeyDone
8422 [traits setReturnKeyType:UIReturnKeyNext];
8427 - (void) addButtonClicked {
8428 [self showAddSourcePrompt];
8431 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8432 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8433 initWithTitle:UCLocalize("ADD")
8434 style:UIBarButtonItemStylePlain
8436 action:@selector(addButtonClicked)
8437 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8439 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8440 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8441 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8443 action:@selector(editButtonClicked)
8444 ] autorelease] animated:animated];
8446 if (IsWildcat_ && !editing)
8447 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8448 initWithTitle:UCLocalize("SETTINGS")
8449 style:UIBarButtonItemStylePlain
8451 action:@selector(settingsButtonClicked)
8455 - (void) settingsButtonClicked {
8456 [delegate_ showSettings];
8459 - (void) editButtonClicked {
8460 [list_ setEditing:![list_ isEditing] animated:YES];
8462 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8468 /* Settings Controller {{{ */
8469 @interface SettingsController : CyteViewController <
8470 UITableViewDataSource,
8473 _transient Database *database_;
8474 // XXX: ok, "roledelegate_"?...
8475 _transient id roledelegate_;
8476 _H<UITableView, 2> table_;
8477 _H<UISegmentedControl> segment_;
8478 _H<UIView> container_;
8481 - (void) showDoneButton;
8482 - (void) resizeSegmentedControl;
8486 @implementation SettingsController
8489 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8491 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8492 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8493 [table_ setDelegate:self];
8494 [(UITableView *) table_ setDataSource:self];
8495 [[self view] addSubview:table_];
8497 NSArray *items = [NSArray arrayWithObjects:
8499 UCLocalize("HACKER"),
8500 UCLocalize("DEVELOPER"),
8502 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8503 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8504 [container_ addSubview:segment_];
8507 - (void) viewDidLoad {
8508 [super viewDidLoad];
8510 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8513 if ([Role_ isEqualToString:@"User"]) index = 0;
8514 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8515 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8517 [segment_ setSelectedSegmentIndex:index];
8518 [self showDoneButton];
8521 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8522 [self resizeSegmentedControl];
8525 - (void) releaseSubviews {
8530 [super releaseSubviews];
8533 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8534 if ((self = [super init]) != nil) {
8535 database_ = database;
8536 roledelegate_ = delegate;
8540 - (void) resizeSegmentedControl {
8541 CGFloat width = [[self view] frame].size.width;
8542 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8545 - (void) viewWillAppear:(BOOL)animated {
8546 [super viewWillAppear:animated];
8548 [self resizeSegmentedControl];
8551 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8552 [self resizeSegmentedControl];
8555 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8556 [self resizeSegmentedControl];
8560 NSString *role(nil);
8562 switch ([segment_ selectedSegmentIndex]) {
8563 case 0: role = @"User"; break;
8564 case 1: role = @"Hacker"; break;
8565 case 2: role = @"Developer"; break;
8570 if (![role isEqualToString:Role_]) {
8571 bool rolling(Role_ == nil);
8574 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8578 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8582 [roledelegate_ loadData];
8584 [roledelegate_ updateData];
8588 - (void) segmentChanged:(UISegmentedControl *)control {
8589 [self showDoneButton];
8592 - (void) saveAndClose {
8595 [[self navigationItem] setRightBarButtonItem:nil];
8596 [[self navigationController] dismissModalViewControllerAnimated:YES];
8599 - (void) doneButtonClicked {
8600 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8601 [spinner startAnimating];
8602 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8603 [[self navigationItem] setRightBarButtonItem:spinItem];
8605 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8608 - (void) showDoneButton {
8609 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8610 initWithTitle:UCLocalize("DONE")
8611 style:UIBarButtonItemStyleDone
8613 action:@selector(doneButtonClicked)
8614 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8617 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8618 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8622 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8626 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8627 return nil; // This method is required by the protocol.
8630 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8632 return UCLocalize("ROLE_EX");
8634 return [NSString stringWithFormat:
8635 @"%@: %@\n%@: %@\n%@: %@",
8636 UCLocalize("USER"), UCLocalize("USER_EX"),
8637 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8638 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8643 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8644 return section == 3 ? 44.0f : 0;
8647 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8648 return section == 3 ? container_ : nil;
8651 - (void) reloadData {
8654 [table_ reloadData];
8659 /* Stash Controller {{{ */
8660 @interface StashController : CyteViewController {
8661 _H<UIActivityIndicatorView> spinner_;
8662 _H<UILabel> status_;
8663 _H<UILabel> caption_;
8668 @implementation StashController
8671 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8672 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8674 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8675 CGRect spinrect = [spinner_ frame];
8676 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8677 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8678 [spinner_ setFrame:spinrect];
8679 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8680 [[self view] addSubview:spinner_];
8681 [spinner_ startAnimating];
8684 captrect.size.width = [[self view] frame].size.width;
8685 captrect.size.height = 40.0f;
8686 captrect.origin.x = 0;
8687 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8688 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8689 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8690 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8691 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8692 [caption_ setTextColor:[UIColor whiteColor]];
8693 [caption_ setBackgroundColor:[UIColor clearColor]];
8694 [caption_ setShadowColor:[UIColor blackColor]];
8695 [caption_ setTextAlignment:UITextAlignmentCenter];
8696 [[self view] addSubview:caption_];
8699 statusrect.size.width = [[self view] frame].size.width;
8700 statusrect.size.height = 30.0f;
8701 statusrect.origin.x = 0;
8702 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8703 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8704 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8705 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8706 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8707 [status_ setTextColor:[UIColor whiteColor]];
8708 [status_ setBackgroundColor:[UIColor clearColor]];
8709 [status_ setShadowColor:[UIColor blackColor]];
8710 [status_ setTextAlignment:UITextAlignmentCenter];
8711 [[self view] addSubview:status_];
8714 - (void) releaseSubviews {
8719 [super releaseSubviews];
8725 @interface CYURLCache : SDURLCache {
8730 @implementation CYURLCache
8732 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8735 else if ([event isEqualToString:@"no-cache"])
8737 else if ([event isEqualToString:@"store"])
8739 else if ([event isEqualToString:@"invalid"])
8741 else if ([event isEqualToString:@"memory"])
8743 else if ([event isEqualToString:@"disk"])
8745 else if ([event isEqualToString:@"miss"])
8748 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8752 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8753 if (NSURLResponse *response = [cached response])
8754 if (NSString *mime = [response MIMEType])
8755 if ([mime isEqualToString:@"text/cache-manifest"]) {
8756 NSURL *url([response URL]);
8759 NSLog(@"###: %@", [url absoluteString]);
8762 @synchronized (HostConfig_) {
8763 [CachedURLs_ addObject:url];
8767 [super storeCachedResponse:cached forRequest:request];
8772 @interface Cydia : UIApplication <
8773 ConfirmationControllerDelegate,
8776 UINavigationControllerDelegate,
8777 UITabBarControllerDelegate
8779 _H<UIWindow> window_;
8780 _H<CYTabBarController> tabbar_;
8781 _H<CydiaLoadingViewController> emulated_;
8783 _H<NSMutableArray> essential_;
8784 _H<NSMutableArray> broken_;
8786 Database *database_;
8788 _H<NSURL> starturl_;
8793 _H<StashController> stash_;
8802 @implementation Cydia
8804 - (void) beginUpdate {
8805 [tabbar_ beginUpdate];
8809 return [tabbar_ updating];
8813 if ([broken_ count] != 0) {
8814 int count = [broken_ count];
8816 UIAlertView *alert = [[[UIAlertView alloc]
8817 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8818 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8820 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8822 UCLocalize("TEMPORARY_IGNORE"),
8826 [alert setContext:@"fixhalf"];
8827 [alert setNumberOfRows:2];
8829 } else if (!Ignored_ && [essential_ count] != 0) {
8830 int count = [essential_ count];
8832 UIAlertView *alert = [[[UIAlertView alloc]
8833 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8834 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8836 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8838 UCLocalize("UPGRADE_ESSENTIAL"),
8839 UCLocalize("COMPLETE_UPGRADE"),
8843 [alert setContext:@"upgrade"];
8848 - (void) _saveConfig {
8854 NSString *error(nil);
8856 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8858 NSError *error(nil);
8859 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8860 NSLog(@"failure to save metadata data: %@", error);
8865 NSLog(@"failure to serialize metadata: %@", error);
8872 // Navigation controller for the queuing badge.
8873 - (UINavigationController *) queueNavigationController {
8874 NSArray *controllers = [tabbar_ viewControllers];
8875 return [controllers objectAtIndex:3];
8878 - (void) unloadData {
8879 [tabbar_ unloadData];
8882 - (void) _updateData {
8886 UINavigationController *navigation = [self queueNavigationController];
8888 id queuedelegate = nil;
8889 if ([[navigation viewControllers] count] > 0)
8890 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8892 [queuedelegate queueStatusDidChange];
8893 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8896 - (void) _refreshIfPossible:(NSDate *)update {
8897 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8899 bool recently = false;
8900 if (update != nil) {
8901 NSTimeInterval interval([update timeIntervalSinceNow]);
8902 if (interval <= 0 && interval > -(15*60))
8906 // Don't automatic refresh if:
8907 // - We already refreshed recently.
8908 // - We already auto-refreshed this launch.
8909 // - Auto-refresh is disabled.
8910 if (recently || loaded_ || ManualRefresh) {
8911 // If we are cancelling, we need to make sure it knows it's already loaded.
8914 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8916 // We are going to load, so remember that.
8919 SCNetworkReachabilityFlags flags; {
8920 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8921 SCNetworkReachabilityGetFlags(reachability, &flags);
8922 CFRelease(reachability);
8925 // XXX: this elaborate mess is what Apple is using to determine this? :(
8926 // XXX: do we care if the user has to intervene? maybe that's ok?
8928 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8929 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8930 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8931 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8932 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8933 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8937 // If we can reach the server, auto-refresh!
8939 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8945 - (void) refreshIfPossible {
8946 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8949 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8950 @synchronized (self) {
8951 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8952 [hud setText:UCLocalize("RELOADING_DATA")];
8954 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8957 [self removeProgressHUD:hud];
8961 [essential_ removeAllObjects];
8962 [broken_ removeAllObjects];
8964 NSArray *packages([database_ packages]);
8965 for (Package *package in packages) {
8967 [broken_ addObject:package];
8968 if ([package upgradableAndEssential:NO]) {
8969 if ([package essential])
8970 [essential_ addObject:package];
8975 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8978 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8979 [changesItem setBadgeValue:badge];
8980 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8981 [self setApplicationIconBadgeNumber:changes];
8984 [changesItem setBadgeValue:nil];
8985 [changesItem setAnimatedBadge:NO];
8986 [self setApplicationIconBadgeNumber:0];
8991 [self refreshIfPossible];
8994 - (void) updateData {
9000 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9003 - (void) disemulate {
9004 if (emulated_ == nil)
9007 [window_ addSubview:[tabbar_ view]];
9008 [[emulated_ view] removeFromSuperview];
9010 [window_ setUserInteractionEnabled:YES];
9013 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9014 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9016 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9018 UIViewController *parent;
9019 if (emulated_ == nil)
9028 [parent presentModalViewController:navigation animated:YES];
9031 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9032 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9034 if (navigation != nil)
9035 [navigation pushViewController:progress animated:YES];
9037 [self presentModalViewController:progress force:YES];
9039 [progress invoke:invocation withTitle:title];
9043 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9044 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9047 - (void) repairWithInvocation:(NSInvocation *)invocation {
9049 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9053 - (void) repairWithSelector:(SEL)selector {
9054 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9057 - (void) reloadData {
9058 [self reloadDataWithInvocation:nil];
9063 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9066 - (void) addSource:(NSDictionary *) source {
9070 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9071 AddSource(href, distribution, sections);
9074 - (void) addTrivialSource:(NSString *)href {
9075 AddSource(href, @"./");
9078 - (void) updateValues {
9083 pkgProblemResolver *resolver = [database_ resolver];
9085 resolver->InstallProtect();
9086 if (!resolver->Resolve(true))
9091 // XXX: this is a really crappy way of doing this.
9092 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9093 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9094 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9095 if ([tabbar_ updating])
9096 [tabbar_ cancelUpdate];
9098 if (![database_ prepare])
9101 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9102 [page setDelegate:self];
9103 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9106 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9107 [tabbar_ presentModalViewController:confirm_ animated:YES];
9113 @synchronized (self) {
9118 - (void) clearPackage:(Package *)package {
9119 @synchronized (self) {
9126 - (void) installPackages:(NSArray *)packages {
9127 @synchronized (self) {
9128 for (Package *package in packages)
9135 - (void) installPackage:(Package *)package {
9136 @synchronized (self) {
9143 - (void) removePackage:(Package *)package {
9144 @synchronized (self) {
9151 - (void) distUpgrade {
9152 @synchronized (self) {
9153 if (![database_ upgrade])
9160 [database_ perform];
9161 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9164 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9167 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9171 - (void) showSettings {
9172 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9175 - (void) retainNetworkActivityIndicator {
9176 if (activity_++ == 0)
9177 [self setNetworkActivityIndicatorVisible:YES];
9180 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9184 - (void) releaseNetworkActivityIndicator {
9185 if (--activity_ == 0)
9186 [self setNetworkActivityIndicatorVisible:NO];
9189 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9194 - (void) cancelAndClear:(bool)clear {
9195 @synchronized (self) {
9207 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9208 NSString *context([alert context]);
9210 if ([context isEqualToString:@"conffile"]) {
9211 FILE *input = [database_ input];
9212 if (button == [alert cancelButtonIndex])
9213 fprintf(input, "N\n");
9214 else if (button == [alert firstOtherButtonIndex])
9215 fprintf(input, "Y\n");
9218 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9219 } else if ([context isEqualToString:@"fixhalf"]) {
9220 if (button == [alert cancelButtonIndex]) {
9221 @synchronized (self) {
9222 for (Package *broken in (id) broken_) {
9225 NSString *id = [broken id];
9226 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9227 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9228 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9229 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9235 } else if (button == [alert firstOtherButtonIndex]) {
9236 [broken_ removeAllObjects];
9240 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9241 } else if ([context isEqualToString:@"upgrade"]) {
9242 if (button == [alert firstOtherButtonIndex]) {
9243 @synchronized (self) {
9244 for (Package *essential in (id) essential_)
9245 [essential install];
9250 } else if (button == [alert firstOtherButtonIndex] + 1) {
9252 } else if (button == [alert cancelButtonIndex]) {
9256 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9260 - (void) system:(NSString *)command {
9261 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9264 system([command UTF8String]);
9270 - (void) applicationWillSuspend {
9272 [super applicationWillSuspend];
9275 - (BOOL) isSafeToSuspend {
9278 NSLog(@"isSafeToSuspend: locked_ != 0");
9283 // Use external process status API internally.
9284 // This is probably a really bad idea.
9285 // XXX: what is the point of this? does this solve anything at all?
9286 uint64_t status = 0;
9288 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9289 notify_get_state(notify_token, &status);
9290 notify_cancel(notify_token);
9295 NSLog(@"isSafeToSuspend: status != 0");
9301 NSLog(@"isSafeToSuspend: -> true");
9306 - (void) applicationSuspend:(__GSEvent *)event {
9307 if ([self isSafeToSuspend])
9308 [super applicationSuspend:event];
9311 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9312 if ([self isSafeToSuspend])
9313 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9316 - (void) _setSuspended:(BOOL)value {
9317 if ([self isSafeToSuspend])
9318 [super _setSuspended:value];
9321 - (UIProgressHUD *) addProgressHUD {
9322 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9323 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9325 [window_ setUserInteractionEnabled:NO];
9327 UIViewController *target(tabbar_);
9328 if (UIViewController *modal = [target modalViewController])
9331 UIView *view([target view]);
9332 [view addSubview:hud];
9340 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9343 [hud removeFromSuperview];
9344 [window_ setUserInteractionEnabled:YES];
9347 - (CyteViewController *) pageForPackage:(NSString *)name {
9348 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9351 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9352 NSString *scheme([[url scheme] lowercaseString]);
9353 if ([[url absoluteString] length] <= [scheme length] + 3)
9355 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9356 NSArray *components([path pathComponents]);
9358 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9359 return [self pageForPackage:[components objectAtIndex:1]];
9361 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9364 NSString *base([components objectAtIndex:0]);
9366 CyteViewController *controller = nil;
9368 if ([base isEqualToString:@"url"]) {
9369 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9370 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9371 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9372 } else if (!external && [components count] == 1) {
9373 if ([base isEqualToString:@"manage"]) {
9374 controller = [[[ManageController alloc] init] autorelease];
9377 if ([base isEqualToString:@"sources"]) {
9378 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9381 if ([base isEqualToString:@"home"]) {
9382 controller = [[[HomeController alloc] init] autorelease];
9385 if ([base isEqualToString:@"sections"]) {
9386 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9389 if ([base isEqualToString:@"search"]) {
9390 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9393 if ([base isEqualToString:@"changes"]) {
9394 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9397 if ([base isEqualToString:@"installed"]) {
9398 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9400 } else if ([components count] == 2) {
9401 NSString *argument = [components objectAtIndex:1];
9403 if ([base isEqualToString:@"package"]) {
9404 controller = [self pageForPackage:argument];
9407 if (!external && [base isEqualToString:@"search"]) {
9408 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9411 if (!external && [base isEqualToString:@"sections"]) {
9412 if ([argument isEqualToString:@"all"])
9414 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9417 if (!external && [base isEqualToString:@"sources"]) {
9418 if ([argument isEqualToString:@"add"]) {
9419 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9420 [(SourcesController *)controller showAddSourcePrompt];
9422 Source *source = [database_ sourceWithKey:argument];
9423 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9427 if (!external && [base isEqualToString:@"launch"]) {
9428 [self launchApplicationWithIdentifier:argument suspended:NO];
9431 } else if (!external && [components count] == 3) {
9432 NSString *arg1 = [components objectAtIndex:1];
9433 NSString *arg2 = [components objectAtIndex:2];
9435 if ([base isEqualToString:@"package"]) {
9436 if ([arg2 isEqualToString:@"settings"]) {
9437 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9438 } else if ([arg2 isEqualToString:@"files"]) {
9439 if (Package *package = [database_ packageWithName:arg1]) {
9440 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9441 [(FileTable *)controller setPackage:package];
9447 [controller setDelegate:self];
9451 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9452 CyteViewController *page([self pageForURL:url forExternal:external]);
9455 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9456 [nav setViewControllers:[NSArray arrayWithObject:page]];
9457 [tabbar_ setUnselectedViewController:nav];
9463 - (void) applicationOpenURL:(NSURL *)url {
9464 [super applicationOpenURL:url];
9469 [self openCydiaURL:url forExternal:YES];
9472 - (void) applicationWillResignActive:(UIApplication *)application {
9473 // Stop refreshing if you get a phone call or lock the device.
9474 if ([tabbar_ updating])
9475 [tabbar_ cancelUpdate];
9477 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9478 [super applicationWillResignActive:application];
9481 - (void) applicationWillTerminate:(UIApplication *)application {
9483 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9484 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9485 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9490 - (void) setConfigurationData:(NSString *)data {
9491 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9493 if (!conffile_r(data)) {
9494 lprintf("E:invalid conffile\n");
9498 NSString *ofile = conffile_r[1];
9499 //NSString *nfile = conffile_r[2];
9501 UIAlertView *alert = [[[UIAlertView alloc]
9502 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9503 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9505 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9507 UCLocalize("ACCEPT_NEW_COPY"),
9508 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9512 [alert setContext:@"conffile"];
9513 [alert setNumberOfRows:2];
9517 - (void) addStashController {
9519 stash_ = [[[StashController alloc] init] autorelease];
9520 [window_ addSubview:[stash_ view]];
9523 - (void) removeStashController {
9524 [[stash_ view] removeFromSuperview];
9530 [self setIdleTimerDisabled:YES];
9532 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9533 UpdateExternalStatus(1);
9534 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9535 UpdateExternalStatus(0);
9537 [self removeStashController];
9539 if (ExecFork() == 0) {
9540 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9541 perror("launchctl stop");
9545 - (void) setupViewControllers {
9546 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9548 NSMutableArray *items([NSMutableArray arrayWithObjects:
9549 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9550 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9551 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9552 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9556 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9557 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9559 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9562 NSMutableArray *controllers([NSMutableArray array]);
9563 for (UITabBarItem *item in items) {
9564 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9565 [controller setTabBarItem:item];
9566 [controllers addObject:controller];
9568 [tabbar_ setViewControllers:controllers];
9570 [tabbar_ setUpdateDelegate:self];
9573 - (void) applicationDidFinishLaunching:(id)unused {
9575 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9576 [self setApplicationSupportsShakeToEdit:NO];
9578 @synchronized (HostConfig_) {
9579 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9582 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9583 initWithMemoryCapacity:524288
9584 diskCapacity:10485760
9585 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9588 [CydiaWebViewController _initialize];
9590 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9592 // this would disallow http{,s} URLs from accessing this data
9593 //[WebView registerURLSchemeAsLocal:@"cydia"];
9595 Font12_ = [UIFont systemFontOfSize:12];
9596 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9597 Font14_ = [UIFont systemFontOfSize:14];
9598 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9599 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9601 essential_ = [NSMutableArray arrayWithCapacity:4];
9602 broken_ = [NSMutableArray arrayWithCapacity:4];
9604 // XXX: I really need this thing... like, seriously... I'm sorry
9605 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9607 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9608 [window_ orderFront:self];
9609 [window_ makeKey:self];
9610 [window_ setHidden:NO];
9613 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9614 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9615 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9616 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9617 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9618 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9619 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9620 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9621 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9624 [self addStashController];
9625 // XXX: this would be much cleaner as a yieldToSelector:
9626 // that way the removeStashController could happen right here inline
9627 // we also could no longer require the useless stash_ field anymore
9628 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9632 database_ = [Database sharedInstance];
9633 [database_ setDelegate:self];
9635 [window_ setUserInteractionEnabled:NO];
9636 [self setupViewControllers];
9638 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9639 [window_ addSubview:[emulated_ view]];
9641 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9645 - (NSArray *) defaultStartPages {
9646 NSMutableArray *standard = [NSMutableArray array];
9647 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9648 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9649 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9651 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9653 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9654 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9656 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9663 [window_ setUserInteractionEnabled:YES];
9664 [self showSettings];
9667 if ([emulated_ modalViewController] != nil)
9668 [emulated_ dismissModalViewControllerAnimated:YES];
9669 [window_ setUserInteractionEnabled:NO];
9677 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9678 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9679 int standardIndex = 0;
9680 NSArray *standard = [self defaultStartPages];
9687 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9688 if (valid && closed != nil) {
9689 NSTimeInterval interval([closed timeIntervalSinceNow]);
9690 // XXX: Is 15 minutes the optimal time here?
9691 if (interval > 0 && interval <= -(15*60))
9695 if (valid && [saved count] != [standard count])
9699 for (unsigned int i = 0; i < [standard count]; i++) {
9700 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9701 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9702 // but it's good enough for now.
9703 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9710 NSArray *items = nil;
9712 [tabbar_ setSelectedIndex:savedIndex];
9715 [tabbar_ setSelectedIndex:standardIndex];
9719 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9720 NSArray *stack = [items objectAtIndex:tab];
9721 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9722 NSMutableArray *current = [NSMutableArray array];
9724 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9725 NSString *addr = [stack objectAtIndex:nav];
9726 NSURL *url = [NSURL URLWithString:addr];
9727 CyteViewController *page = [self pageForURL:url forExternal:NO];
9729 [current addObject:page];
9732 [navigation setViewControllers:current];
9735 // (Try to) show the startup URL.
9736 if (starturl_ != nil) {
9737 [self openCydiaURL:starturl_ forExternal:NO];
9742 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9743 if (item != nil && IsWildcat_) {
9744 [sheet showFromBarButtonItem:item animated:YES];
9746 [sheet showInView:window_];
9750 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9751 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9752 [progress setTitle:task];
9753 [progress addProgressEvent:event];
9756 - (void) addProgressEventForTask:(NSArray *)data {
9757 CydiaProgressEvent *event([data objectAtIndex:0]);
9758 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9759 [self addProgressEvent:event forTask:task];
9762 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9763 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9769 id Alloc_(id self, SEL selector) {
9770 id object = alloc_(self, selector);
9771 lprintf("[%s]A-%p\n", self->isa->name, object);
9776 id Dealloc_(id self, SEL selector) {
9777 id object = dealloc_(self, selector);
9778 lprintf("[%s]D-%p\n", self->isa->name, object);
9782 Class $WebDefaultUIKitDelegate;
9784 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9785 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9786 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9787 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9790 static NSSet *MobilizedFiles_;
9792 static NSURL *MobilizeURL(NSURL *url) {
9793 NSString *path([url path]);
9794 if ([path hasPrefix:@"/var/root/"]) {
9795 NSString *file([path substringFromIndex:10]);
9796 if ([MobilizedFiles_ containsObject:file])
9797 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9803 Class $CFXPreferencesPropertyListSource;
9804 @class CFXPreferencesPropertyListSource;
9806 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9807 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9808 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9809 url = MobilizeURL(url);
9810 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9811 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9817 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9818 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9819 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9820 url = MobilizeURL(url);
9821 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9822 //NSLog(@"%@ %@", [url absoluteString], value);
9828 Class $NSURLConnection;
9830 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9831 NSMutableURLRequest *copy([request mutableCopy]);
9833 NSURL *url([copy URL]);
9835 NSString *href([url absoluteString]);
9836 NSString *host([url host]);
9837 NSString *scheme([[url scheme] lowercaseString]);
9839 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9841 @synchronized (HostConfig_) {
9842 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9843 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9844 [copy setHTTPShouldUsePipelining:YES];
9846 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9847 if ([control isEqualToString:@"max-age=0"])
9848 if ([CachedURLs_ containsObject:href]) {
9850 NSLog(@"~~~: %@", href);
9853 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9855 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9856 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9857 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9861 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9865 int main(int argc, char *argv[]) {
9866 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9870 UpdateExternalStatus(0);
9872 if (Class $UIDevice = objc_getClass("UIDevice")) {
9873 UIDevice *device([$UIDevice currentDevice]);
9874 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9878 UIScreen *screen([UIScreen mainScreen]);
9879 if ([screen respondsToSelector:@selector(scale)])
9880 ScreenScale_ = [screen scale];
9884 UIDevice *device([UIDevice currentDevice]);
9885 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9888 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9889 if (idiom == UIUserInterfaceIdiomPhone)
9891 else if (idiom == UIUserInterfaceIdiomPad)
9894 NSLog(@"unknown UIUserInterfaceIdiom!");
9897 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9899 HostConfig_ = [[[NSObject alloc] init] autorelease];
9900 @synchronized (HostConfig_) {
9901 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9902 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9903 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9904 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9905 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9908 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9910 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9912 MobilizedFiles_ = [NSMutableSet setWithObjects:
9913 @"Library/Preferences/com.apple.Accessibility.plist",
9914 @"Library/Preferences/com.apple.preferences.sounds.plist",
9917 /* Library Hacks {{{ */
9918 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9920 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9922 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9923 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9924 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9925 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9928 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9929 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9930 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9931 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9934 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9935 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9936 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9937 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9938 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9941 $NSURLConnection = objc_getClass("NSURLConnection");
9942 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9943 if (NSURLConnection$init$ != NULL) {
9944 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9945 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9948 /* Set Locale {{{ */
9949 Locale_ = CFLocaleCopyCurrent();
9950 Languages_ = [NSLocale preferredLanguages];
9952 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9953 //NSLog(@"%@", [Languages_ description]);
9956 if (Locale_ != NULL)
9957 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9958 else if (Languages_ != nil && [Languages_ count] != 0)
9959 lang = [[Languages_ objectAtIndex:0] UTF8String];
9961 // XXX: consider just setting to C and then falling through?
9965 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9966 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9969 NSLog(@"Setting Language: %s", lang);
9972 setenv("LANG", lang, true);
9973 std::setlocale(LC_ALL, lang);
9977 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9979 /* Parse Arguments {{{ */
9980 bool substrate(false);
9986 for (int argi(1); argi != argc; ++argi)
9987 if (strcmp(argv[argi], "--") == 0) {
9989 argv[argi] = argv[0];
9995 for (int argi(1); argi != arge; ++argi)
9996 if (strcmp(args[argi], "--substrate") == 0)
9999 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10003 App_ = [[NSBundle mainBundle] bundlePath];
10009 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10010 alloc_ = alloc->method_imp;
10011 alloc->method_imp = (IMP) &Alloc_;*/
10013 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10014 dealloc_ = dealloc->method_imp;
10015 dealloc->method_imp = (IMP) &Dealloc_;*/
10017 /* System Information {{{ */
10021 size = sizeof(maxproc);
10022 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10023 perror("sysctlbyname(\"kern.maxproc\", ?)");
10024 else if (maxproc < 64) {
10026 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10027 perror("sysctlbyname(\"kern.maxproc\", #)");
10030 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10031 char *osversion = new char[size];
10032 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10033 perror("sysctlbyname(\"kern.osversion\", ?)");
10035 System_ = [NSString stringWithUTF8String:osversion];
10037 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10038 char *machine = new char[size];
10039 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10040 perror("sysctlbyname(\"hw.machine\", ?)");
10042 Machine_ = machine;
10044 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10045 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10046 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10048 UniqueID_ = [device uniqueIdentifier];
10050 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10051 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10052 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10054 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10055 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10056 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10058 if (mcc != NULL && mnc != NULL)
10059 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10066 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10067 Build_ = [system objectForKey:@"ProductBuildVersion"];
10068 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10069 Product_ = [info objectForKey:@"SafariProductVersion"];
10070 Safari_ = [info objectForKey:@"CFBundleVersion"];
10073 /* Load Database {{{ */
10075 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10077 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10079 if (Metadata_ == NULL)
10080 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10082 Settings_ = [Metadata_ objectForKey:@"Settings"];
10084 Packages_ = [Metadata_ objectForKey:@"Packages"];
10086 Values_ = [Metadata_ objectForKey:@"Values"];
10087 Sections_ = [Metadata_ objectForKey:@"Sections"];
10088 Sources_ = [Metadata_ objectForKey:@"Sources"];
10090 Token_ = [Metadata_ objectForKey:@"Token"];
10092 Version_ = [Metadata_ objectForKey:@"Version"];
10094 @synchronized (HostConfig_) {
10095 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10099 if (Settings_ != nil)
10100 Role_ = [Settings_ objectForKey:@"Role"];
10102 if (Values_ == nil) {
10103 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10104 [Metadata_ setObject:Values_ forKey:@"Values"];
10107 if (Sections_ == nil) {
10108 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10109 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10112 if (Sources_ == nil) {
10113 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10114 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10117 if (Version_ == nil) {
10118 Version_ = [NSNumber numberWithUnsignedInt:0];
10119 [Metadata_ setObject:Version_ forKey:@"Version"];
10122 @synchronized (HostConfig_) {
10123 if (CydiaSource_ == nil) {
10124 CydiaSource_ = @"apt.saurik.com";
10125 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10129 if ([Version_ unsignedIntValue] == 0) {
10130 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10131 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10132 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10133 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10135 Version_ = [NSNumber numberWithUnsignedInt:1];
10136 [Metadata_ setObject:Version_ forKey:@"Version"];
10145 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10148 if (Packages_ != nil) {
10150 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10154 [Metadata_ removeObjectForKey:@"Packages"];
10160 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10162 #define MobileSubstrate_(name) \
10163 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10164 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10165 if (handle == NULL) \
10166 NSLog(@"%s", dlerror()); \
10169 MobileSubstrate_(Activator)
10170 MobileSubstrate_(libstatusbar)
10171 MobileSubstrate_(SimulatedKeyEvents)
10172 MobileSubstrate_(WinterBoard)
10174 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10175 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10177 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10179 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10180 unlink("/tmp/.cydia.fw");
10182 } else if (access("/User", F_OK) != 0 || version < 4) {
10185 system("/usr/libexec/cydia/firmware.sh");
10189 _assert([[NSFileManager defaultManager]
10190 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10191 withIntermediateDirectories:YES
10196 if (access("/tmp/cydia.chk", F_OK) == 0) {
10197 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10198 _assert(errno == ENOENT);
10199 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10200 _assert(errno == ENOENT);
10203 /* APT Initialization {{{ */
10204 _assert(pkgInitConfig(*_config));
10205 _assert(pkgInitSystem(*_config, _system));
10208 _config->Set("APT::Acquire::Translation", lang);
10210 // XXX: this timeout might be important :(
10211 //_config->Set("Acquire::http::Timeout", 15);
10213 _config->Set("Acquire::http::MaxParallel", 3);
10215 /* Color Choices {{{ */
10216 space_ = CGColorSpaceCreateDeviceRGB();
10218 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10219 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10220 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10221 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10222 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10223 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10224 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10225 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10226 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10228 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10229 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10231 /* UIKit Configuration {{{ */
10232 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10233 if ($GSFontSetUseLegacyFontMetrics != NULL)
10234 $GSFontSetUseLegacyFontMetrics(YES);
10236 // XXX: I have a feeling this was important
10237 //UIKeyboardDisableAutomaticAppearance();
10240 Colon_ = UCLocalize("COLON_DELIMITED");
10241 Elision_ = UCLocalize("ELISION");
10242 Error_ = UCLocalize("ERROR");
10243 Warning_ = UCLocalize("WARNING");
10246 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10248 CGColorSpaceRelease(space_);
10249 CFRelease(Locale_);