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
875 - (void) retainNetworkActivityIndicator;
876 - (void) releaseNetworkActivityIndicator;
877 - (void) clearPackage:(Package *)package;
878 - (void) installPackage:(Package *)package;
879 - (void) installPackages:(NSArray *)packages;
880 - (void) removePackage:(Package *)package;
881 - (void) beginUpdate;
883 - (void) distUpgrade;
887 - (void) addSource:(NSDictionary *)source;
888 - (void) addTrivialSource:(NSString *)href;
889 - (void) showSettings;
890 - (UIProgressHUD *) addProgressHUD;
891 - (void) removeProgressHUD:(UIProgressHUD *)hud;
892 - (CyteViewController *) pageForPackage:(NSString *)name;
893 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
894 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
898 /* Status Delegation {{{ */
900 public pkgAcquireStatus
903 _transient NSObject<ProgressDelegate> *delegate_;
913 void setDelegate(NSObject<ProgressDelegate> *delegate) {
914 delegate_ = delegate;
917 NSObject<ProgressDelegate> *getDelegate() const {
921 virtual bool MediaChange(std::string media, std::string drive) {
925 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
928 virtual void Fetch(pkgAcquire::ItemDesc &item) {
929 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
930 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
931 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
934 virtual void Done(pkgAcquire::ItemDesc &item) {
937 virtual void Fail(pkgAcquire::ItemDesc &item) {
939 item.Owner->Status == pkgAcquire::Item::StatIdle ||
940 item.Owner->Status == pkgAcquire::Item::StatDone
944 std::string &error(item.Owner->ErrorText);
948 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
949 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
952 virtual bool Pulse(pkgAcquire *Owner) {
953 bool value = pkgAcquireStatus::Pulse(Owner);
956 double(CurrentBytes + CurrentItems) /
957 double(TotalBytes + TotalItems)
960 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
961 [NSNumber numberWithDouble:percent], @"Percent",
963 [NSNumber numberWithDouble:CurrentBytes], @"Current",
964 [NSNumber numberWithDouble:TotalBytes], @"Total",
965 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
966 nil] waitUntilDone:YES];
968 if (value && ![delegate_ isProgressCancelled])
976 _finline bool WasCancelled() const {
980 virtual void Start() {
981 pkgAcquireStatus::Start();
982 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
985 virtual void Stop() {
986 pkgAcquireStatus::Stop();
987 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
988 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
992 /* Database Interface {{{ */
993 typedef std::map< unsigned long, _H<Source> > SourceMap;
995 @interface Database : NSObject {
1001 pkgCacheFile cache_;
1002 pkgDepCache::Policy *policy_;
1003 pkgRecords *records_;
1004 pkgProblemResolver *resolver_;
1005 pkgAcquire *fetcher_;
1007 SPtr<pkgPackageManager> manager_;
1008 pkgSourceList *list_;
1010 SourceMap sourceMap_;
1011 _H<NSMutableArray> sourceList_;
1013 CFMutableArrayRef packages_;
1015 _transient NSObject<DatabaseDelegate> *delegate_;
1016 _transient NSObject<ProgressDelegate> *progress_;
1024 std::map<const char *, _H<NSString> > sections_;
1027 + (Database *) sharedInstance;
1030 - (void) _readCydia:(NSNumber *)fd;
1031 - (void) _readStatus:(NSNumber *)fd;
1032 - (void) _readOutput:(NSNumber *)fd;
1036 - (Package *) packageWithName:(NSString *)name;
1038 - (pkgCacheFile &) cache;
1039 - (pkgDepCache::Policy *) policy;
1040 - (pkgRecords *) records;
1041 - (pkgProblemResolver *) resolver;
1042 - (pkgAcquire &) fetcher;
1043 - (pkgSourceList &) list;
1044 - (NSArray *) packages;
1045 - (NSArray *) sources;
1046 - (Source *) sourceWithKey:(NSString *)key;
1047 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1055 - (void) updateWithStatus:(Status &)status;
1057 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1059 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1060 - (NSObject<ProgressDelegate> *) progressDelegate;
1062 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1064 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1068 /* ProgressEvent Implementation {{{ */
1069 @implementation CydiaProgressEvent
1071 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1072 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1075 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1076 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1077 [event setPackage:package];
1081 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1082 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1084 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1085 NSArray *fields([description componentsSeparatedByString:@" "]);
1086 [event setItem:fields];
1088 if ([fields count] > 3) {
1089 [event setPackage:[fields objectAtIndex:2]];
1090 [event setVersion:[fields objectAtIndex:3]];
1093 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1098 + (NSArray *) _attributeKeys {
1099 return [NSArray arrayWithObjects:
1109 - (NSArray *) attributeKeys {
1110 return [[self class] _attributeKeys];
1113 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1114 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1117 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1118 if ((self = [super init]) != nil) {
1124 - (NSString *) message {
1128 - (NSString *) type {
1132 - (NSArray *) item {
1133 return (id) item_ ?: [NSNull null];
1136 - (void) setItem:(NSArray *)item {
1140 - (NSString *) package {
1141 return (id) package_ ?: [NSNull null];
1144 - (void) setPackage:(NSString *)package {
1148 - (NSString *) url {
1149 return (id) url_ ?: [NSNull null];
1152 - (void) setURL:(NSString *)url {
1156 - (void) setVersion:(NSString *)version {
1160 - (NSString *) version {
1161 return (id) version_ ?: [NSNull null];
1164 - (NSString *) compound:(NSString *)value {
1166 NSString *mode(nil); {
1167 NSString *type([self type]);
1168 if ([type isEqualToString:kCydiaProgressEventTypeError])
1169 mode = UCLocalize("ERROR");
1170 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1171 mode = UCLocalize("WARNING");
1175 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1181 - (NSString *) compoundMessage {
1182 return [self compound:[self message]];
1185 - (NSString *) compoundTitle {
1188 if (package_ == nil)
1190 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1191 title = [package name];
1195 return [self compound:title];
1201 // Cytore Definitions {{{
1202 struct PackageValue :
1205 Cytore::Offset<PackageValue> next_;
1207 uint32_t index_ : 23;
1208 uint32_t subscribed_ : 1;
1225 Cytore::Offset<PackageValue> packages_[1 << 16];
1228 static Cytore::File<MetaValue> MetaFile_;
1230 // Cytore Helper Functions {{{
1231 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1232 SplitHash nhash = { hashlittle(name, length) };
1234 PackageValue *metadata;
1236 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1237 offset: if (offset->IsNull()) {
1238 *offset = MetaFile_.New<PackageValue>(length + 1);
1239 metadata = &MetaFile_.Get(*offset);
1241 if (metadata == NULL) {
1245 metadata = new PackageValue();
1246 memset(metadata, 0, sizeof(*metadata));
1249 memcpy(metadata->name_, name, length + 1);
1250 metadata->nhash_ = nhash.u16[1];
1252 metadata = &MetaFile_.Get(*offset);
1254 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1255 offset = &metadata->next_;
1263 static void PackageImport(const void *key, const void *value, void *context) {
1264 bool &fail(*reinterpret_cast<bool *>(context));
1267 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1268 NSLog(@"failed to import package %@", key);
1272 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1273 NSDictionary *package((NSDictionary *) value);
1275 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1276 if ([subscribed boolValue] && !metadata->subscribed_)
1277 metadata->subscribed_ = true;
1279 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1280 time_t time([date timeIntervalSince1970]);
1281 if (metadata->first_ > time || metadata->first_ == 0)
1282 metadata->first_ = time;
1285 NSDate *date([package objectForKey:@"LastSeen"]);
1286 NSString *version([package objectForKey:@"LastVersion"]);
1288 if (date != nil && version != nil) {
1289 time_t time([date timeIntervalSince1970]);
1290 if (metadata->last_ < time || metadata->last_ == 0)
1291 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1292 size_t length(strlen(buffer));
1293 uint16_t vhash(hashlittle(buffer, length));
1295 size_t capped(std::min<size_t>(8, length));
1296 char *latest(buffer + length - capped);
1298 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1299 metadata->vhash_ = vhash;
1301 metadata->last_ = time;
1307 /* Source Class {{{ */
1308 @interface Source : NSObject {
1309 CYString depiction_;
1310 CYString description_;
1316 CYString distribution_;
1322 _H<NSString> authority_;
1324 CYString defaultIcon_;
1326 _H<NSDictionary> record_;
1330 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1332 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1334 - (NSString *) depictionForPackage:(NSString *)package;
1335 - (NSString *) supportForPackage:(NSString *)package;
1337 - (NSDictionary *) record;
1341 - (NSString *) distribution;
1342 - (NSString *) type;
1344 - (NSString *) base;
1347 - (NSString *) host;
1349 - (NSString *) name;
1350 - (NSString *) shortDescription;
1351 - (NSString *) label;
1352 - (NSString *) origin;
1353 - (NSString *) version;
1355 - (NSString *) defaultIcon;
1359 @implementation Source
1363 distribution_.clear();
1368 description_.clear();
1374 defaultIcon_.clear();
1381 + (NSString *) webScriptNameForSelector:(SEL)selector {
1383 else if (selector == @selector(addSection:))
1384 return @"addSection";
1385 else if (selector == @selector(removeSection:))
1386 return @"removeSection";
1387 else if (selector == @selector(remove))
1393 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1394 return [self webScriptNameForSelector:selector] == nil;
1397 + (NSArray *) _attributeKeys {
1398 return [NSArray arrayWithObjects:
1406 @"shortDescription",
1414 - (NSArray *) attributeKeys {
1415 return [[self class] _attributeKeys];
1418 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1419 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1422 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1425 trusted_ = index->IsTrusted();
1427 uri_.set(pool, index->GetURI());
1428 distribution_.set(pool, index->GetDist());
1429 type_.set(pool, index->GetType());
1431 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1432 if (dindex != NULL) {
1433 base_.set(pool, dindex->MetaIndexURI(""));
1436 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1439 pkgTagFile tags(&fd);
1441 pkgTagSection section;
1448 {"default-icon", &defaultIcon_},
1449 {"depiction", &depiction_},
1450 {"description", &description_},
1452 {"origin", &origin_},
1453 {"support", &support_},
1454 {"version", &version_},
1457 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1458 const char *start, *end;
1460 if (section.Find(names[i].name_, start, end)) {
1461 CYString &value(*names[i].value_);
1462 value.set(pool, start, end - start);
1468 record_ = [Sources_ objectForKey:[self key]];
1470 NSURL *url([NSURL URLWithString:uri_]);
1474 host_ = [host_ lowercaseString];
1479 authority_ = [url path];
1482 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1483 if ((self = [super init]) != nil) {
1484 [self setMetaIndex:index inPool:pool];
1488 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1489 NSDictionary *lhr = [self record];
1490 NSDictionary *rhr = [source record];
1493 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1495 NSString *lhs = [self name];
1496 NSString *rhs = [source name];
1498 if ([lhs length] != 0 && [rhs length] != 0) {
1499 unichar lhc = [lhs characterAtIndex:0];
1500 unichar rhc = [rhs characterAtIndex:0];
1502 if (isalpha(lhc) && !isalpha(rhc))
1503 return NSOrderedAscending;
1504 else if (!isalpha(lhc) && isalpha(rhc))
1505 return NSOrderedDescending;
1508 return [lhs compare:rhs options:LaxCompareOptions_];
1511 - (NSString *) depictionForPackage:(NSString *)package {
1512 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1515 - (NSString *) supportForPackage:(NSString *)package {
1516 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1519 - (NSArray *) sections {
1520 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1523 - (void) _addSection:(NSString *)section {
1526 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1527 if (![sections containsObject:section]) {
1528 [sections addObject:section];
1532 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1537 - (bool) addSection:(NSString *)section {
1541 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1545 - (void) _removeSection:(NSString *)section {
1549 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1550 if ([sections containsObject:section]) {
1551 [sections removeObject:section];
1556 - (bool) removeSection:(NSString *)section {
1560 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1565 [Sources_ removeObjectForKey:[self key]];
1570 bool value(record_ != nil);
1571 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1575 - (NSDictionary *) record {
1583 - (NSString *) uri {
1587 - (NSString *) distribution {
1588 return distribution_;
1591 - (NSString *) type {
1595 - (NSString *) base {
1599 - (NSString *) key {
1600 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1603 - (NSString *) host {
1607 - (NSString *) name {
1608 return origin_.empty() ? (id) authority_ : origin_;
1611 - (NSString *) shortDescription {
1612 return description_;
1615 - (NSString *) label {
1616 return label_.empty() ? (id) authority_ : label_;
1619 - (NSString *) origin {
1623 - (NSString *) version {
1627 - (NSString *) defaultIcon {
1628 return defaultIcon_;
1633 /* CydiaOperation Class {{{ */
1634 @interface CydiaOperation : NSObject {
1635 _H<NSString> operator_;
1636 _H<NSString> value_;
1639 - (NSString *) operator;
1640 - (NSString *) value;
1644 @implementation CydiaOperation
1646 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1647 if ((self = [super init]) != nil) {
1648 operator_ = [NSString stringWithUTF8String:_operator];
1649 value_ = [NSString stringWithUTF8String:value];
1653 + (NSArray *) _attributeKeys {
1654 return [NSArray arrayWithObjects:
1660 - (NSArray *) attributeKeys {
1661 return [[self class] _attributeKeys];
1664 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1665 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1668 - (NSString *) operator {
1672 - (NSString *) value {
1678 /* CydiaClause Class {{{ */
1679 @interface CydiaClause : NSObject {
1680 _H<NSString> package_;
1681 _H<CydiaOperation> version_;
1684 - (NSString *) package;
1685 - (CydiaOperation *) version;
1689 @implementation CydiaClause
1691 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1692 if ((self = [super init]) != nil) {
1693 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1695 if (const char *version = dep.TargetVer())
1696 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1698 version_ = (id) [NSNull null];
1702 + (NSArray *) _attributeKeys {
1703 return [NSArray arrayWithObjects:
1709 - (NSArray *) attributeKeys {
1710 return [[self class] _attributeKeys];
1713 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1714 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1717 - (NSString *) package {
1721 - (CydiaOperation *) version {
1727 /* CydiaRelation Class {{{ */
1728 @interface CydiaRelation : NSObject {
1729 _H<NSString> relationship_;
1730 _H<NSMutableArray> clauses_;
1733 - (NSString *) relationship;
1734 - (NSArray *) clauses;
1738 @implementation CydiaRelation
1740 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1741 if ((self = [super init]) != nil) {
1742 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1743 clauses_ = [NSMutableArray arrayWithCapacity:8];
1745 pkgCache::DepIterator start;
1746 pkgCache::DepIterator end;
1747 dep.GlobOr(start, end); // ++dep
1750 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1752 // yes, seriously. (wtf?)
1760 + (NSArray *) _attributeKeys {
1761 return [NSArray arrayWithObjects:
1767 - (NSArray *) attributeKeys {
1768 return [[self class] _attributeKeys];
1771 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1772 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1775 - (NSString *) relationship {
1776 return relationship_;
1779 - (NSArray *) clauses {
1783 - (void) addClause:(CydiaClause *)clause {
1784 [clauses_ addObject:clause];
1789 /* Package Class {{{ */
1790 struct ParsedPackage {
1795 CYString depiction_;
1805 @interface Package : NSObject {
1808 uint32_t essential_ : 1;
1809 uint32_t obsolete_ : 1;
1810 uint32_t ignored_ : 1;
1816 _transient Database *database_;
1818 pkgCache::VerIterator version_;
1819 pkgCache::PkgIterator iterator_;
1820 pkgCache::VerFileIterator file_;
1826 CYString installed_;
1828 const char *section_;
1829 _transient NSString *section$_;
1833 PackageValue *metadata_;
1834 ParsedPackage *parsed_;
1836 _H<NSMutableArray> tags_;
1839 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1840 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1842 - (pkgCache::PkgIterator) iterator;
1845 - (NSString *) section;
1846 - (NSString *) simpleSection;
1848 - (NSString *) longSection;
1849 - (NSString *) shortSection;
1853 - (MIMEAddress *) maintainer;
1855 - (NSString *) longDescription;
1856 - (NSString *) shortDescription;
1859 - (PackageValue *) metadata;
1862 - (bool) subscribed;
1863 - (bool) setSubscribed:(bool)subscribed;
1867 - (NSString *) latest;
1868 - (NSString *) installed;
1869 - (BOOL) uninstalled;
1872 - (BOOL) upgradableAndEssential:(BOOL)essential;
1875 - (BOOL) unfiltered;
1879 - (BOOL) halfConfigured;
1880 - (BOOL) halfInstalled;
1882 - (NSString *) mode;
1885 - (NSString *) name;
1887 - (NSString *) homepage;
1888 - (NSString *) depiction;
1889 - (MIMEAddress *) author;
1891 - (NSString *) support;
1893 - (NSArray *) files;
1894 - (NSArray *) warnings;
1895 - (NSArray *) applications;
1897 - (Source *) source;
1900 - (BOOL) matches:(NSArray *)query;
1902 - (bool) hasSupportingRole;
1903 - (BOOL) hasTag:(NSString *)tag;
1904 - (NSString *) primaryPurpose;
1905 - (NSArray *) purposes;
1906 - (bool) isCommercial;
1908 - (void) setIndex:(size_t)index;
1910 - (CYString &) cyname;
1912 - (uint32_t) compareBySection:(NSArray *)sections;
1917 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query;
1918 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1919 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1920 - (bool) isVisibleInSection:(NSString *)section;
1921 - (bool) isVisibleInSource:(Source *)source;
1925 uint32_t PackageChangesRadix(Package *self, void *) {
1930 uint32_t timestamp : 30;
1931 uint32_t ignored : 1;
1932 uint32_t upgradable : 1;
1936 bool upgradable([self upgradableAndEssential:YES]);
1937 value.bits.upgradable = upgradable ? 1 : 0;
1940 value.bits.timestamp = 0;
1941 value.bits.ignored = [self ignored] ? 0 : 1;
1942 value.bits.upgradable = 1;
1944 value.bits.timestamp = [self seen] >> 2;
1945 value.bits.ignored = 0;
1946 value.bits.upgradable = 0;
1949 return _not(uint32_t) - value.key;
1952 uint32_t PackagePrefixRadix(Package *self, void *context) {
1953 size_t offset(reinterpret_cast<size_t>(context));
1954 CYString &name([self cyname]);
1956 size_t size(name.size());
1959 char *text(name.data());
1962 if (!isdigit(text[0]))
1966 while (size != digits && isdigit(text[digits]))
1974 if (offset == 0 && zeros != 0) {
1975 memset(data, '0', zeros);
1976 memcpy(data + zeros, text, 4 - zeros);
1978 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1979 if (size <= offset - zeros)
1982 text += offset - zeros;
1983 size -= offset - zeros;
1986 memcpy(data, text, 4);
1988 memcpy(data, text, size);
1989 memset(data + size, 0, 4 - size);
1992 for (size_t i(0); i != 4; ++i)
1993 if (isalpha(data[i]))
2001 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2003 /* XXX: ntohl may be more honest */
2004 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2007 CYString &(*PackageName)(Package *self, SEL sel);
2009 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2010 _profile(PackageNameCompare)
2011 CYString &lhi(PackageName(lhs, @selector(cyname)));
2012 CYString &rhi(PackageName(rhs, @selector(cyname)));
2013 CFStringRef lhn(lhi), rhn(rhi);
2016 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2017 else if (rhn == NULL)
2018 return NSOrderedDescending;
2020 _profile(PackageNameCompare$NumbersLast)
2021 if (!lhi.empty() && !rhi.empty()) {
2022 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2023 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2024 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2025 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2026 return lha ? NSOrderedAscending : NSOrderedDescending;
2030 CFIndex length = CFStringGetLength(lhn);
2032 _profile(PackageNameCompare$Compare)
2033 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2038 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2039 return PackageNameCompare(*lhs, *rhs, context);
2042 struct PackageNameOrdering :
2043 std::binary_function<Package *, Package *, bool>
2045 _finline bool operator ()(Package *lhs, Package *rhs) const {
2046 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2050 @implementation Package
2052 - (NSString *) description {
2053 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2057 if (parsed_ != NULL)
2062 + (NSString *) webScriptNameForSelector:(SEL)selector {
2064 else if (selector == @selector(clear))
2066 else if (selector == @selector(getField:))
2068 else if (selector == @selector(hasTag:))
2070 else if (selector == @selector(install))
2072 else if (selector == @selector(remove))
2078 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2079 return [self webScriptNameForSelector:selector] == nil;
2082 + (NSArray *) _attributeKeys {
2083 return [NSArray arrayWithObjects:
2102 @"shortDescription",
2115 - (NSArray *) attributeKeys {
2116 return [[self class] _attributeKeys];
2119 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2120 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2123 - (NSArray *) relations {
2124 @synchronized (database_) {
2125 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2126 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2127 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2131 - (NSString *) getField:(NSString *)name {
2132 @synchronized (database_) {
2133 if ([database_ era] != era_ || file_.end())
2136 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2138 const char *start, *end;
2139 if (!parser.Find([name UTF8String], start, end))
2140 return (NSString *) [NSNull null];
2142 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2146 if (parsed_ != NULL)
2148 @synchronized (database_) {
2149 if ([database_ era] != era_ || file_.end())
2152 ParsedPackage *parsed(new ParsedPackage);
2155 _profile(Package$parse)
2156 pkgRecords::Parser *parser;
2158 _profile(Package$parse$Lookup)
2159 parser = &[database_ records]->Lookup(file_);
2164 _profile(Package$parse$Find)
2169 {"icon", &parsed->icon_},
2170 {"depiction", &parsed->depiction_},
2171 {"homepage", &parsed->homepage_},
2172 {"website", &website},
2173 {"bugs", &parsed->bugs_},
2174 {"support", &parsed->support_},
2175 {"sponsor", &parsed->sponsor_},
2176 {"author", &parsed->author_},
2179 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2180 const char *start, *end;
2182 if (parser->Find(names[i].name_, start, end)) {
2183 CYString &value(*names[i].value_);
2184 _profile(Package$parse$Value)
2185 value.set(pool_, start, end - start);
2191 _profile(Package$parse$Tagline)
2192 const char *start, *end;
2193 if (parser->ShortDesc(start, end)) {
2194 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2197 while (stop != start && stop[-1] == '\r')
2199 parsed->tagline_.set(pool_, start, stop - start);
2203 _profile(Package$parse$Retain)
2204 if (parsed->homepage_.empty())
2205 parsed->homepage_ = website;
2206 if (parsed->homepage_ == parsed->depiction_)
2207 parsed->homepage_.clear();
2212 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2213 if ((self = [super init]) != nil) {
2214 _profile(Package$initWithVersion)
2217 database_ = database;
2218 era_ = [database era];
2222 pkgCache::PkgIterator iterator(version.ParentPkg());
2223 iterator_ = iterator;
2225 _profile(Package$initWithVersion$Version)
2226 if (!version_.end())
2227 file_ = version_.FileList();
2229 pkgCache &cache([database_ cache]);
2230 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2234 _profile(Package$initWithVersion$Cache)
2235 name_.set(NULL, iterator.Display());
2237 latest_.set(NULL, StripVersion_(version_.VerStr()));
2239 pkgCache::VerIterator current(iterator.CurrentVer());
2241 installed_.set(NULL, StripVersion_(current.VerStr()));
2244 _profile(Package$initWithVersion$Tags)
2245 pkgCache::TagIterator tag(iterator.TagList());
2247 tags_ = [NSMutableArray arrayWithCapacity:8];
2249 const char *name(tag.Name());
2250 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2252 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2253 if (strcmp(name + 6, "enduser") == 0)
2255 else if (strcmp(name + 6, "hacker") == 0)
2257 else if (strcmp(name + 6, "developer") == 0)
2259 else if (strcmp(name + 6, "cydia") == 0)
2265 if (strncmp(name, "cydia::", 7) == 0) {
2266 if (strcmp(name + 7, "essential") == 0)
2268 else if (strcmp(name + 7, "obsolete") == 0)
2273 } while (!tag.end());
2277 _profile(Package$initWithVersion$Metadata)
2278 const char *mixed(iterator.Name());
2279 size_t size(strlen(mixed));
2280 char lower[size + 1];
2282 for (size_t i(0); i != size; ++i)
2283 lower[i] = mixed[i] | 0x20;
2286 PackageValue *metadata(PackageFind(lower, size));
2287 metadata_ = metadata;
2289 id_.set(NULL, metadata->name_, size);
2291 const char *latest(version_.VerStr());
2292 size_t length(strlen(latest));
2294 uint16_t vhash(hashlittle(latest, length));
2296 size_t capped(std::min<size_t>(8, length));
2297 latest = latest + length - capped;
2299 if (metadata->first_ == 0)
2300 metadata->first_ = now_;
2302 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2303 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2304 metadata->vhash_ = vhash;
2305 metadata->last_ = now_;
2306 } else if (metadata->last_ == 0)
2307 metadata->last_ = metadata->first_;
2310 _profile(Package$initWithVersion$Section)
2311 section_ = iterator.Section();
2314 _profile(Package$initWithVersion$Flags)
2315 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2316 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2321 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2322 pkgCache::VerIterator version;
2324 _profile(Package$packageWithIterator$GetCandidateVer)
2325 version = [database policy]->GetCandidateVer(iterator);
2333 _profile(Package$packageWithIterator$Allocate)
2334 package = [Package allocWithZone:zone];
2337 _profile(Package$packageWithIterator$Initialize)
2339 initWithVersion:version
2346 _profile(Package$packageWithIterator$Autorelease)
2347 package = [package autorelease];
2353 - (pkgCache::PkgIterator) iterator {
2357 - (NSString *) section {
2358 if (section$_ == nil) {
2359 if (section_ == NULL)
2362 _profile(Package$section$mappedSectionForPointer)
2363 section$_ = [database_ mappedSectionForPointer:section_];
2368 - (NSString *) simpleSection {
2369 if (NSString *section = [self section])
2370 return Simplify(section);
2375 - (NSString *) longSection {
2376 return LocalizeSection([self section]);
2379 - (NSString *) shortSection {
2380 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2383 - (NSString *) uri {
2386 pkgIndexFile *index;
2387 pkgCache::PkgFileIterator file(file_.File());
2388 if (![database_ list].FindIndex(file, index))
2390 return [NSString stringWithUTF8String:iterator_->Path];
2391 //return [NSString stringWithUTF8String:file.Site()];
2392 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2396 - (MIMEAddress *) maintainer {
2397 @synchronized (database_) {
2398 if ([database_ era] != era_ || file_.end())
2401 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2402 const std::string &maintainer(parser->Maintainer());
2403 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2407 @synchronized (database_) {
2408 if ([database_ era] != era_ || version_.end())
2411 return version_->InstalledSize;
2414 - (NSString *) longDescription {
2415 @synchronized (database_) {
2416 if ([database_ era] != era_ || file_.end())
2419 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2420 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2422 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2423 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2424 if ([lines count] < 2)
2427 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2428 for (size_t i(1), e([lines count]); i != e; ++i) {
2429 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2430 [trimmed addObject:trim];
2433 return [trimmed componentsJoinedByString:@"\n"];
2436 - (NSString *) shortDescription {
2437 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2441 _profile(Package$index)
2442 CFStringRef name((CFStringRef) [self name]);
2443 if (CFStringGetLength(name) == 0)
2445 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2446 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2448 return toupper(character);
2452 - (PackageValue *) metadata {
2457 PackageValue *metadata([self metadata]);
2458 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2461 - (bool) subscribed {
2462 return [self metadata]->subscribed_;
2465 - (bool) setSubscribed:(bool)subscribed {
2466 PackageValue *metadata([self metadata]);
2467 if (metadata->subscribed_ == subscribed)
2469 metadata->subscribed_ = subscribed;
2477 - (NSString *) latest {
2481 - (NSString *) installed {
2485 - (BOOL) uninstalled {
2486 return installed_.empty();
2490 return !version_.end();
2493 - (BOOL) upgradableAndEssential:(BOOL)essential {
2494 _profile(Package$upgradableAndEssential)
2495 pkgCache::VerIterator current(iterator_.CurrentVer());
2497 return essential && essential_;
2499 return !version_.end() && version_ != current;
2503 - (BOOL) essential {
2508 return [database_ cache][iterator_].InstBroken();
2511 - (BOOL) unfiltered {
2512 _profile(Package$unfiltered$obsolete)
2513 if (_unlikely(obsolete_))
2517 _profile(Package$unfiltered$hasSupportingRole)
2518 if (_unlikely(![self hasSupportingRole]))
2526 if (![self unfiltered])
2531 _profile(Package$visible$section)
2532 section = [self section];
2535 _profile(Package$visible$isSectionVisible)
2536 if (!isSectionVisible(section))
2544 unsigned char current(iterator_->CurrentState);
2545 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2548 - (BOOL) halfConfigured {
2549 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2552 - (BOOL) halfInstalled {
2553 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2557 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2558 return state.Mode != pkgDepCache::ModeKeep;
2561 - (NSString *) mode {
2562 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2564 switch (state.Mode) {
2565 case pkgDepCache::ModeDelete:
2566 if ((state.iFlags & pkgDepCache::Purge) != 0)
2570 case pkgDepCache::ModeKeep:
2571 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2572 return @"REINSTALL";
2573 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2577 case pkgDepCache::ModeInstall:
2578 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2579 return @"REINSTALL";
2580 else*/ switch (state.Status) {
2582 return @"DOWNGRADE";
2588 return @"NEW_INSTALL";
2599 - (NSString *) name {
2600 return name_.empty() ? id_ : name_;
2603 - (UIImage *) icon {
2604 NSString *section = [self simpleSection];
2607 if (parsed_ != NULL)
2608 if (NSString *href = parsed_->icon_)
2609 if ([href hasPrefix:@"file:///"])
2610 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2611 if (icon == nil) if (section != nil)
2612 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2613 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2614 if ([dicon hasPrefix:@"file:///"])
2615 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2617 icon = [UIImage applicationImageNamed:@"unknown.png"];
2621 - (NSString *) homepage {
2622 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2625 - (NSString *) depiction {
2626 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2629 - (MIMEAddress *) sponsor {
2630 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [MIMEAddress addressWithString:parsed_->sponsor_];
2633 - (MIMEAddress *) author {
2634 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2637 - (NSString *) support {
2638 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2641 - (NSArray *) files {
2642 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2643 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2646 fin.open([path UTF8String]);
2651 while (std::getline(fin, line))
2652 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2657 - (NSString *) state {
2658 @synchronized (database_) {
2659 if ([database_ era] != era_ || file_.end())
2662 switch (iterator_->CurrentState) {
2663 case pkgCache::State::NotInstalled:
2664 return @"NotInstalled";
2665 case pkgCache::State::UnPacked:
2667 case pkgCache::State::HalfConfigured:
2668 return @"HalfConfigured";
2669 case pkgCache::State::HalfInstalled:
2670 return @"HalfInstalled";
2671 case pkgCache::State::ConfigFiles:
2672 return @"ConfigFiles";
2673 case pkgCache::State::Installed:
2674 return @"Installed";
2675 case pkgCache::State::TriggersAwaited:
2676 return @"TriggersAwaited";
2677 case pkgCache::State::TriggersPending:
2678 return @"TriggersPending";
2681 return (NSString *) [NSNull null];
2684 - (NSString *) selection {
2685 @synchronized (database_) {
2686 if ([database_ era] != era_ || file_.end())
2689 switch (iterator_->SelectedState) {
2690 case pkgCache::State::Unknown:
2692 case pkgCache::State::Install:
2694 case pkgCache::State::Hold:
2696 case pkgCache::State::DeInstall:
2697 return @"DeInstall";
2698 case pkgCache::State::Purge:
2702 return (NSString *) [NSNull null];
2705 - (NSArray *) warnings {
2706 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2707 const char *name(iterator_.Name());
2709 size_t length(strlen(name));
2710 if (length < 2) invalid:
2711 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2712 else for (size_t i(0); i != length; ++i)
2714 /* XXX: technically this is not allowed */
2715 (name[i] < 'A' || name[i] > 'Z') &&
2716 (name[i] < 'a' || name[i] > 'z') &&
2717 (name[i] < '0' || name[i] > '9') &&
2718 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2721 if (strcmp(name, "cydia") != 0) {
2724 bool _private = false;
2727 bool repository = [[self section] isEqualToString:@"Repositories"];
2729 if (NSArray *files = [self files])
2730 for (NSString *file in files)
2731 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2733 else if (!user && [file isEqualToString:@"/User"])
2735 else if (!_private && [file isEqualToString:@"/private"])
2737 else if (!stash && [file isEqualToString:@"/var/stash"])
2740 /* XXX: this is not sensitive enough. only some folders are valid. */
2741 if (cydia && !repository)
2742 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2744 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2746 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2748 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2751 return [warnings count] == 0 ? nil : warnings;
2754 - (NSArray *) applications {
2755 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2757 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2759 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2760 if (NSArray *files = [self files])
2761 for (NSString *file in files)
2762 if (application_r(file)) {
2763 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2764 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2765 if ([id isEqualToString:me])
2768 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2770 display = application_r[1];
2772 NSString *bundle([file stringByDeletingLastPathComponent]);
2773 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2774 if (icon == nil || [icon length] == 0)
2776 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2778 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2779 [applications addObject:application];
2781 [application addObject:id];
2782 [application addObject:display];
2783 [application addObject:url];
2786 return [applications count] == 0 ? nil : applications;
2789 - (Source *) source {
2790 if (source_ == nil) {
2791 @synchronized (database_) {
2792 if ([database_ era] != era_ || file_.end())
2793 source_ = (Source *) [NSNull null];
2795 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
2799 return source_ == (Source *) [NSNull null] ? nil : source_;
2806 - (BOOL) matches:(NSArray *)query {
2807 if (query == nil || [query count] == 0)
2818 string = [self name];
2819 length = [string length];
2821 for (NSString *term in query) {
2822 range = [string rangeOfString:term options:MatchCompareOptions_];
2823 if (range.location != NSNotFound)
2824 rank_ -= 6 * 1000000 / length;
2829 length = [string length];
2831 for (NSString *term in query) {
2832 range = [string rangeOfString:term options:MatchCompareOptions_];
2833 if (range.location != NSNotFound)
2834 rank_ -= 6 * 1000000 / length;
2838 string = [self shortDescription];
2839 length = [string length];
2840 NSUInteger stop(std::min<NSUInteger>(length, 100));
2842 for (NSString *term in query) {
2843 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
2844 if (range.location != NSNotFound)
2845 rank_ -= 2 * 100000;
2851 - (bool) hasSupportingRole {
2856 if ([Role_ isEqualToString:@"User"])
2860 if ([Role_ isEqualToString:@"Hacker"])
2864 if ([Role_ isEqualToString:@"Developer"])
2869 - (NSArray *) tags {
2873 - (BOOL) hasTag:(NSString *)tag {
2874 return tags_ == nil ? NO : [tags_ containsObject:tag];
2877 - (NSString *) primaryPurpose {
2878 for (NSString *tag in (NSArray *) tags_)
2879 if ([tag hasPrefix:@"purpose::"])
2880 return [tag substringFromIndex:9];
2884 - (NSArray *) purposes {
2885 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2886 for (NSString *tag in (NSArray *) tags_)
2887 if ([tag hasPrefix:@"purpose::"])
2888 [purposes addObject:[tag substringFromIndex:9]];
2889 return [purposes count] == 0 ? nil : purposes;
2892 - (bool) isCommercial {
2893 return [self hasTag:@"cydia::commercial"];
2896 - (void) setIndex:(size_t)index {
2897 if (metadata_->index_ != index)
2898 metadata_->index_ = index;
2901 - (CYString &) cyname {
2902 return name_.empty() ? id_ : name_;
2905 - (uint32_t) compareBySection:(NSArray *)sections {
2906 NSString *section([self section]);
2907 for (size_t i(0), e([sections count]); i != e; ++i) {
2908 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2912 return _not(uint32_t);
2916 @synchronized (database_) {
2917 pkgProblemResolver *resolver = [database_ resolver];
2918 resolver->Clear(iterator_);
2920 pkgCacheFile &cache([database_ cache]);
2921 cache->SetReInstall(iterator_, false);
2922 cache->MarkKeep(iterator_, false);
2926 @synchronized (database_) {
2927 pkgProblemResolver *resolver = [database_ resolver];
2928 resolver->Clear(iterator_);
2929 resolver->Protect(iterator_);
2931 pkgCacheFile &cache([database_ cache]);
2932 cache->SetReInstall(iterator_, false);
2933 cache->MarkInstall(iterator_, false);
2935 pkgDepCache::StateCache &state((*cache)[iterator_]);
2936 if (!state.Install())
2937 cache->SetReInstall(iterator_, true);
2941 @synchronized (database_) {
2942 pkgProblemResolver *resolver = [database_ resolver];
2943 resolver->Clear(iterator_);
2944 resolver->Remove(iterator_);
2945 resolver->Protect(iterator_);
2947 pkgCacheFile &cache([database_ cache]);
2948 cache->SetReInstall(iterator_, false);
2949 cache->MarkDelete(iterator_, true);
2952 - (bool) isUnfilteredAndSearchedForBy:(NSArray *)query {
2953 _profile(Package$isUnfilteredAndSearchedForBy)
2956 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2957 value &= [self unfiltered];
2960 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2961 value &= [self matches:query];
2968 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2969 if ([search length] == 0)
2972 _profile(Package$isUnfilteredAndSelectedForBy)
2975 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2976 value &= [self unfiltered];
2979 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2980 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2987 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2988 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2991 - (bool) isVisibleInSection:(NSString *)name {
2992 NSString *section([self section]);
2996 section == nil && [name length] == 0 ||
2997 [name isEqualToString:section]
2998 ) && [self visible];
3001 - (bool) isVisibleInSource:(Source *)source {
3002 return [self source] == source && [self visible];
3007 /* Section Class {{{ */
3008 @interface Section : NSObject {
3013 _H<NSString> localized_;
3016 - (NSComparisonResult) compareByLocalized:(Section *)section;
3017 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3018 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3019 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3020 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3021 - (NSString *) name;
3028 - (void) addToCount;
3030 - (void) setCount:(size_t)count;
3031 - (NSString *) localized;
3035 @implementation Section
3037 - (NSComparisonResult) compareByLocalized:(Section *)section {
3038 NSString *lhs(localized_);
3039 NSString *rhs([section localized]);
3041 /*if ([lhs length] != 0 && [rhs length] != 0) {
3042 unichar lhc = [lhs characterAtIndex:0];
3043 unichar rhc = [rhs characterAtIndex:0];
3045 if (isalpha(lhc) && !isalpha(rhc))
3046 return NSOrderedAscending;
3047 else if (!isalpha(lhc) && isalpha(rhc))
3048 return NSOrderedDescending;
3051 return [lhs compare:rhs options:LaxCompareOptions_];
3054 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3055 if ((self = [self initWithName:name localize:NO]) != nil) {
3056 if (localized != nil)
3057 localized_ = localized;
3061 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3062 return [self initWithName:name row:0 localize:localize];
3065 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3066 if ((self = [super init]) != nil) {
3071 localized_ = LocalizeSection(name_);
3075 /* XXX: localize the index thingees */
3076 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3077 if ((self = [super init]) != nil) {
3078 name_ = [NSString stringWithCharacters:&index length:1];
3084 - (NSString *) name {
3104 - (void) addToCount {
3108 - (void) setCount:(size_t)count {
3112 - (NSString *) localized {
3119 static NSString *Colon_;
3121 static NSString *Error_;
3122 static NSString *Warning_;
3124 class CydiaLogCleaner :
3125 public pkgArchiveCleaner
3128 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3133 /* Database Implementation {{{ */
3134 @implementation Database
3136 + (Database *) sharedInstance {
3137 static _H<Database> instance;
3138 if (instance == nil)
3139 instance = [[[Database alloc] init] autorelease];
3147 - (void) releasePackages {
3148 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3149 CFArrayRemoveAllValues(packages_);
3153 // XXX: actually implement this thing
3155 [self releasePackages];
3156 apr_pool_destroy(pool_);
3157 NSRecycleZone(zone_);
3161 - (void) _readCydia:(NSNumber *)fd {
3162 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3163 std::istream is(&ib);
3166 static Pcre finish_r("^finish:([^:]*)$");
3168 while (std::getline(is, line)) {
3169 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3171 const char *data(line.c_str());
3172 size_t size = line.size();
3173 lprintf("C:%s\n", data);
3175 if (finish_r(data, size)) {
3176 NSString *finish = finish_r[1];
3177 int index = [Finishes_ indexOfObject:finish];
3178 if (index != INT_MAX && index > Finish_)
3188 - (void) _readStatus:(NSNumber *)fd {
3189 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3190 std::istream is(&ib);
3193 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3194 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3196 while (std::getline(is, line)) {
3197 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3199 const char *data(line.c_str());
3200 size_t size(line.size());
3201 lprintf("S:%s\n", data);
3203 if (conffile_r(data, size)) {
3204 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3205 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3206 } else if (strncmp(data, "status: ", 8) == 0) {
3207 // status: <package>: {unpacked,half-configured,installed}
3208 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3209 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3210 } else if (strncmp(data, "processing: ", 12) == 0) {
3211 // processing: configure: config-test
3212 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3213 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3214 } else if (pmstatus_r(data, size)) {
3215 std::string type([pmstatus_r[1] UTF8String]);
3217 NSString *package = pmstatus_r[2];
3218 if ([package isEqualToString:@"dpkg-exec"])
3221 float percent([pmstatus_r[3] floatValue]);
3222 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3224 NSString *string = pmstatus_r[4];
3226 if (type == "pmerror") {
3227 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3228 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3229 } else if (type == "pmstatus") {
3230 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3231 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3232 } else if (type == "pmconffile")
3233 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3235 lprintf("E:unknown pmstatus\n");
3237 lprintf("E:unknown status\n");
3245 - (void) _readOutput:(NSNumber *)fd {
3246 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3247 std::istream is(&ib);
3250 while (std::getline(is, line)) {
3251 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3253 lprintf("O:%s\n", line.c_str());
3255 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3256 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3268 - (Package *) packageWithName:(NSString *)name {
3269 @synchronized (self) {
3270 if (static_cast<pkgDepCache *>(cache_) == NULL)
3272 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3273 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3277 if ((self = [super init]) != nil) {
3284 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3285 apr_pool_create(&pool_, NULL);
3287 size_t capacity(MetaFile_->active_);
3293 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3294 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3298 _assert(pipe(fds) != -1);
3301 _config->Set("APT::Keep-Fds::", cydiafd_);
3302 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3305 detachNewThreadSelector:@selector(_readCydia:)
3307 withObject:[NSNumber numberWithInt:fds[0]]
3310 _assert(pipe(fds) != -1);
3314 detachNewThreadSelector:@selector(_readStatus:)
3316 withObject:[NSNumber numberWithInt:fds[0]]
3319 _assert(pipe(fds) != -1);
3320 _assert(dup2(fds[0], 0) != -1);
3321 _assert(close(fds[0]) != -1);
3323 input_ = fdopen(fds[1], "a");
3325 _assert(pipe(fds) != -1);
3326 _assert(dup2(fds[1], 1) != -1);
3327 _assert(close(fds[1]) != -1);
3330 detachNewThreadSelector:@selector(_readOutput:)
3332 withObject:[NSNumber numberWithInt:fds[0]]
3337 - (pkgCacheFile &) cache {
3341 - (pkgDepCache::Policy *) policy {
3345 - (pkgRecords *) records {
3349 - (pkgProblemResolver *) resolver {
3353 - (pkgAcquire &) fetcher {
3357 - (pkgSourceList &) list {
3361 - (NSArray *) packages {
3362 return (NSArray *) packages_;
3365 - (NSArray *) sources {
3369 - (Source *) sourceWithKey:(NSString *)key {
3370 for (Source *source in [self sources]) {
3371 if ([[source key] isEqualToString:key])
3376 - (bool) popErrorWithTitle:(NSString *)title {
3379 while (!_error->empty()) {
3381 bool warning(!_error->PopMessage(error));
3386 size_t size(error.size());
3387 if (size == 0 || error[size - 1] != '\n')
3389 error.resize(size - 1);
3392 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3394 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3400 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3401 return [self popErrorWithTitle:title] || !success;
3404 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3405 @synchronized (self) {
3408 [self releasePackages];
3411 [sourceList_ removeAllObjects];
3431 apr_pool_clear(pool_);
3433 NSRecycleZone(zone_);
3434 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3436 int chk(creat("/tmp/cydia.chk", 0644));
3440 if (invocation != nil)
3441 [invocation invoke];
3443 NSString *title(UCLocalize("DATABASE"));
3446 OpProgress progress;
3447 while (!cache_.Open(progress, true)) { pop:
3449 bool warning(!_error->PopMessage(error));
3450 lprintf("cache_.Open():[%s]\n", error.c_str());
3452 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3453 [delegate_ repairWithSelector:@selector(configure)];
3454 else if (error == "The package lists or status file could not be parsed or opened.")
3455 [delegate_ repairWithSelector:@selector(update)];
3456 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3457 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3458 // else if (error == "Malformed Status line")
3459 // else if (error == "The list of sources could not be read.")
3461 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3471 unlink("/tmp/cydia.chk");
3473 now_ = [[NSDate date] timeIntervalSince1970];
3475 policy_ = new pkgDepCache::Policy();
3476 records_ = new pkgRecords(cache_);
3477 resolver_ = new pkgProblemResolver(cache_);
3478 fetcher_ = new pkgAcquire(&status_);
3481 list_ = new pkgSourceList();
3482 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3485 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3486 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3490 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3493 if (cache_->BrokenCount() != 0) {
3494 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3497 if (cache_->BrokenCount() != 0) {
3498 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3502 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3506 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3507 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3508 [sourceList_ addObject:object];
3510 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3511 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3512 // XXX: this could be more intelligent
3513 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3514 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3516 sourceMap_[cached->ID] = object;
3521 /*std::vector<Package *> packages;
3522 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3527 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3528 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3529 //packages.push_back(package);
3530 CFArrayAppendValue(packages_, CFRetain(package));
3534 /*if (packages.empty())
3535 packages_ = [[NSArray alloc] init];
3537 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3540 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3541 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3542 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3550 /*if (!packages.empty())
3551 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3552 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3554 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3556 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3558 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3562 size_t count(CFArrayGetCount(packages_));
3563 MetaFile_->active_ = count;
3565 for (size_t index(0); index != count; ++index)
3566 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3573 @synchronized (self) {
3575 resolver_ = new pkgProblemResolver(cache_);
3577 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3578 if (!cache_[iterator].Keep())
3579 cache_->MarkKeep(iterator, false);
3580 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3581 cache_->SetReInstall(iterator, false);
3584 - (void) configure {
3585 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3587 system([dpkg UTF8String]);
3592 // XXX: I don't remember this condition
3597 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3599 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3601 if ([self popErrorWithTitle:title])
3605 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3607 CydiaLogCleaner cleaner;
3608 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3615 fetcher_->Shutdown();
3617 pkgRecords records(cache_);
3619 lock_ = new FileFd();
3620 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3622 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3624 if ([self popErrorWithTitle:title])
3628 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3631 manager_ = (_system->CreatePM(cache_));
3632 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3639 bool substrate(RestartSubstrate_);
3640 RestartSubstrate_ = false;
3642 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3644 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3646 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3648 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3649 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3652 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3654 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3656 [self popErrorWithTitle:title];
3660 bool failed = false;
3661 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3662 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3664 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3670 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3678 RestartSubstrate_ = true;
3681 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3683 if (_error->PendingError()) {
3688 if (result == pkgPackageManager::Failed) {
3693 if (result != pkgPackageManager::Completed) {
3698 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3700 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3702 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3703 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3706 if (![before isEqualToArray:after])
3711 NSString *title(UCLocalize("UPGRADE"));
3712 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3718 [self updateWithStatus:status_];
3721 - (void) updateWithStatus:(Status &)status {
3722 NSString *title(UCLocalize("REFRESHING_DATA"));
3725 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3729 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3730 if ([self popErrorWithTitle:title])
3733 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3735 bool success(ListUpdate(status, list, PulseInterval_));
3736 if (status.WasCancelled())
3739 [self popErrorWithTitle:title forOperation:success];
3740 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3744 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3747 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3748 delegate_ = delegate;
3751 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3752 progress_ = delegate;
3753 status_.setDelegate(delegate);
3756 - (NSObject<ProgressDelegate> *) progressDelegate {
3760 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3761 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3762 return i == sourceMap_.end() ? nil : i->second;
3765 - (NSString *) mappedSectionForPointer:(const char *)section {
3766 _H<NSString> *mapped;
3768 _profile(Database$mappedSectionForPointer$Cache)
3769 mapped = §ions_[section];
3772 if (*mapped == NULL) {
3773 size_t length(strlen(section));
3774 char spaced[length + 1];
3776 _profile(Database$mappedSectionForPointer$Replace)
3777 for (size_t index(0); index != length; ++index)
3778 spaced[index] = section[index] == '_' ? ' ' : section[index];
3779 spaced[length] = '\0';
3784 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3785 string = [NSString stringWithUTF8String:spaced];
3788 _profile(Database$mappedSectionForPointer$Map)
3789 string = [SectionMap_ objectForKey:string] ?: string;
3799 static _H<NSMutableSet> Diversions_;
3801 @interface Diversion : NSObject {
3804 _H<NSString> format_;
3809 @implementation Diversion
3811 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3812 if ((self = [super init]) != nil) {
3813 pattern_ = [from UTF8String];
3819 - (NSString *) divert:(NSString *)url {
3820 return !pattern_(url) ? nil : pattern_->*format_;
3823 + (NSURL *) divertURL:(NSURL *)url {
3825 NSString *href([url absoluteString]);
3827 for (Diversion *diversion in (id) Diversions_)
3828 if (NSString *diverted = [diversion divert:href]) {
3830 NSLog(@"div: %@", diverted);
3832 url = [NSURL URLWithString:diverted];
3839 - (NSString *) key {
3843 - (NSUInteger) hash {
3847 - (BOOL) isEqual:(Diversion *)object {
3848 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3853 @interface CydiaObject : NSObject {
3854 _H<IndirectDelegate> indirect_;
3855 _transient id delegate_;
3858 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3862 @interface CydiaWebViewController : CyteWebViewController {
3863 _H<CydiaObject> cydia_;
3866 + (void) addDiversion:(Diversion *)diversion;
3870 /* Web Scripting {{{ */
3871 @implementation CydiaObject
3873 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3874 if ((self = [super init]) != nil) {
3875 indirect_ = indirect;
3879 - (void) setDelegate:(id)delegate {
3880 delegate_ = delegate;
3883 + (NSArray *) _attributeKeys {
3884 return [NSArray arrayWithObjects:
3901 - (NSArray *) attributeKeys {
3902 return [[self class] _attributeKeys];
3905 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3906 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3909 - (NSString *) version {
3913 - (NSString *) device {
3914 return [[UIDevice currentDevice] uniqueIdentifier];
3917 - (NSString *) firmware {
3918 return [[UIDevice currentDevice] systemVersion];
3921 - (NSString *) hostname {
3922 return [[UIDevice currentDevice] name];
3925 - (NSString *) idiom {
3926 return (id) Idiom_ ?: [NSNull null];
3929 - (NSString *) plmn {
3930 return (id) PLMN_ ?: [NSNull null];
3933 - (NSString *) bbsnum {
3934 return (id) BBSNum_ ?: [NSNull null];
3937 - (NSString *) ecid {
3938 return (id) ChipID_ ?: [NSNull null];
3941 - (NSString *) serial {
3942 return SerialNumber_;
3945 - (NSString *) role {
3946 return (id) Role_ ?: [NSNull null];
3949 - (NSString *) model {
3950 return [NSString stringWithUTF8String:Machine_];
3953 - (NSString *) token {
3954 return (id) Token_ ?: [NSNull null];
3957 + (NSString *) webScriptNameForSelector:(SEL)selector {
3959 else if (selector == @selector(addBridgedHost:))
3960 return @"addBridgedHost";
3961 else if (selector == @selector(addInsecureHost:))
3962 return @"addInsecureHost";
3963 else if (selector == @selector(addInternalRedirect::))
3964 return @"addInternalRedirect";
3965 else if (selector == @selector(addPipelinedHost:scheme:))
3966 return @"addPipelinedHost";
3967 else if (selector == @selector(addSource:::))
3968 return @"addSource";
3969 else if (selector == @selector(addTokenHost:))
3970 return @"addTokenHost";
3971 else if (selector == @selector(addTrivialSource:))
3972 return @"addTrivialSource";
3973 else if (selector == @selector(close))
3975 else if (selector == @selector(du:))
3977 else if (selector == @selector(stringWithFormat:arguments:))
3979 else if (selector == @selector(getAllSources))
3980 return @"getAllSourcs";
3981 else if (selector == @selector(getKernelNumber:))
3982 return @"getKernelNumber";
3983 else if (selector == @selector(getKernelString:))
3984 return @"getKernelString";
3985 else if (selector == @selector(getInstalledPackages))
3986 return @"getInstalledPackages";
3987 else if (selector == @selector(getIORegistryEntry::))
3988 return @"getIORegistryEntry";
3989 else if (selector == @selector(getLocaleIdentifier))
3990 return @"getLocaleIdentifier";
3991 else if (selector == @selector(getPreferredLanguages))
3992 return @"getPreferredLanguages";
3993 else if (selector == @selector(getPackageById:))
3994 return @"getPackageById";
3995 else if (selector == @selector(getMetadataKeys))
3996 return @"getMetadataKeys";
3997 else if (selector == @selector(getMetadataValue:))
3998 return @"getMetadataValue";
3999 else if (selector == @selector(getSessionValue:))
4000 return @"getSessionValue";
4001 else if (selector == @selector(installPackages:))
4002 return @"installPackages";
4003 else if (selector == @selector(localizedStringForKey:value:table:))
4005 else if (selector == @selector(popViewController:))
4006 return @"popViewController";
4007 else if (selector == @selector(refreshSources))
4008 return @"refreshSources";
4009 else if (selector == @selector(removeButton))
4010 return @"removeButton";
4011 else if (selector == @selector(saveConfig))
4012 return @"saveConfig";
4013 else if (selector == @selector(setCydiaSource:))
4014 return @"setCydiaSource";
4015 else if (selector == @selector(setMetadataValue::))
4016 return @"setMetadataValue";
4017 else if (selector == @selector(setSessionValue::))
4018 return @"setSessionValue";
4019 else if (selector == @selector(substitutePackageNames:))
4020 return @"substitutePackageNames";
4021 else if (selector == @selector(scrollToBottom:))
4022 return @"scrollToBottom";
4023 else if (selector == @selector(setAllowsNavigationAction:))
4024 return @"setAllowsNavigationAction";
4025 else if (selector == @selector(setBadgeValue:))
4026 return @"setBadgeValue";
4027 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4028 return @"setButtonImage";
4029 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4030 return @"setButtonTitle";
4031 else if (selector == @selector(setHidesBackButton:))
4032 return @"setHidesBackButton";
4033 else if (selector == @selector(setHidesNavigationBar:))
4034 return @"setHidesNavigationBar";
4035 else if (selector == @selector(setNavigationBarStyle:))
4036 return @"setNavigationBarStyle";
4037 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4038 return @"setNavigationBarTintColor";
4039 else if (selector == @selector(setPasteboardString:))
4040 return @"setPasteboardString";
4041 else if (selector == @selector(setPasteboardURL:))
4042 return @"setPasteboardURL";
4043 else if (selector == @selector(setToken:))
4045 else if (selector == @selector(setViewportWidth:))
4046 return @"setViewportWidth";
4047 else if (selector == @selector(statfs:))
4049 else if (selector == @selector(supports:))
4051 else if (selector == @selector(unload))
4057 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4058 return [self webScriptNameForSelector:selector] == nil;
4061 - (BOOL) supports:(NSString *)feature {
4062 return [feature isEqualToString:@"window.open"];
4066 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4069 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4070 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4073 - (NSNumber *) getKernelNumber:(NSString *)name {
4074 const char *string([name UTF8String]);
4077 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4078 return (id) [NSNull null];
4080 if (size != sizeof(int))
4081 return (id) [NSNull null];
4084 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4085 return (id) [NSNull null];
4087 return [NSNumber numberWithInt:value];
4090 - (NSString *) getKernelString:(NSString *)name {
4091 const char *string([name UTF8String]);
4094 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4095 return (id) [NSNull null];
4097 char value[size + 1];
4098 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4099 return (id) [NSNull null];
4101 // XXX: just in case you request something ludicrous
4104 return [NSString stringWithCString:value];
4107 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4108 NSObject *value(CYIOGetValue([path UTF8String], entry));
4111 if ([value isKindOfClass:[NSData class]])
4112 value = CYHex((NSData *) value);
4117 - (void) _setCydiaSource:(NSString *)source {
4118 @synchronized (HostConfig_) {
4119 CydiaSource_ = source;
4120 [Metadata_ setObject:source forKey:@"CydiaSource"];
4126 - (void) setCydiaSource:(NSString *)source {
4127 [self performSelectorOnMainThread:@selector(_setCydiaSource:) withObject:source waitUntilDone:NO];
4130 - (NSString *) cydiaSource {
4131 @synchronized (HostConfig_) {
4132 return (id) CydiaSource_ ?: [NSNull null];
4136 - (NSArray *) getMetadataKeys {
4137 @synchronized (Values_) {
4138 return [Values_ allKeys];
4141 - (id) getMetadataValue:(NSString *)key {
4142 @synchronized (Values_) {
4143 return [Values_ objectForKey:key];
4146 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4147 @synchronized (Values_) {
4148 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4149 [Values_ removeObjectForKey:key];
4151 [Values_ setObject:value forKey:key];
4153 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4156 - (id) getSessionValue:(NSString *)key {
4157 @synchronized (SessionData_) {
4158 return [SessionData_ objectForKey:key];
4161 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4162 @synchronized (SessionData_) {
4163 if (value == (id) [WebUndefined undefined])
4164 [SessionData_ removeObjectForKey:key];
4166 [SessionData_ setObject:value forKey:key];
4169 - (void) addBridgedHost:(NSString *)host {
4170 @synchronized (HostConfig_) {
4171 [BridgedHosts_ addObject:host];
4174 - (void) addInsecureHost:(NSString *)host {
4175 @synchronized (HostConfig_) {
4176 [InsecureHosts_ addObject:host];
4179 - (void) addTokenHost:(NSString *)host {
4180 @synchronized (HostConfig_) {
4181 [TokenHosts_ addObject:host];
4184 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4185 @synchronized (HostConfig_) {
4186 if (scheme != (id) [WebUndefined undefined])
4187 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4189 [PipelinedHosts_ addObject:host];
4192 - (void) popViewController:(NSNumber *)value {
4193 if (value == (id) [WebUndefined undefined])
4194 value = [NSNumber numberWithBool:YES];
4195 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4198 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4199 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4201 for (NSString *section in sections)
4202 [array addObject:section];
4204 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4207 distribution, @"Distribution",
4209 nil] waitUntilDone:NO];
4212 - (void) addTrivialSource:(NSString *)href {
4213 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4216 - (void) refreshSources {
4217 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4220 - (void) saveConfig {
4221 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4224 - (NSArray *) getAllSources {
4225 return [[Database sharedInstance] sources];
4228 - (NSArray *) getInstalledPackages {
4229 Database *database([Database sharedInstance]);
4230 @synchronized (database) {
4231 NSArray *packages([database packages]);
4232 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4233 for (Package *package in packages)
4234 if (![package uninstalled])
4235 [installed addObject:package];
4239 - (Package *) getPackageById:(NSString *)id {
4240 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4244 return (Package *) [NSNull null];
4247 - (NSString *) getLocaleIdentifier {
4248 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4251 - (NSArray *) getPreferredLanguages {
4255 - (NSArray *) statfs:(NSString *)path {
4258 if (path == nil || statfs([path UTF8String], &stat) == -1)
4261 return [NSArray arrayWithObjects:
4262 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4263 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4264 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4268 - (NSNumber *) du:(NSString *)path {
4269 NSNumber *value(nil);
4272 _assert(pipe(fds) != -1);
4274 pid_t pid(ExecFork());
4276 _assert(dup2(fds[1], 1) != -1);
4277 _assert(close(fds[0]) != -1);
4278 _assert(close(fds[1]) != -1);
4279 /* XXX: this should probably not use du */
4280 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4285 _assert(close(fds[1]) != -1);
4287 if (FILE *du = fdopen(fds[0], "r")) {
4289 while (fgets(line, sizeof(line), du) != NULL) {
4290 size_t length(strlen(line));
4291 while (length != 0 && line[length - 1] == '\n')
4292 line[--length] = '\0';
4293 if (char *tab = strchr(line, '\t')) {
4295 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4300 } else _assert(close(fds[0]));
4304 if (waitpid(pid, &status, 0) == -1)
4307 else _assert(false);
4313 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4316 - (void) installPackages:(NSArray *)packages {
4317 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4320 - (NSString *) substitutePackageNames:(NSString *)message {
4321 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4322 for (size_t i(0), e([words count]); i != e; ++i) {
4323 NSString *word([words objectAtIndex:i]);
4324 if (Package *package = [[Database sharedInstance] packageWithName:word])
4325 [words replaceObjectAtIndex:i withObject:[package name]];
4328 return [words componentsJoinedByString:@" "];
4331 - (void) removeButton {
4332 [indirect_ removeButton];
4335 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4336 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4339 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4340 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4343 - (void) setBadgeValue:(id)value {
4344 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4347 - (void) setAllowsNavigationAction:(NSString *)value {
4348 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4351 - (void) setHidesBackButton:(NSString *)value {
4352 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4355 - (void) setHidesNavigationBar:(NSString *)value {
4356 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4359 - (void) setNavigationBarStyle:(NSString *)value {
4360 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4363 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4364 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4365 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4366 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4369 - (void) setPasteboardString:(NSString *)value {
4370 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4373 - (void) setPasteboardURL:(NSString *)value {
4374 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4377 - (void) _setToken:(NSString *)token {
4381 [Metadata_ removeObjectForKey:@"Token"];
4383 [Metadata_ setObject:Token_ forKey:@"Token"];
4388 - (void) setToken:(NSString *)token {
4389 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4392 - (void) scrollToBottom:(NSNumber *)animated {
4393 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4396 - (void) setViewportWidth:(float)width {
4397 [indirect_ setViewportWidthOnMainThread:width];
4400 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4401 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4402 unsigned count([arguments count]);
4404 for (unsigned i(0); i != count; ++i)
4405 values[i] = [arguments objectAtIndex:i];
4406 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4409 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4410 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4412 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4414 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4420 @interface NSURL (CydiaSecure)
4423 @implementation NSURL (CydiaSecure)
4425 - (bool) isCydiaSecure {
4426 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4429 @synchronized (HostConfig_) {
4430 if ([InsecureHosts_ containsObject:[self host]])
4439 /* Cydia Browser Controller {{{ */
4440 @implementation CydiaWebViewController
4442 - (NSURL *) navigationURL {
4443 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4446 + (void) initialize {
4447 Diversions_ = [NSMutableSet setWithCapacity:0];
4450 + (void) addDiversion:(Diversion *)diversion {
4451 [Diversions_ addObject:diversion];
4454 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4455 [super webView:view didClearWindowObject:window forFrame:frame];
4457 WebDataSource *source([frame dataSource]);
4458 NSURLResponse *response([source response]);
4459 NSURL *url([response URL]);
4460 NSString *scheme([[url scheme] lowercaseString]);
4462 bool bridged(false);
4464 @synchronized (HostConfig_) {
4465 if ([scheme isEqualToString:@"file"])
4467 else if ([scheme isEqualToString:@"https"])
4468 if ([BridgedHosts_ containsObject:[url host]])
4473 [window setValue:cydia_ forKey:@"cydia"];
4476 - (void) _setupMail:(MFMailComposeViewController *)controller {
4477 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4479 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4480 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4483 - (NSURL *) URLWithURL:(NSURL *)url {
4484 return [Diversion divertURL:url];
4487 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4488 NSURL *url([request URL]);
4489 NSString *host([url host]);
4491 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4493 if (System_ != NULL && [copy valueForHTTPHeaderField:@"X-System"] == nil)
4494 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4495 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4496 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4499 @synchronized (HostConfig_) {
4500 token = [TokenHosts_ containsObject:host] || [BridgedHosts_ containsObject:host];
4503 if ([url isCydiaSecure] && token) {
4504 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4505 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4511 - (void) setDelegate:(id)delegate {
4512 [super setDelegate:delegate];
4513 [cydia_ setDelegate:delegate];
4516 - (NSString *) applicationNameForUserAgent {
4517 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4520 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4522 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4523 if (Product_ != nil)
4524 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4530 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4531 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4539 @interface NSObject (CydiaScript)
4540 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4543 @implementation NSObject (CydiaScript)
4545 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4551 @implementation NSArray (CydiaScript)
4553 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4554 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4555 for (size_t i(0), e([self count]); i != e; ++i)
4556 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4562 @implementation NSDictionary (CydiaScript)
4564 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4565 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4567 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4574 /* Confirmation Controller {{{ */
4575 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4576 if (!iterator.end())
4577 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4578 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4580 pkgCache::PkgIterator package(dep.TargetPkg());
4583 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4590 @protocol ConfirmationControllerDelegate
4591 - (void) cancelAndClear:(bool)clear;
4592 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4596 @interface ConfirmationController : CydiaWebViewController {
4597 _transient Database *database_;
4599 _H<UIAlertView> essential_;
4601 _H<NSDictionary> changes_;
4602 _H<NSMutableArray> issues_;
4603 _H<NSDictionary> sizes_;
4608 - (id) initWithDatabase:(Database *)database;
4612 @implementation ConfirmationController
4616 RestartSubstrate_ = true;
4617 [delegate_ confirmWithNavigationController:[self navigationController]];
4620 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4621 NSString *context([alert context]);
4623 if ([context isEqualToString:@"remove"]) {
4624 if (button == [alert cancelButtonIndex])
4625 [self dismissModalViewControllerAnimated:YES];
4626 else if (button == [alert firstOtherButtonIndex]) {
4630 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4631 } else if ([context isEqualToString:@"unable"]) {
4632 [self dismissModalViewControllerAnimated:YES];
4633 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4635 [super alertView:alert clickedButtonAtIndex:button];
4639 - (void) _doContinue {
4640 [self dismissModalViewControllerAnimated:YES];
4641 [delegate_ cancelAndClear:NO];
4644 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4645 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4649 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4650 [super webView:view didClearWindowObject:window forFrame:frame];
4652 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4653 (id) changes_, @"changes",
4654 (id) issues_, @"issues",
4655 (id) sizes_, @"sizes",
4657 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4660 - (id) initWithDatabase:(Database *)database {
4661 if ((self = [super init]) != nil) {
4662 database_ = database;
4664 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4665 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4666 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4667 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4668 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4672 pkgCacheFile &cache([database_ cache]);
4673 NSArray *packages([database_ packages]);
4674 pkgDepCache::Policy *policy([database_ policy]);
4676 issues_ = [NSMutableArray arrayWithCapacity:4];
4678 for (Package *package in packages) {
4679 pkgCache::PkgIterator iterator([package iterator]);
4680 NSString *name([package id]);
4682 if ([package broken]) {
4683 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4685 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4687 reasons, @"reasons",
4690 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4694 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4695 pkgCache::DepIterator start;
4696 pkgCache::DepIterator end;
4697 dep.GlobOr(start, end); // ++dep
4699 if (!cache->IsImportantDep(end))
4701 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4704 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4706 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4707 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4708 clauses, @"clauses",
4712 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4714 pkgCache::PkgIterator target(start.TargetPkg());
4715 if (target->ProvidesList != 0)
4716 reason = @"missing";
4718 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4720 reason = @"installed";
4721 installed = [NSString stringWithUTF8String:ver.VerStr()];
4722 } else if (!cache[target].CandidateVerIter(cache).end())
4723 reason = @"uninstalled";
4724 else if (target->ProvidesList == 0)
4725 reason = @"uninstallable";
4727 reason = @"virtual";
4730 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4731 [NSString stringWithUTF8String:start.CompType()], @"operator",
4732 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4735 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4736 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4737 version, @"version",
4739 installed, @"installed",
4742 // yes, seriously. (wtf?)
4750 pkgDepCache::StateCache &state(cache[iterator]);
4752 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4754 if (state.NewInstall())
4755 [installs addObject:name];
4756 // XXX: else if (state.Install())
4757 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4758 [reinstalls addObject:name];
4759 // XXX: move before previous if
4760 else if (state.Upgrade())
4761 [upgrades addObject:name];
4762 else if (state.Downgrade())
4763 [downgrades addObject:name];
4764 else if (!state.Delete())
4765 // XXX: _assert(state.Keep());
4767 else if (special_r(name))
4768 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4769 [NSNull null], @"package",
4770 [NSArray arrayWithObjects:
4771 [NSDictionary dictionaryWithObjectsAndKeys:
4772 @"Conflicts", @"relationship",
4773 [NSArray arrayWithObjects:
4774 [NSDictionary dictionaryWithObjectsAndKeys:
4776 [NSNull null], @"version",
4777 @"installed", @"reason",
4784 if ([package essential])
4786 [removes addObject:name];
4789 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4790 substrate_ |= DepSubstrate(iterator.CurrentVer());
4795 else if (Advanced_) {
4796 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4798 essential_ = [[[UIAlertView alloc]
4799 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4800 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4802 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4804 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4808 [essential_ setContext:@"remove"];
4810 essential_ = [[[UIAlertView alloc]
4811 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4812 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4814 cancelButtonTitle:UCLocalize("OKAY")
4815 otherButtonTitles:nil
4818 [essential_ setContext:@"unable"];
4821 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4822 installs, @"installs",
4823 reinstalls, @"reinstalls",
4824 upgrades, @"upgrades",
4825 downgrades, @"downgrades",
4826 removes, @"removes",
4829 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
4830 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4831 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4834 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4838 - (UIBarButtonItem *) leftButton {
4839 return [[[UIBarButtonItem alloc]
4840 initWithTitle:UCLocalize("CANCEL")
4841 style:UIBarButtonItemStylePlain
4843 action:@selector(cancelButtonClicked)
4848 - (void) applyRightButton {
4849 if ([issues_ count] == 0 && ![self isLoading])
4850 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4851 initWithTitle:UCLocalize("CONFIRM")
4852 style:UIBarButtonItemStyleDone
4854 action:@selector(confirmButtonClicked)
4857 [[self navigationItem] setRightBarButtonItem:nil];
4861 - (void) cancelButtonClicked {
4862 [self dismissModalViewControllerAnimated:YES];
4863 [delegate_ cancelAndClear:YES];
4867 - (void) confirmButtonClicked {
4868 if (essential_ != nil)
4878 /* Progress Data {{{ */
4879 @interface CydiaProgressData : NSObject {
4880 _transient id delegate_;
4889 _H<NSMutableArray> events_;
4890 _H<NSString> title_;
4892 _H<NSString> status_;
4893 _H<NSString> finish_;
4898 @implementation CydiaProgressData
4900 + (NSArray *) _attributeKeys {
4901 return [NSArray arrayWithObjects:
4913 - (NSArray *) attributeKeys {
4914 return [[self class] _attributeKeys];
4917 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4918 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4922 if ((self = [super init]) != nil) {
4923 events_ = [NSMutableArray arrayWithCapacity:32];
4927 - (void) setDelegate:(id)delegate {
4928 delegate_ = delegate;
4931 - (void) setPercent:(float)value {
4935 - (NSNumber *) percent {
4936 return [NSNumber numberWithFloat:percent_];
4939 - (void) setCurrent:(float)value {
4943 - (NSNumber *) current {
4944 return [NSNumber numberWithFloat:current_];
4947 - (void) setTotal:(float)value {
4951 - (NSNumber *) total {
4952 return [NSNumber numberWithFloat:total_];
4955 - (void) setSpeed:(float)value {
4959 - (NSNumber *) speed {
4960 return [NSNumber numberWithFloat:speed_];
4963 - (NSArray *) events {
4967 - (void) removeAllEvents {
4968 [events_ removeAllObjects];
4971 - (void) addEvent:(CydiaProgressEvent *)event {
4972 [events_ addObject:event];
4975 - (void) setTitle:(NSString *)text {
4979 - (NSString *) title {
4983 - (void) setFinish:(NSString *)text {
4987 - (NSString *) finish {
4988 return (id) finish_ ?: [NSNull null];
4991 - (void) setRunning:(bool)running {
4995 - (NSNumber *) running {
4996 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5001 /* Progress Controller {{{ */
5002 @interface ProgressController : CydiaWebViewController <
5005 _transient Database *database_;
5006 _H<CydiaProgressData, 1> progress_;
5010 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5012 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5014 - (void) setTitle:(NSString *)title;
5015 - (void) setCancellable:(bool)cancellable;
5019 @implementation ProgressController
5022 [database_ setProgressDelegate:nil];
5026 - (UIBarButtonItem *) leftButton {
5027 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5028 initWithTitle:UCLocalize("CANCEL")
5029 style:UIBarButtonItemStylePlain
5031 action:@selector(cancel)
5032 ] autorelease] : nil;
5035 - (void) updateCancel {
5036 [super applyLeftButton];
5039 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5040 if ((self = [super init]) != nil) {
5041 database_ = database;
5042 delegate_ = delegate;
5044 [database_ setProgressDelegate:self];
5046 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5047 [progress_ setDelegate:self];
5049 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5051 [scroller_ setBackgroundColor:[UIColor blackColor]];
5053 [[self navigationItem] setHidesBackButton:YES];
5055 [self updateCancel];
5059 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5060 [super webView:view didClearWindowObject:window forFrame:frame];
5061 [window setValue:progress_ forKey:@"cydiaProgress"];
5064 - (void) updateProgress {
5065 [self dispatchEvent:@"CydiaProgressUpdate"];
5068 - (void) viewWillAppear:(BOOL)animated {
5069 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5070 [super viewWillAppear:animated];
5074 UpdateExternalStatus(0);
5077 [delegate_ saveState];
5084 [delegate_ terminateWithSuccess];
5085 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5086 [delegate_ suspendWithAnimation:YES];
5088 [delegate_ suspend];*/
5100 system("/usr/bin/sbreload");
5106 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5107 SBReboot(SBSSpringBoardServerPort());
5109 reboot2(RB_AUTOBOOT);
5116 - (void) setTitle:(NSString *)title {
5117 [progress_ setTitle:title];
5118 [self updateProgress];
5121 - (UIBarButtonItem *) rightButton {
5122 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5123 initWithTitle:UCLocalize("CLOSE")
5124 style:UIBarButtonItemStylePlain
5126 action:@selector(close)
5130 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5131 UpdateExternalStatus(1);
5133 [progress_ setRunning:true];
5134 [self setTitle:title];
5135 // implicit updateProgress
5137 SHA1SumValue notifyconf; {
5139 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5142 MMap mmap(file, MMap::ReadOnly);
5144 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5145 notifyconf = sha1.Result();
5149 SHA1SumValue springlist; {
5151 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5154 MMap mmap(file, MMap::ReadOnly);
5156 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5157 springlist = sha1.Result();
5161 if (invocation != nil) {
5162 [invocation yieldToSelector:@selector(invoke)];
5163 [self setTitle:@"COMPLETE"];
5168 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5171 MMap mmap(file, MMap::ReadOnly);
5173 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5174 if (!(notifyconf == sha1.Result()))
5181 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5184 MMap mmap(file, MMap::ReadOnly);
5186 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5187 if (!(springlist == sha1.Result()))
5193 if (RestartSubstrate_)
5197 RestartSubstrate_ = false;
5200 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5201 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5202 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5203 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5204 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5208 system("su -c /usr/bin/uicache mobile");
5211 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5213 [progress_ setRunning:false];
5214 [self updateProgress];
5216 [self applyRightButton];
5219 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5220 [progress_ addEvent:event];
5221 [self updateProgress];
5224 - (bool) isProgressCancelled {
5225 return cancel_ == 2;
5230 [self updateCancel];
5233 - (void) setCancellable:(bool)cancellable {
5234 unsigned cancel(cancel_);
5238 else if (cancel_ == 0)
5241 if (cancel != cancel_)
5242 [self updateCancel];
5245 - (void) setProgressCancellable:(NSNumber *)cancellable {
5246 [self setCancellable:[cancellable boolValue]];
5249 - (void) setProgressPercent:(NSNumber *)percent {
5250 [progress_ setPercent:[percent floatValue]];
5251 [self updateProgress];
5254 - (void) setProgressStatus:(NSDictionary *)status {
5255 if (status == nil) {
5256 [progress_ setCurrent:0];
5257 [progress_ setTotal:0];
5258 [progress_ setSpeed:0];
5260 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5262 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5263 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5264 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5267 [self updateProgress];
5273 /* Package Cell {{{ */
5274 @interface PackageCell : CyteTableViewCell <
5275 CyteTableViewCellDelegate
5279 _H<NSString> description_;
5281 _H<NSString> source_;
5283 _H<Package> package_;
5284 _H<UIImage> placard_;
5288 - (PackageCell *) init;
5289 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5291 - (void) drawContentRect:(CGRect)rect;
5295 @implementation PackageCell
5297 - (PackageCell *) init {
5298 CGRect frame(CGRectMake(0, 0, 320, 74));
5299 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5300 UIView *content([self contentView]);
5301 CGRect bounds([content bounds]);
5303 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5304 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5305 [content addSubview:content_];
5307 [content_ setDelegate:self];
5308 [content_ setOpaque:YES];
5312 - (NSString *) accessibilityLabel {
5313 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), (id) name_, (id) description_];
5316 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5317 summarized_ = summary;
5329 Source *source = [package source];
5331 icon_ = [package icon];
5333 if (NSString *name = [package name])
5334 name_ = [NSString stringWithString:name];
5336 NSString *description(nil);
5338 if (description == nil && IsWildcat_)
5339 description = [package longDescription];
5340 if (description == nil)
5341 description = [package shortDescription];
5343 if (description != nil)
5344 description_ = [NSString stringWithString:description];
5346 commercial_ = [package isCommercial];
5350 NSString *label = nil;
5351 bool trusted = false;
5353 if (source != nil) {
5354 label = [source label];
5355 trusted = [source trusted];
5356 } else if ([[package id] isEqualToString:@"firmware"])
5357 label = UCLocalize("APPLE");
5359 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5361 NSString *from(label);
5363 NSString *section = [package simpleSection];
5364 if (section != nil && ![section isEqualToString:label]) {
5365 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5366 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5369 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5371 if (NSString *purpose = [package primaryPurpose])
5372 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5377 if (NSString *mode = [package_ mode]) {
5378 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5379 color = RemovingColor_;
5380 //placard = @"removing";
5382 color = InstallingColor_;
5383 //placard = @"installing";
5386 // XXX: the removing/installing placards are not @2x
5389 color = [UIColor whiteColor];
5391 if ([package installed] != nil)
5392 placard = @"installed";
5397 [content_ setBackgroundColor:color];
5400 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5402 [self setNeedsDisplay];
5403 [content_ setNeedsDisplay];
5406 - (void) drawSummaryContentRect:(CGRect)rect {
5407 bool highlighted(highlighted_);
5408 float width([self bounds].size.width);
5412 rect.size = [(UIImage *) icon_ size];
5414 rect.size.width /= 4;
5415 rect.size.height /= 4;
5417 rect.origin.x = 14 - rect.size.width / 4;
5418 rect.origin.y = 14 - rect.size.height / 4;
5420 [icon_ drawInRect:rect];
5423 if (badge_ != nil) {
5425 rect.size = [(UIImage *) badge_ size];
5427 rect.size.width /= 4;
5428 rect.size.height /= 4;
5430 rect.origin.x = 20 - rect.size.width / 4;
5431 rect.origin.y = 20 - rect.size.height / 4;
5433 [badge_ drawInRect:rect];
5440 UISetColor(commercial_ ? Purple_ : Black_);
5441 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5443 if (placard_ != nil)
5444 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5447 - (void) drawNormalContentRect:(CGRect)rect {
5448 bool highlighted(highlighted_);
5449 float width([self bounds].size.width);
5453 rect.size = [(UIImage *) icon_ size];
5455 rect.size.width /= 2;
5456 rect.size.height /= 2;
5458 rect.origin.x = 25 - rect.size.width / 2;
5459 rect.origin.y = 25 - rect.size.height / 2;
5461 [icon_ drawInRect:rect];
5464 if (badge_ != nil) {
5466 rect.size = [(UIImage *) badge_ size];
5468 rect.size.width /= 2;
5469 rect.size.height /= 2;
5471 rect.origin.x = 36 - rect.size.width / 2;
5472 rect.origin.y = 36 - rect.size.height / 2;
5474 [badge_ drawInRect:rect];
5481 UISetColor(commercial_ ? Purple_ : Black_);
5482 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5483 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5486 UISetColor(commercial_ ? Purplish_ : Gray_);
5487 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5489 if (placard_ != nil)
5490 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5493 - (void) drawContentRect:(CGRect)rect {
5495 [self drawSummaryContentRect:rect];
5497 [self drawNormalContentRect:rect];
5502 /* Section Cell {{{ */
5503 @interface SectionCell : CyteTableViewCell <
5504 CyteTableViewCellDelegate
5506 _H<NSString> basic_;
5507 _H<NSString> section_;
5509 _H<NSString> count_;
5511 _H<UISwitch> switch_;
5515 - (void) setSection:(Section *)section editing:(BOOL)editing;
5519 @implementation SectionCell
5521 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5522 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5523 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5524 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5525 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5527 UIView *content([self contentView]);
5528 CGRect bounds([content bounds]);
5530 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5531 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5532 [content addSubview:content_];
5533 [content_ setBackgroundColor:[UIColor whiteColor]];
5535 [content_ setDelegate:self];
5539 - (void) onSwitch:(id)sender {
5540 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5541 if (metadata == nil) {
5542 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5543 [Sections_ setObject:metadata forKey:basic_];
5546 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5550 - (void) setSection:(Section *)section editing:(BOOL)editing {
5551 if (editing != editing_) {
5553 [switch_ removeFromSuperview];
5555 [self addSubview:switch_];
5564 if (section == nil) {
5565 name_ = UCLocalize("ALL_PACKAGES");
5568 basic_ = [section name];
5569 section_ = [section localized];
5571 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5572 count_ = [NSString stringWithFormat:@"%d", [section count]];
5575 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5578 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5579 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5581 [content_ setNeedsDisplay];
5584 - (void) setFrame:(CGRect)frame {
5585 [super setFrame:frame];
5587 CGRect rect([switch_ frame]);
5588 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5591 - (NSString *) accessibilityLabel {
5595 - (void) drawContentRect:(CGRect)rect {
5596 bool highlighted(highlighted_ && !editing_);
5598 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5603 float width(rect.size.width);
5609 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5611 CGSize size = [count_ sizeWithFont:Font14_];
5615 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5621 /* File Table {{{ */
5622 @interface FileTable : CyteViewController <
5623 UITableViewDataSource,
5626 _transient Database *database_;
5627 _H<Package> package_;
5629 _H<NSMutableArray> files_;
5630 _H<UITableView, 2> list_;
5633 - (id) initWithDatabase:(Database *)database;
5634 - (void) setPackage:(Package *)package;
5638 @implementation FileTable
5640 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5641 return files_ == nil ? 0 : [files_ count];
5644 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5648 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5649 static NSString *reuseIdentifier = @"Cell";
5651 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5653 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5654 [cell setFont:[UIFont systemFontOfSize:16]];
5656 [cell setText:[files_ objectAtIndex:indexPath.row]];
5657 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5662 - (NSURL *) navigationURL {
5663 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5667 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5669 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
5670 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5671 [list_ setRowHeight:24.0f];
5672 [(UITableView *) list_ setDataSource:self];
5673 [list_ setDelegate:self];
5674 [[self view] addSubview:list_];
5677 - (void) viewDidLoad {
5678 [super viewDidLoad];
5680 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5683 - (void) releaseSubviews {
5686 [super releaseSubviews];
5689 - (id) initWithDatabase:(Database *)database {
5690 if ((self = [super init]) != nil) {
5691 database_ = database;
5693 files_ = [NSMutableArray arrayWithCapacity:32];
5697 - (void) setPackage:(Package *)package {
5701 [files_ removeAllObjects];
5703 if (package != nil) {
5705 name_ = [package id];
5707 if (NSArray *files = [package files])
5708 [files_ addObjectsFromArray:files];
5710 if ([files_ count] != 0) {
5711 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5712 [files_ removeObjectAtIndex:0];
5713 [files_ sortUsingSelector:@selector(compareByPath:)];
5715 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5716 [stack addObject:@"/"];
5718 for (int i(0), e([files_ count]); i != e; ++i) {
5719 NSString *file = [files_ objectAtIndex:i];
5720 while (![file hasPrefix:[stack lastObject]])
5721 [stack removeLastObject];
5722 NSString *directory = [stack lastObject];
5723 [stack addObject:[file stringByAppendingString:@"/"]];
5724 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5725 ([stack count] - 2) * 3, "",
5726 [file substringFromIndex:[directory length]]
5735 - (void) reloadData {
5738 [self setPackage:[database_ packageWithName:name_]];
5743 /* Package Controller {{{ */
5744 @interface CYPackageController : CydiaWebViewController <
5745 UIActionSheetDelegate
5747 _transient Database *database_;
5748 _H<Package> package_;
5751 _H<NSMutableArray> buttons_;
5752 _H<UIBarButtonItem> button_;
5755 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5759 @implementation CYPackageController
5761 - (NSURL *) navigationURL {
5762 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5765 /* XXX: this is not safe at all... localization of /fail/ */
5766 - (void) _clickButtonWithName:(NSString *)name {
5767 if ([name isEqualToString:UCLocalize("CLEAR")])
5768 [delegate_ clearPackage:package_];
5769 else if ([name isEqualToString:UCLocalize("INSTALL")])
5770 [delegate_ installPackage:package_];
5771 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5772 [delegate_ installPackage:package_];
5773 else if ([name isEqualToString:UCLocalize("REMOVE")])
5774 [delegate_ removePackage:package_];
5775 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5776 [delegate_ installPackage:package_];
5777 else _assert(false);
5780 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5781 NSString *context([sheet context]);
5783 if ([context isEqualToString:@"modify"]) {
5784 if (button != [sheet cancelButtonIndex]) {
5785 NSString *buttonName = [buttons_ objectAtIndex:button];
5786 [self _clickButtonWithName:buttonName];
5789 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5793 - (bool) _allowJavaScriptPanel {
5798 - (void) _customButtonClicked {
5799 int count([buttons_ count]);
5804 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5806 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5807 [buttons addObjectsFromArray:buttons_];
5809 UIActionSheet *sheet = [[[UIActionSheet alloc]
5812 cancelButtonTitle:nil
5813 destructiveButtonTitle:nil
5814 otherButtonTitles:nil
5817 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5819 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5820 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5822 [sheet setContext:@"modify"];
5824 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5828 // We don't want to allow non-commercial packages to do custom things to the install button,
5829 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5830 - (void) customButtonClicked {
5832 [super customButtonClicked];
5834 [self _customButtonClicked];
5837 - (void) reloadButtonClicked {
5838 // Don't reload a commerical package by tapping the loading button,
5839 // but if it's not an Install button, we should forward it on.
5840 if (![package_ uninstalled])
5841 [self _customButtonClicked];
5844 - (void) applyLoadingTitle {
5845 // Don't show "Loading" as the title. Ever.
5848 - (UIBarButtonItem *) rightButton {
5853 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5854 if ((self = [super init]) != nil) {
5855 database_ = database;
5856 buttons_ = [NSMutableArray arrayWithCapacity:4];
5857 name_ = [NSString stringWithString:name];
5858 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5862 - (void) reloadData {
5865 package_ = [database_ packageWithName:name_];
5867 [buttons_ removeAllObjects];
5869 if (package_ != nil) {
5870 [(Package *) package_ parse];
5872 commercial_ = [package_ isCommercial];
5874 if ([package_ mode] != nil)
5875 [buttons_ addObject:UCLocalize("CLEAR")];
5876 if ([package_ source] == nil);
5877 else if ([package_ upgradableAndEssential:NO])
5878 [buttons_ addObject:UCLocalize("UPGRADE")];
5879 else if ([package_ uninstalled])
5880 [buttons_ addObject:UCLocalize("INSTALL")];
5882 [buttons_ addObject:UCLocalize("REINSTALL")];
5883 if (![package_ uninstalled])
5884 [buttons_ addObject:UCLocalize("REMOVE")];
5888 switch ([buttons_ count]) {
5889 case 0: title = nil; break;
5890 case 1: title = [buttons_ objectAtIndex:0]; break;
5891 default: title = UCLocalize("MODIFY"); break;
5894 button_ = [[[UIBarButtonItem alloc]
5896 style:UIBarButtonItemStylePlain
5898 action:@selector(customButtonClicked)
5902 - (bool) isLoading {
5903 return commercial_ ? [super isLoading] : false;
5909 /* Package List Controller {{{ */
5910 @interface PackageListController : CyteViewController <
5911 UITableViewDataSource,
5914 _transient Database *database_;
5916 _H<NSArray> packages_;
5917 _H<NSMutableArray> sections_;
5918 _H<UITableView, 2> list_;
5919 _H<NSMutableArray> index_;
5920 _H<NSMutableDictionary> indices_;
5921 _H<NSString> title_;
5922 unsigned reloading_;
5925 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5926 - (void) setDelegate:(id)delegate;
5927 - (void) resetCursor;
5932 @implementation PackageListController
5934 - (bool) isSummarized {
5938 - (bool) showsSections {
5942 - (void) deselectWithAnimation:(BOOL)animated {
5943 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5946 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5947 CGRect base = [[self view] bounds];
5948 base.size.height -= bounds.size.height;
5949 base.origin = [list_ frame].origin;
5951 [UIView beginAnimations:nil context:NULL];
5952 [UIView setAnimationBeginsFromCurrentState:YES];
5953 [UIView setAnimationCurve:curve];
5954 [UIView setAnimationDuration:duration];
5955 [list_ setFrame:base];
5956 [UIView commitAnimations];
5959 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5960 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5963 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5964 [self resizeForKeyboardBounds:bounds duration:0];
5967 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
5968 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
5969 *curve = UIViewAnimationCurveEaseInOut;
5971 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
5973 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
5976 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
5979 - (void) keyboardWillShow:(NSNotification *)notification {
5982 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5983 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5985 NSTimeInterval duration;
5986 UIViewAnimationCurve curve;
5987 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
5989 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);
5990 UIViewController *base = self;
5991 while ([base parentViewController] != nil)
5992 base = [base parentViewController];
5993 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5994 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5996 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
5997 intersection.size.height += CYStatusBarHeight([self interfaceOrientation]);
5999 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6002 - (void) keyboardWillHide:(NSNotification *)notification {
6003 NSTimeInterval duration;
6004 UIViewAnimationCurve curve;
6005 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6007 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6010 - (void) viewWillAppear:(BOOL)animated {
6011 [super viewWillAppear:animated];
6013 [self resizeForKeyboardBounds:CGRectZero];
6014 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6015 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6018 - (void) viewWillDisappear:(BOOL)animated {
6019 [super viewWillDisappear:animated];
6021 [self resizeForKeyboardBounds:CGRectZero];
6022 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6023 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6026 - (void) viewDidAppear:(BOOL)animated {
6027 [super viewDidAppear:animated];
6028 [self deselectWithAnimation:animated];
6031 - (void) didSelectPackage:(Package *)package {
6032 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6033 [view setDelegate:delegate_];
6034 [[self navigationController] pushViewController:view animated:YES];
6037 #if TryIndexedCollation
6038 + (BOOL) hasIndexedCollation {
6039 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6043 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6044 NSInteger count([sections_ count]);
6045 return count == 0 ? 1 : count;
6048 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6049 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6051 return [[sections_ objectAtIndex:section] name];
6054 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6055 if ([sections_ count] == 0)
6057 return [[sections_ objectAtIndex:section] count];
6060 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6061 @synchronized (database_) {
6062 if ([database_ era] != era_)
6065 Section *section([sections_ objectAtIndex:[path section]]);
6066 NSInteger row([path row]);
6067 Package *package([packages_ objectAtIndex:([section row] + row)]);
6068 return [[package retain] autorelease];
6071 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6072 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6074 cell = [[[PackageCell alloc] init] autorelease];
6075 [cell setPackage:[self packageAtIndexPath:path] asSummary:[self isSummarized]];
6079 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6080 Package *package([self packageAtIndexPath:path]);
6081 package = [database_ packageWithName:[package id]];
6082 [self didSelectPackage:package];
6085 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6086 if (![self showsSections])
6092 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6093 #if TryIndexedCollation
6094 if ([[self class] hasIndexedCollation]) {
6095 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6102 - (void) updateHeight {
6103 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6106 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6107 if ((self = [super init]) != nil) {
6108 database_ = database;
6109 title_ = [title copy];
6110 [[self navigationItem] setTitle:title_];
6112 #if TryIndexedCollation
6113 if ([[self class] hasIndexedCollation])
6114 index_ = [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles];
6117 index_ = [NSMutableArray arrayWithCapacity:32];
6119 indices_ = [NSMutableDictionary dictionaryWithCapacity:32];
6121 packages_ = [NSArray array];
6122 sections_ = [NSMutableArray arrayWithCapacity:16];
6127 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
6129 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6130 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6131 [[self view] addSubview:list_];
6133 // XXX: is 20 the most optimal number here?
6134 [list_ setSectionIndexMinimumDisplayRowCount:20];
6136 [(UITableView *) list_ setDataSource:self];
6137 [list_ setDelegate:self];
6139 [self updateHeight];
6142 - (void) releaseSubviews {
6145 [super releaseSubviews];
6148 - (void) setDelegate:(id)delegate {
6149 delegate_ = delegate;
6152 - (bool) shouldYield {
6156 - (bool) shouldBlock {
6160 - (NSMutableArray *) _reloadPackages {
6161 @synchronized (database_) {
6162 era_ = [database_ era];
6163 NSArray *packages([database_ packages]);
6165 return [NSMutableArray arrayWithArray:packages];
6168 - (void) _reloadData {
6169 if (reloading_ != 0) {
6176 if ([self shouldYield]) {
6180 if (![self shouldBlock])
6183 hud = [delegate_ addProgressHUD];
6184 [hud setText:UCLocalize("LOADING")];
6188 packages = [self yieldToSelector:@selector(_reloadPackages)];
6191 [delegate_ removeProgressHUD:hud];
6192 } while (reloading_ == 2);
6196 packages = [self _reloadPackages];
6199 packages_ = packages;
6201 [indices_ removeAllObjects];
6202 [sections_ removeAllObjects];
6204 Section *section = nil;
6206 #if TryIndexedCollation
6207 if ([[self class] hasIndexedCollation]) {
6208 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6209 NSArray *titles = [collation sectionIndexTitles];
6212 _profile(PackageTable$reloadData$Section)
6213 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6217 _profile(PackageTable$reloadData$Section$Package)
6218 package = [packages_ objectAtIndex:offset];
6219 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6222 while (secidx < index) {
6225 _profile(PackageTable$reloadData$Section$Allocate)
6226 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6229 _profile(PackageTable$reloadData$Section$Add)
6230 [sections_ addObject:section];
6234 [section addToCount];
6240 [index_ removeAllObjects];
6242 bool sectioned([self showsSections]);
6244 section = [[[Section alloc] initWithName:nil localize:false] autorelease];
6245 [sections_ addObject:section];
6248 _profile(PackageTable$reloadData$Section)
6249 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6253 _profile(PackageTable$reloadData$Section$Package)
6254 package = [packages_ objectAtIndex:offset];
6255 index = [package index];
6258 if (sectioned && (section == nil || [section index] != index)) {
6259 _profile(PackageTable$reloadData$Section$Allocate)
6260 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6263 [index_ addObject:[section name]];
6264 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6266 _profile(PackageTable$reloadData$Section$Add)
6267 [sections_ addObject:section];
6271 [section addToCount];
6276 [self updateHeight];
6278 _profile(PackageTable$reloadData$List)
6279 [(UITableView *) list_ setDataSource:self];
6284 - (void) reloadData {
6286 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6289 - (void) resetCursor {
6290 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6293 - (void) clearData {
6294 [self updateHeight];
6296 [list_ setDataSource:nil];
6304 /* Filtered Package List Controller {{{ */
6305 @interface FilteredPackageListController : PackageListController {
6308 _H<NSObject> object_;
6311 - (void) setObject:(id)object;
6312 - (void) setObject:(id)object forFilter:(SEL)filter;
6315 - (void) setFilter:(SEL)filter;
6317 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6321 @implementation FilteredPackageListController
6327 - (void) setFilter:(SEL)filter {
6328 @synchronized (self) {
6331 /* XXX: this is an unsafe optimization of doomy hell */
6332 Method method(class_getInstanceMethod([Package class], filter));
6333 _assert(method != NULL);
6334 imp_ = method_getImplementation(method);
6335 _assert(imp_ != NULL);
6338 - (void) setObject:(id)object {
6339 @synchronized (self) {
6343 - (void) setObject:(id)object forFilter:(SEL)filter {
6344 @synchronized (self) {
6345 [self setFilter:filter];
6346 [self setObject:object];
6349 - (NSMutableArray *) _reloadPackages {
6350 @synchronized (database_) {
6351 era_ = [database_ era];
6352 NSArray *packages([database_ packages]);
6354 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6358 _H<NSObject> object;
6360 @synchronized (self) {
6366 _profile(PackageTable$reloadData$Filter)
6367 for (Package *package in packages)
6368 if ([package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp))(package, filter, object))
6369 [filtered addObject:package];
6375 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6376 if ((self = [super initWithDatabase:database title:title]) != nil) {
6377 [self setFilter:filter];
6378 [self setObject:object];
6385 /* Home Controller {{{ */
6386 @interface HomeController : CydiaWebViewController {
6391 @implementation HomeController
6394 if ((self = [super init]) != nil) {
6395 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6400 - (NSURL *) navigationURL {
6401 return [NSURL URLWithString:@"cydia://home"];
6404 - (void) aboutButtonClicked {
6405 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6407 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6408 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6409 [alert setCancelButtonIndex:0];
6412 @"Copyright \u00a9 2008-2011\n"
6415 "Jay Freeman (saurik)\n"
6416 "saurik@saurik.com\n"
6417 "http://www.saurik.com/"
6423 - (UIBarButtonItem *) leftButton {
6424 return [[[UIBarButtonItem alloc]
6425 initWithTitle:UCLocalize("ABOUT")
6426 style:UIBarButtonItemStylePlain
6428 action:@selector(aboutButtonClicked)
6434 /* Manage Controller {{{ */
6435 @interface ManageController : CydiaWebViewController {
6438 - (void) queueStatusDidChange;
6442 @implementation ManageController
6445 if ((self = [super init]) != nil) {
6446 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6450 - (NSURL *) navigationURL {
6451 return [NSURL URLWithString:@"cydia://manage"];
6454 - (UIBarButtonItem *) leftButton {
6455 return [[[UIBarButtonItem alloc]
6456 initWithTitle:UCLocalize("SETTINGS")
6457 style:UIBarButtonItemStylePlain
6459 action:@selector(settingsButtonClicked)
6463 - (void) settingsButtonClicked {
6464 [delegate_ showSettings];
6467 - (void) queueButtonClicked {
6471 - (UIBarButtonItem *) customButton {
6472 return Queuing_ ? [[[UIBarButtonItem alloc]
6473 initWithTitle:UCLocalize("QUEUE")
6474 style:UIBarButtonItemStyleDone
6476 action:@selector(queueButtonClicked)
6477 ] autorelease] : [super customButton];
6480 - (void) queueStatusDidChange {
6481 [self applyRightButton];
6484 - (bool) isLoading {
6485 return !Queuing_ && [super isLoading];
6491 /* Refresh Bar {{{ */
6492 @interface RefreshBar : UINavigationBar {
6493 _H<UIProgressIndicator> indicator_;
6494 _H<UITextLabel> prompt_;
6495 _H<UIProgressBar> progress_;
6496 _H<UINavigationButton> cancel_;
6501 @implementation RefreshBar
6503 - (void) positionViews {
6504 CGRect frame = [cancel_ frame];
6505 frame.size = [cancel_ sizeThatFits:frame.size];
6506 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6507 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6508 [cancel_ setFrame:frame];
6510 CGSize prgsize = {75, 100};
6512 [self frame].size.width - prgsize.width - 10,
6513 ([self frame].size.height - prgsize.height) / 2
6515 [progress_ setFrame:prgrect];
6517 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6518 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6519 CGRect indrect = {{indoffset, indoffset}, indsize};
6520 [indicator_ setFrame:indrect];
6522 CGSize prmsize = {215, indsize.height + 4};
6524 indoffset * 2 + indsize.width,
6525 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6527 [prompt_ setFrame:prmrect];
6530 - (void) setFrame:(CGRect)frame {
6531 [super setFrame:frame];
6532 [self positionViews];
6535 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6536 if ((self = [super initWithFrame:frame]) != nil) {
6537 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6539 [self setBarStyle:UIBarStyleBlack];
6541 UIBarStyle barstyle([self _barStyle:NO]);
6542 bool ugly(barstyle == UIBarStyleDefault);
6544 UIProgressIndicatorStyle style = ugly ?
6545 UIProgressIndicatorStyleMediumBrown :
6546 UIProgressIndicatorStyleMediumWhite;
6548 indicator_ = [[[UIProgressIndicator alloc] initWithFrame:CGRectZero] autorelease];
6549 [(UIProgressIndicator *) indicator_ setStyle:style];
6550 [indicator_ startAnimation];
6551 [self addSubview:indicator_];
6553 prompt_ = [[[UITextLabel alloc] initWithFrame:CGRectZero] autorelease];
6554 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6555 [prompt_ setBackgroundColor:[UIColor clearColor]];
6556 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6557 [self addSubview:prompt_];
6559 progress_ = [[[UIProgressBar alloc] initWithFrame:CGRectZero] autorelease];
6560 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6561 [(UIProgressBar *) progress_ setStyle:0];
6562 [self addSubview:progress_];
6564 cancel_ = [[[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted] autorelease];
6565 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6566 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6567 [cancel_ setBarStyle:barstyle];
6569 [self positionViews];
6573 - (void) setCancellable:(bool)cancellable {
6575 [self addSubview:cancel_];
6577 [cancel_ removeFromSuperview];
6581 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6582 [progress_ setProgress:0];
6586 [self setCancellable:NO];
6589 - (void) setPrompt:(NSString *)prompt {
6590 [prompt_ setText:prompt];
6593 - (void) setProgress:(float)progress {
6594 [progress_ setProgress:progress];
6600 /* Cydia Navigation Controller Interface {{{ */
6601 @interface UINavigationController (Cydia)
6603 - (NSArray *) navigationURLCollection;
6604 - (void) unloadData;
6609 /* Cydia Tab Bar Controller {{{ */
6610 @interface CYTabBarController : UITabBarController <
6611 UITabBarControllerDelegate,
6614 _transient Database *database_;
6615 _H<RefreshBar, 1> refreshbar_;
6619 // XXX: ok, "updatedelegate_"?...
6620 _transient NSObject<CydiaDelegate> *updatedelegate_;
6622 _H<UIViewController> remembered_;
6623 _transient UIViewController *transient_;
6626 - (NSArray *) navigationURLCollection;
6627 - (void) dropBar:(BOOL)animated;
6628 - (void) beginUpdate;
6629 - (void) raiseBar:(BOOL)animated;
6631 - (void) unloadData;
6635 @implementation CYTabBarController
6637 - (void) setUnselectedViewController:(UIViewController *)transient {
6638 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6639 if (transient != nil) {
6640 if (transient_ == nil)
6641 remembered_ = [controllers objectAtIndex:0];
6642 transient_ = transient;
6643 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6644 [controllers replaceObjectAtIndex:0 withObject:transient_];
6645 [self setSelectedIndex:0];
6646 [self setViewControllers:controllers];
6647 [self concealTabBarSelection];
6648 } else if (remembered_ != nil) {
6649 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6650 transient_ = transient;
6651 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6653 [self setViewControllers:controllers];
6654 [self revealTabBarSelection];
6658 - (UIViewController *) unselectedViewController {
6662 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6663 if ([self unselectedViewController])
6664 [self setUnselectedViewController:nil];
6667 - (NSArray *) navigationURLCollection {
6668 NSMutableArray *items([NSMutableArray array]);
6670 // XXX: Should this deal with transient view controllers?
6671 for (id navigation in [self viewControllers]) {
6672 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6674 [items addObject:stack];
6680 - (void) unloadData {
6683 for (UINavigationController *controller in [self viewControllers])
6684 [controller unloadData];
6686 if (UIViewController *selected = [self selectedViewController])
6687 [selected reloadData];
6689 if (UIViewController *unselected = [self unselectedViewController]) {
6690 [unselected unloadData];
6691 [unselected reloadData];
6696 [[NSNotificationCenter defaultCenter] removeObserver:self];
6701 - (id) initWithDatabase:(Database *)database {
6702 if ((self = [super init]) != nil) {
6703 database_ = database;
6704 [self setDelegate:self];
6706 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6707 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6709 refreshbar_ = [[[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self] autorelease];
6713 - (void) setUpdate:(NSDate *)date {
6717 - (void) beginUpdate {
6718 [(RefreshBar *) refreshbar_ start];
6721 [updatedelegate_ retainNetworkActivityIndicator];
6725 detachNewThreadSelector:@selector(performUpdate)
6731 - (void) performUpdate {
6732 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6735 status.setDelegate(self);
6736 [database_ updateWithStatus:status];
6739 performSelectorOnMainThread:@selector(completeUpdate)
6747 - (void) stopUpdateWithSelector:(SEL)selector {
6749 [updatedelegate_ releaseNetworkActivityIndicator];
6751 [self raiseBar:YES];
6754 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6757 - (void) completeUpdate {
6760 [self stopUpdateWithSelector:@selector(reloadData)];
6763 - (void) cancelUpdate {
6764 [self stopUpdateWithSelector:@selector(updateData)];
6767 - (void) cancelPressed {
6768 [self cancelUpdate];
6775 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6776 [refreshbar_ setPrompt:[event compoundMessage]];
6779 - (bool) isProgressCancelled {
6783 - (void) setProgressCancellable:(NSNumber *)cancellable {
6784 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6787 - (void) setProgressPercent:(NSNumber *)percent {
6788 [refreshbar_ setProgress:[percent floatValue]];
6791 - (void) setProgressStatus:(NSDictionary *)status {
6793 [self setProgressPercent:[status objectForKey:@"Percent"]];
6796 - (void) setUpdateDelegate:(id)delegate {
6797 updatedelegate_ = delegate;
6800 - (UIView *) transitionView {
6801 if ([self respondsToSelector:@selector(_transitionView)])
6802 return [self _transitionView];
6804 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6807 - (void) dropBar:(BOOL)animated {
6812 UIView *transition([self transitionView]);
6813 [[self view] addSubview:refreshbar_];
6815 CGRect barframe([refreshbar_ frame]);
6817 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6818 barframe.origin.y = CYStatusBarHeight([self interfaceOrientation]);
6820 barframe.origin.y = 0;
6822 [refreshbar_ setFrame:barframe];
6825 [UIView beginAnimations:nil context:NULL];
6827 CGRect viewframe = [transition frame];
6828 viewframe.origin.y += barframe.size.height;
6829 viewframe.size.height -= barframe.size.height;
6830 [transition setFrame:viewframe];
6833 [UIView commitAnimations];
6835 // Ensure bar has the proper width for our view, it might have changed
6836 barframe.size.width = viewframe.size.width;
6837 [refreshbar_ setFrame:barframe];
6840 - (void) raiseBar:(BOOL)animated {
6845 UIView *transition([self transitionView]);
6846 [refreshbar_ removeFromSuperview];
6848 CGRect barframe([refreshbar_ frame]);
6851 [UIView beginAnimations:nil context:NULL];
6853 CGRect viewframe = [transition frame];
6854 viewframe.origin.y -= barframe.size.height;
6855 viewframe.size.height += barframe.size.height;
6856 [transition setFrame:viewframe];
6859 [UIView commitAnimations];
6862 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6863 bool dropped(dropped_);
6868 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6874 - (void) statusBarFrameChanged:(NSNotification *)notification {
6884 /* Cydia Navigation Controller Implementation {{{ */
6885 @implementation UINavigationController (Cydia)
6887 - (NSArray *) navigationURLCollection {
6888 NSMutableArray *stack([NSMutableArray array]);
6890 for (CyteViewController *controller in [self viewControllers]) {
6891 NSString *url = [[controller navigationURL] absoluteString];
6893 [stack addObject:url];
6899 - (void) reloadData {
6902 if (UIViewController *visible = [self visibleViewController])
6903 [visible reloadData];
6906 - (void) unloadData {
6907 for (CyteViewController *page in [self viewControllers])
6916 /* Cydia:// Protocol {{{ */
6917 @interface CydiaURLProtocol : NSURLProtocol {
6922 @implementation CydiaURLProtocol
6924 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6925 NSURL *url([request URL]);
6929 NSString *scheme([[url scheme] lowercaseString]);
6930 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6932 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6938 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6942 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6943 id<NSURLProtocolClient> client([self client]);
6945 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6947 NSData *data(UIImagePNGRepresentation(icon));
6949 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6950 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6951 [client URLProtocol:self didLoadData:data];
6952 [client URLProtocolDidFinishLoading:self];
6956 - (void) startLoading {
6957 id<NSURLProtocolClient> client([self client]);
6958 NSURLRequest *request([self request]);
6960 NSURL *url([request URL]);
6961 NSString *href([url absoluteString]);
6962 NSString *scheme([[url scheme] lowercaseString]);
6966 if ([scheme isEqualToString:@"cydia"])
6967 path = [href substringFromIndex:8];
6968 else if ([scheme isEqualToString:@"about"])
6969 path = [href substringFromIndex:12];
6970 else _assert(false);
6972 NSRange slash([path rangeOfString:@"/"]);
6975 if (slash.location == NSNotFound) {
6979 command = [path substringToIndex:slash.location];
6980 path = [path substringFromIndex:(slash.location + 1)];
6983 Database *database([Database sharedInstance]);
6985 if ([command isEqualToString:@"package-icon"]) {
6988 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6989 Package *package([database packageWithName:path]);
6993 UIImage *icon([package icon]);
6994 [self _returnPNGWithImage:icon forRequest:request];
6995 } else if ([command isEqualToString:@"source-icon"]) {
6998 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6999 NSString *source(Simplify(path));
7000 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7002 icon = [UIImage applicationImageNamed:@"unknown.png"];
7003 [self _returnPNGWithImage:icon forRequest:request];
7004 } else if ([command isEqualToString:@"uikit-image"]) {
7007 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7008 UIImage *icon(_UIImageWithName(path));
7009 [self _returnPNGWithImage:icon forRequest:request];
7010 } else if ([command isEqualToString:@"section-icon"]) {
7013 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7014 NSString *section(Simplify(path));
7015 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7017 icon = [UIImage applicationImageNamed:@"unknown.png"];
7018 [self _returnPNGWithImage:icon forRequest:request];
7020 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7024 - (void) stopLoading {
7030 /* Section Controller {{{ */
7031 @interface SectionController : FilteredPackageListController {
7032 _H<NSString> section_;
7035 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7039 @implementation SectionController
7041 - (NSURL *) navigationURL {
7042 NSString *name = section_;
7046 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7049 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7052 title = UCLocalize("ALL_PACKAGES");
7053 else if (![name isEqual:@""])
7054 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7056 title = UCLocalize("NO_SECTION");
7058 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7065 /* Sections Controller {{{ */
7066 @interface SectionsController : CyteViewController <
7067 UITableViewDataSource,
7070 _transient Database *database_;
7071 _H<NSMutableArray> sections_;
7072 _H<NSMutableArray> filtered_;
7073 _H<UITableView, 2> list_;
7076 - (id) initWithDatabase:(Database *)database;
7077 - (void) editButtonClicked;
7081 @implementation SectionsController
7083 - (NSURL *) navigationURL {
7084 return [NSURL URLWithString:@"cydia://sections"];
7087 - (void) updateNavigationItem {
7088 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7089 if ([sections_ count] == 0) {
7090 [[self navigationItem] setRightBarButtonItem:nil];
7092 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7093 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7095 action:@selector(editButtonClicked)
7096 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7100 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7101 [super setEditing:editing animated:animated];
7106 [delegate_ updateData];
7108 [self updateNavigationItem];
7111 - (void) viewDidAppear:(BOOL)animated {
7112 [super viewDidAppear:animated];
7113 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7116 - (void) viewWillDisappear:(BOOL)animated {
7117 [super viewWillDisappear:animated];
7118 if ([self isEditing]) [self setEditing:NO];
7121 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7122 Section *section = nil;
7123 int index = [indexPath row];
7124 if (![self isEditing]) {
7127 section = [filtered_ objectAtIndex:index];
7129 section = [sections_ objectAtIndex:index];
7134 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7135 if ([self isEditing])
7136 return [sections_ count];
7138 return [filtered_ count] + 1;
7141 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7145 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7146 static NSString *reuseIdentifier = @"SectionCell";
7148 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7150 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7152 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7157 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7158 if ([self isEditing])
7161 Section *section = [self sectionAtIndexPath:indexPath];
7163 SectionController *controller = [[[SectionController alloc]
7164 initWithDatabase:database_
7165 section:[section name]
7167 [controller setDelegate:delegate_];
7169 [[self navigationController] pushViewController:controller animated:YES];
7173 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7175 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds]] autorelease];
7176 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7177 [list_ setRowHeight:45.0f];
7178 [(UITableView *) list_ setDataSource:self];
7179 [list_ setDelegate:self];
7180 [[self view] addSubview:list_];
7183 - (void) viewDidLoad {
7184 [super viewDidLoad];
7186 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7189 - (void) releaseSubviews {
7192 [super releaseSubviews];
7195 - (id) initWithDatabase:(Database *)database {
7196 if ((self = [super init]) != nil) {
7197 database_ = database;
7199 sections_ = [NSMutableArray arrayWithCapacity:16];
7200 filtered_ = [NSMutableArray arrayWithCapacity:16];
7204 - (void) reloadData {
7207 NSArray *packages = [database_ packages];
7209 [sections_ removeAllObjects];
7210 [filtered_ removeAllObjects];
7212 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7215 for (Package *package in packages) {
7216 NSString *name([package section]);
7217 NSString *key(name == nil ? @"" : name);
7221 _profile(SectionsView$reloadData$Section)
7222 section = [sections objectForKey:key];
7223 if (section == nil) {
7224 _profile(SectionsView$reloadData$Section$Allocate)
7225 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7226 [sections setObject:section forKey:key];
7231 [section addToCount];
7233 _profile(SectionsView$reloadData$Filter)
7234 if (![package valid] || ![package visible])
7242 [sections_ addObjectsFromArray:[sections allValues]];
7244 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7246 for (Section *section in (id) sections_) {
7247 size_t count([section row]);
7251 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7252 [section setCount:count];
7253 [filtered_ addObject:section];
7256 [self updateNavigationItem];
7261 - (void) editButtonClicked {
7262 [self setEditing:![self isEditing] animated:YES];
7268 /* Changes Controller {{{ */
7269 @interface ChangesController : CyteViewController <
7270 UITableViewDataSource,
7273 _transient Database *database_;
7275 _H<NSArray> packages_;
7276 _H<NSMutableArray> sections_;
7277 _H<UITableView, 2> list_;
7281 - (id) initWithDatabase:(Database *)database;
7285 @implementation ChangesController
7287 - (NSURL *) navigationURL {
7288 return [NSURL URLWithString:@"cydia://changes"];
7291 - (void) viewDidAppear:(BOOL)animated {
7292 [super viewDidAppear:animated];
7293 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7296 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7297 NSInteger count([sections_ count]);
7298 return count == 0 ? 1 : count;
7301 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7302 if ([sections_ count] == 0)
7304 return [[sections_ objectAtIndex:section] name];
7307 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7308 if ([sections_ count] == 0)
7310 return [[sections_ objectAtIndex:section] count];
7313 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7314 @synchronized (database_) {
7315 if ([database_ era] != era_)
7318 NSUInteger sectionIndex([path section]);
7319 if (sectionIndex >= [sections_ count])
7321 Section *section([sections_ objectAtIndex:sectionIndex]);
7322 NSInteger row([path row]);
7323 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7326 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7327 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7329 cell = [[[PackageCell alloc] init] autorelease];
7330 [cell setPackage:[self packageAtIndexPath:path] asSummary:false];
7334 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7335 Package *package([self packageAtIndexPath:path]);
7336 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7337 [view setDelegate:delegate_];
7338 [[self navigationController] pushViewController:view animated:YES];
7342 - (void) refreshButtonClicked {
7343 [delegate_ beginUpdate];
7344 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7347 - (void) upgradeButtonClicked {
7348 [delegate_ distUpgrade];
7349 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7353 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7355 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
7356 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7357 [list_ setRowHeight:73];
7358 [(UITableView *) list_ setDataSource:self];
7359 [list_ setDelegate:self];
7360 [[self view] addSubview:list_];
7363 - (void) viewDidLoad {
7364 [super viewDidLoad];
7366 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7369 - (void) releaseSubviews {
7372 [super releaseSubviews];
7375 - (id) initWithDatabase:(Database *)database {
7376 if ((self = [super init]) != nil) {
7377 database_ = database;
7379 packages_ = [NSArray array];
7380 sections_ = [NSMutableArray arrayWithCapacity:16];
7384 - (NSMutableArray *) _reloadPackages {
7385 @synchronized (database_) {
7386 era_ = [database_ era];
7387 NSArray *packages([database_ packages]);
7389 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
7392 _profile(ChangesController$_reloadPackages$Filter)
7393 for (Package *package in packages)
7394 if ([package upgradableAndEssential:YES] || [package visible])
7395 CFArrayAppendValue((CFMutableArrayRef) filtered, package);
7398 _profile(ChangesController$_reloadPackages$radixSort)
7399 [filtered radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7406 - (void) _reloadData {
7411 UIProgressHUD *hud([delegate_ addProgressHUD]);
7412 [hud setText:UCLocalize("LOADING")];
7413 //NSLog(@"HUD:%@::%@", delegate_, hud);
7414 packages = [self yieldToSelector:@selector(_reloadPackages)];
7415 [delegate_ removeProgressHUD:hud];
7417 packages = [self _reloadPackages];
7420 @synchronized (database_) {
7421 if (era_ != [database_ era])
7424 packages_ = packages;
7425 [sections_ removeAllObjects];
7427 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7428 Section *ignored = nil;
7429 Section *section = nil;
7433 bool unseens = false;
7435 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7437 for (size_t offset = 0, count = [packages_ count]; offset != count; ++offset) {
7438 Package *package = [packages_ objectAtIndex:offset];
7440 BOOL uae = [package upgradableAndEssential:YES];
7444 time_t seen([package seen]);
7446 if (section == nil || last != seen) {
7450 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7453 _profile(ChangesController$reloadData$Allocate)
7454 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7455 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7456 [sections_ addObject:section];
7460 [section addToCount];
7461 } else if ([package ignored]) {
7462 if (ignored == nil) {
7463 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7465 [ignored addToCount];
7468 [upgradable addToCount];
7473 CFRelease(formatter);
7476 Section *last = [sections_ lastObject];
7477 size_t count = [last count];
7478 [packages_ removeObjectsInRange:NSMakeRange([packages_ count] - count, count)];
7479 [sections_ removeLastObject];
7482 if ([ignored count] != 0)
7483 [sections_ insertObject:ignored atIndex:0];
7485 [sections_ insertObject:upgradable atIndex:0];
7489 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7490 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7491 style:UIBarButtonItemStylePlain
7493 action:@selector(upgradeButtonClicked)
7494 ] autorelease]) animated:YES];
7496 [[self navigationItem] setLeftBarButtonItem:([delegate_ updating] ? nil : [[[UIBarButtonItem alloc]
7497 initWithTitle:UCLocalize("REFRESH")
7498 style:UIBarButtonItemStylePlain
7500 action:@selector(refreshButtonClicked)
7501 ] autorelease]) animated:YES];
7506 - (void) reloadData {
7508 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7513 /* Search Controller {{{ */
7514 @interface SearchController : FilteredPackageListController <
7517 _H<UISearchBar, 1> search_;
7521 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7522 - (void) reloadData;
7526 @implementation SearchController
7528 - (NSURL *) navigationURL {
7529 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7530 return [NSURL URLWithString:@"cydia://search"];
7532 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7535 - (void) useSearch {
7536 [self setObject:[[search_ text] componentsSeparatedByString:@" "] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7541 - (void) viewWillAppear:(BOOL)animated {
7542 [super viewWillAppear:animated];
7544 if ([self filter] == @selector(isUnfilteredAndSelectedForBy:))
7548 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7549 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7554 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7555 [search_ resignFirstResponder];
7559 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7560 [search_ setText:@""];
7561 [self searchBarButtonClicked:searchBar];
7564 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7565 [self searchBarButtonClicked:searchBar];
7568 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7569 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7573 - (bool) shouldYield {
7577 - (bool) shouldBlock {
7578 return [self filter] == @selector(isUnfilteredAndSearchedForBy:);
7581 - (bool) isSummarized {
7582 return [self filter] == @selector(isUnfilteredAndSelectedForBy:);
7585 - (bool) showsSections {
7589 - (NSMutableArray *) _reloadPackages {
7590 NSMutableArray *packages([super _reloadPackages]);
7591 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7592 [packages radixSortUsingSelector:@selector(rank)];
7596 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7597 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:[query componentsSeparatedByString:@" "]])) {
7598 search_ = [[[UISearchBar alloc] init] autorelease];
7599 [search_ setDelegate:self];
7602 [search_ setText:query];
7606 - (void) viewDidAppear:(BOOL)animated {
7607 [super viewDidAppear:animated];
7609 if (!searchloaded_) {
7610 searchloaded_ = YES;
7611 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7612 [search_ layoutSubviews];
7613 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7615 UITextField *textField;
7616 if ([search_ respondsToSelector:@selector(searchField)])
7617 textField = [search_ searchField];
7619 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7621 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7622 [textField setEnablesReturnKeyAutomatically:NO];
7623 [[self navigationItem] setTitleView:textField];
7627 - (void) reloadData {
7628 id object([search_ text]);
7629 if ([self filter] == @selector(isUnfilteredAndSearchedForBy:))
7630 object = [object componentsSeparatedByString:@" "];
7632 [self setObject:object];
7638 - (void) didSelectPackage:(Package *)package {
7639 [search_ resignFirstResponder];
7640 [super didSelectPackage:package];
7645 /* Package Settings Controller {{{ */
7646 @interface PackageSettingsController : CyteViewController <
7647 UITableViewDataSource,
7650 _transient Database *database_;
7652 _H<Package> package_;
7653 _H<UITableView, 2> table_;
7654 _H<UISwitch> subscribedSwitch_;
7655 _H<UISwitch> ignoredSwitch_;
7656 _H<UITableViewCell> subscribedCell_;
7657 _H<UITableViewCell> ignoredCell_;
7660 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7664 @implementation PackageSettingsController
7666 - (NSURL *) navigationURL {
7667 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7670 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7671 if (package_ == nil)
7674 if ([package_ installed] == nil)
7680 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7681 if (package_ == nil)
7684 // both sections contain just one item right now.
7688 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7692 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7694 return UCLocalize("SHOW_ALL_CHANGES_EX");
7696 return UCLocalize("IGNORE_UPGRADES_EX");
7699 - (void) onSubscribed:(id)control {
7700 bool value([control isOn]);
7701 if (package_ == nil)
7703 if ([package_ setSubscribed:value])
7704 [delegate_ updateData];
7707 - (void) _updateIgnored {
7708 const char *package([name_ UTF8String]);
7709 bool on([ignoredSwitch_ isOn]);
7711 pid_t pid(ExecFork());
7713 FILE *dpkg(popen("dpkg --set-selections", "w"));
7714 fwrite(package, strlen(package), 1, dpkg);
7717 fwrite(" hold\n", 6, 1, dpkg);
7719 fwrite(" install\n", 9, 1, dpkg);
7729 int result(waitpid(pid, &status, 0));
7732 _assert(result == pid);
7738 - (void) onIgnored:(id)control {
7739 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7740 [invocation setTarget:self];
7741 [invocation setSelector:@selector(_updateIgnored)];
7743 [delegate_ reloadDataWithInvocation:invocation];
7746 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7747 if (package_ == nil)
7750 switch ([indexPath section]) {
7751 case 0: return subscribedCell_;
7752 case 1: return ignoredCell_;
7761 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7763 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7764 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7765 [(UITableView *) table_ setDataSource:self];
7766 [table_ setDelegate:self];
7767 [[self view] addSubview:table_];
7769 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7770 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7771 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7773 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7774 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7775 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7777 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7778 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7779 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7780 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7782 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7783 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7784 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7785 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7788 - (void) viewDidLoad {
7789 [super viewDidLoad];
7791 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7794 - (void) releaseSubviews {
7796 subscribedCell_ = nil;
7798 ignoredSwitch_ = nil;
7799 subscribedSwitch_ = nil;
7801 [super releaseSubviews];
7804 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7805 if ((self = [super init]) != nil) {
7806 database_ = database;
7811 - (void) reloadData {
7814 package_ = [database_ packageWithName:name_];
7816 if (package_ != nil) {
7817 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7818 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7819 } // XXX: what now, G?
7821 [table_ reloadData];
7827 /* Installed Controller {{{ */
7828 @interface InstalledController : FilteredPackageListController {
7832 - (id) initWithDatabase:(Database *)database;
7834 - (void) updateRoleButton;
7835 - (void) queueStatusDidChange;
7839 @implementation InstalledController
7841 - (NSURL *) navigationURL {
7842 return [NSURL URLWithString:@"cydia://installed"];
7845 - (id) initWithDatabase:(Database *)database {
7846 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7847 [self updateRoleButton];
7848 [self queueStatusDidChange];
7853 - (void) queueButtonClicked {
7858 - (void) queueStatusDidChange {
7862 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7863 initWithTitle:UCLocalize("QUEUE")
7864 style:UIBarButtonItemStyleDone
7866 action:@selector(queueButtonClicked)
7869 [[self navigationItem] setLeftBarButtonItem:nil];
7875 - (void) updateRoleButton {
7876 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7877 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7878 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7879 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7881 action:@selector(roleButtonClicked)
7885 - (void) roleButtonClicked {
7886 [self setObject:[NSNumber numberWithBool:expert_]];
7890 [self updateRoleButton];
7896 /* Source Cell {{{ */
7897 @interface SourceCell : CyteTableViewCell <
7898 CyteTableViewCellDelegate
7901 _H<NSString> origin_;
7902 _H<NSString> label_;
7905 - (void) setSource:(Source *)source;
7909 @implementation SourceCell
7911 - (void) _setImage:(UIImage *)image {
7913 [content_ setNeedsDisplay];
7916 - (void) _setSource:(Source *)source {
7917 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7919 if (NSString *base = [source base])
7920 if ([base length] != 0) {
7921 NSURL *url([NSURL URLWithString:[base stringByAppendingString:@"CydiaIcon.png"]]);
7923 if (NSData *data = [NSURLConnection
7924 sendSynchronousRequest:[NSURLRequest
7926 //cachePolicy:NSURLRequestUseProtocolCachePolicy
7930 returningResponse:NULL
7933 if (UIImage *image = [UIImage imageWithData:data])
7934 [self performSelectorOnMainThread:@selector(_setImage:) withObject:image waitUntilDone:NO];
7940 - (void) setSource:(Source *)source {
7941 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7943 origin_ = [source name];
7944 label_ = [source uri];
7946 [content_ setNeedsDisplay];
7948 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:source];
7951 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7952 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7953 UIView *content([self contentView]);
7954 CGRect bounds([content bounds]);
7956 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
7957 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7958 [content_ setBackgroundColor:[UIColor whiteColor]];
7959 [content addSubview:content_];
7961 [content_ setDelegate:self];
7962 [content_ setOpaque:YES];
7966 - (NSString *) accessibilityLabel {
7970 - (void) drawContentRect:(CGRect)rect {
7971 bool highlighted(highlighted_);
7972 float width(rect.size.width);
7975 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7982 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7986 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7991 /* Source Controller {{{ */
7992 @interface SourceController : FilteredPackageListController {
7993 _transient Source *source_;
7997 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8001 @implementation SourceController
8003 - (NSURL *) navigationURL {
8004 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8007 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8008 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8010 key_ = [source key];
8014 - (void) reloadData {
8015 source_ = [database_ sourceWithKey:key_];
8016 key_ = [source_ key];
8017 [self setObject:source_];
8019 [[self navigationItem] setTitle:[source_ label]];
8026 /* Sources Controller {{{ */
8027 @interface SourcesController : CyteViewController <
8028 UITableViewDataSource,
8031 _transient Database *database_;
8032 _H<UITableView, 2> list_;
8033 _H<NSMutableArray> sources_;
8037 _H<UIProgressHUD> hud_;
8040 //NSURLConnection *installer_;
8041 NSURLConnection *trivial_;
8042 NSURLConnection *trivial_bz2_;
8043 NSURLConnection *trivial_gz_;
8044 //NSURLConnection *automatic_;
8049 - (id) initWithDatabase:(Database *)database;
8050 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8054 @implementation SourcesController
8056 - (void) _releaseConnection:(NSURLConnection *)connection {
8057 if (connection != nil) {
8058 [connection cancel];
8059 //[connection setDelegate:nil];
8060 [connection release];
8065 //[self _releaseConnection:installer_];
8066 [self _releaseConnection:trivial_];
8067 [self _releaseConnection:trivial_gz_];
8068 [self _releaseConnection:trivial_bz2_];
8069 //[self _releaseConnection:automatic_];
8074 - (NSURL *) navigationURL {
8075 return [NSURL URLWithString:@"cydia://sources"];
8078 - (void) viewDidAppear:(BOOL)animated {
8079 [super viewDidAppear:animated];
8080 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8083 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8084 return offset_ == 0 ? 1 : 2;
8087 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8088 switch (section + (offset_ == 0 ? 1 : 0)) {
8089 case 0: return UCLocalize("ENTERED_BY_USER");
8090 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8096 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8097 int count = [sources_ count];
8099 case 0: return (offset_ == 0 ? count : offset_);
8100 case 1: return count - offset_;
8106 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8108 switch (indexPath.section) {
8109 case 0: idx = indexPath.row; break;
8110 case 1: idx = indexPath.row + offset_; break;
8114 return [sources_ objectAtIndex:idx];
8117 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8118 static NSString *cellIdentifier = @"SourceCell";
8120 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8121 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8122 [cell setSource:[self sourceAtIndexPath:indexPath]];
8123 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8128 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8129 Source *source = [self sourceAtIndexPath:indexPath];
8131 SourceController *controller = [[[SourceController alloc]
8132 initWithDatabase:database_
8136 [controller setDelegate:delegate_];
8138 [[self navigationController] pushViewController:controller animated:YES];
8141 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8142 Source *source = [self sourceAtIndexPath:indexPath];
8143 return [source record] != nil;
8146 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8147 if (editingStyle == UITableViewCellEditingStyleDelete) {
8148 Source *source = [self sourceAtIndexPath:indexPath];
8149 [Sources_ removeObjectForKey:[source key]];
8150 [delegate_ syncData];
8155 [delegate_ addTrivialSource:href_];
8156 [delegate_ syncData];
8159 - (NSString *) getWarning {
8160 NSString *href(href_);
8161 NSRange colon([href rangeOfString:@"://"]);
8162 if (colon.location != NSNotFound)
8163 href = [href substringFromIndex:(colon.location + 3)];
8164 href = [href stringByAddingPercentEscapes];
8165 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8166 href = [href stringByCachingURLWithCurrentCDN];
8168 NSURL *url([NSURL URLWithString:href]);
8170 NSStringEncoding encoding;
8171 NSError *error(nil);
8173 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8174 return [warning length] == 0 ? nil : warning;
8178 - (void) _endConnection:(NSURLConnection *)connection {
8179 // XXX: the memory management in this method is horribly awkward
8181 NSURLConnection **field = NULL;
8182 if (connection == trivial_)
8184 else if (connection == trivial_bz2_)
8185 field = &trivial_bz2_;
8186 else if (connection == trivial_gz_)
8187 field = &trivial_gz_;
8188 _assert(field != NULL);
8189 [connection release];
8194 trivial_bz2_ == nil &&
8197 [delegate_ releaseNetworkActivityIndicator];
8199 [delegate_ removeProgressHUD:hud_];
8205 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8208 UIAlertView *alert = [[[UIAlertView alloc]
8209 initWithTitle:UCLocalize("SOURCE_WARNING")
8212 cancelButtonTitle:UCLocalize("CANCEL")
8214 UCLocalize("ADD_ANYWAY"),
8218 [alert setContext:@"warning"];
8219 [alert setNumberOfRows:1];
8223 } else if (error_ != nil) {
8224 UIAlertView *alert = [[[UIAlertView alloc]
8225 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8226 message:[error_ localizedDescription]
8228 cancelButtonTitle:UCLocalize("OK")
8229 otherButtonTitles:nil
8232 [alert setContext:@"urlerror"];
8235 UIAlertView *alert = [[[UIAlertView alloc]
8236 initWithTitle:UCLocalize("NOT_REPOSITORY")
8237 message:UCLocalize("NOT_REPOSITORY_EX")
8239 cancelButtonTitle:UCLocalize("OK")
8240 otherButtonTitles:nil
8243 [alert setContext:@"trivial"];
8252 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8253 switch ([response statusCode]) {
8259 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8260 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8262 [self _endConnection:connection];
8265 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8266 [self _endConnection:connection];
8269 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8270 NSURL *url([NSURL URLWithString:href]);
8272 NSMutableURLRequest *request = [NSMutableURLRequest
8274 cachePolicy:NSURLRequestUseProtocolCachePolicy
8275 timeoutInterval:120.0
8278 [request setHTTPMethod:method];
8280 if (Machine_ != NULL)
8281 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8283 if ([url isCydiaSecure]) {
8284 if (UniqueID_ != nil)
8285 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8288 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8291 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8292 NSString *context([alert context]);
8294 if ([context isEqualToString:@"source"]) {
8297 NSString *href = [[alert textField] text];
8299 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8301 if (![href hasSuffix:@"/"])
8302 href_ = [href stringByAppendingString:@"/"];
8306 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8307 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8308 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8309 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8313 // XXX: this is stupid
8314 hud_ = [delegate_ addProgressHUD];
8315 [hud_ setText:UCLocalize("VERIFYING_URL")];
8316 [delegate_ retainNetworkActivityIndicator];
8325 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8326 } else if ([context isEqualToString:@"trivial"])
8327 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8328 else if ([context isEqualToString:@"urlerror"])
8329 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8330 else if ([context isEqualToString:@"warning"]) {
8344 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8349 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8351 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
8352 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8353 [list_ setRowHeight:56];
8354 [(UITableView *) list_ setDataSource:self];
8355 [list_ setDelegate:self];
8356 [[self view] addSubview:list_];
8359 - (void) viewDidLoad {
8360 [super viewDidLoad];
8362 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8363 [self updateButtonsForEditingStatus:NO animated:NO];
8366 - (void) releaseSubviews {
8369 [super releaseSubviews];
8372 - (id) initWithDatabase:(Database *)database {
8373 if ((self = [super init]) != nil) {
8374 database_ = database;
8375 sources_ = [NSMutableArray arrayWithCapacity:16];
8379 - (void) reloadData {
8383 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8386 [sources_ removeAllObjects];
8387 [sources_ addObjectsFromArray:[database_ sources]];
8389 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8392 int count([sources_ count]);
8394 for (int i = 0; i != count; i++) {
8395 if ([[sources_ objectAtIndex:i] record] == nil)
8400 [list_ setEditing:NO];
8401 [self updateButtonsForEditingStatus:NO animated:NO];
8405 - (void) showAddSourcePrompt {
8406 UIAlertView *alert = [[[UIAlertView alloc]
8407 initWithTitle:UCLocalize("ENTER_APT_URL")
8410 cancelButtonTitle:UCLocalize("CANCEL")
8412 UCLocalize("ADD_SOURCE"),
8416 [alert setContext:@"source"];
8418 [alert setNumberOfRows:1];
8419 [alert addTextFieldWithValue:@"http://" label:@""];
8421 UITextInputTraits *traits = [[alert textField] textInputTraits];
8422 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8423 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8424 [traits setKeyboardType:UIKeyboardTypeURL];
8425 // XXX: UIReturnKeyDone
8426 [traits setReturnKeyType:UIReturnKeyNext];
8431 - (void) addButtonClicked {
8432 [self showAddSourcePrompt];
8435 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8436 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8437 initWithTitle:UCLocalize("ADD")
8438 style:UIBarButtonItemStylePlain
8440 action:@selector(addButtonClicked)
8441 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8443 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8444 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8445 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8447 action:@selector(editButtonClicked)
8448 ] autorelease] animated:animated];
8450 if (IsWildcat_ && !editing)
8451 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8452 initWithTitle:UCLocalize("SETTINGS")
8453 style:UIBarButtonItemStylePlain
8455 action:@selector(settingsButtonClicked)
8459 - (void) settingsButtonClicked {
8460 [delegate_ showSettings];
8463 - (void) editButtonClicked {
8464 [list_ setEditing:![list_ isEditing] animated:YES];
8466 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8472 /* Settings Controller {{{ */
8473 @interface SettingsController : CyteViewController <
8474 UITableViewDataSource,
8477 _transient Database *database_;
8478 // XXX: ok, "roledelegate_"?...
8479 _transient id roledelegate_;
8480 _H<UITableView, 2> table_;
8481 _H<UISegmentedControl> segment_;
8482 _H<UIView> container_;
8485 - (void) showDoneButton;
8486 - (void) resizeSegmentedControl;
8490 @implementation SettingsController
8493 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8495 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8496 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8497 [table_ setDelegate:self];
8498 [(UITableView *) table_ setDataSource:self];
8499 [[self view] addSubview:table_];
8501 NSArray *items = [NSArray arrayWithObjects:
8503 UCLocalize("HACKER"),
8504 UCLocalize("DEVELOPER"),
8506 segment_ = [[[UISegmentedControl alloc] initWithItems:items] autorelease];
8507 container_ = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)] autorelease];
8508 [container_ addSubview:segment_];
8511 - (void) viewDidLoad {
8512 [super viewDidLoad];
8514 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8517 if ([Role_ isEqualToString:@"User"]) index = 0;
8518 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8519 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8521 [segment_ setSelectedSegmentIndex:index];
8522 [self showDoneButton];
8525 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8526 [self resizeSegmentedControl];
8529 - (void) releaseSubviews {
8534 [super releaseSubviews];
8537 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8538 if ((self = [super init]) != nil) {
8539 database_ = database;
8540 roledelegate_ = delegate;
8544 - (void) resizeSegmentedControl {
8545 CGFloat width = [[self view] frame].size.width;
8546 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8549 - (void) viewWillAppear:(BOOL)animated {
8550 [super viewWillAppear:animated];
8552 [self resizeSegmentedControl];
8555 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8556 [self resizeSegmentedControl];
8559 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8560 [self resizeSegmentedControl];
8564 NSString *role(nil);
8566 switch ([segment_ selectedSegmentIndex]) {
8567 case 0: role = @"User"; break;
8568 case 1: role = @"Hacker"; break;
8569 case 2: role = @"Developer"; break;
8574 if (![role isEqualToString:Role_]) {
8575 bool rolling(Role_ == nil);
8578 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8582 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8586 [roledelegate_ loadData];
8588 [roledelegate_ updateData];
8592 - (void) segmentChanged:(UISegmentedControl *)control {
8593 [self showDoneButton];
8596 - (void) saveAndClose {
8599 [[self navigationItem] setRightBarButtonItem:nil];
8600 [[self navigationController] dismissModalViewControllerAnimated:YES];
8603 - (void) doneButtonClicked {
8604 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8605 [spinner startAnimating];
8606 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8607 [[self navigationItem] setRightBarButtonItem:spinItem];
8609 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8612 - (void) showDoneButton {
8613 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8614 initWithTitle:UCLocalize("DONE")
8615 style:UIBarButtonItemStyleDone
8617 action:@selector(doneButtonClicked)
8618 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8621 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8622 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8626 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8630 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8631 return nil; // This method is required by the protocol.
8634 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8636 return UCLocalize("ROLE_EX");
8638 return [NSString stringWithFormat:
8639 @"%@: %@\n%@: %@\n%@: %@",
8640 UCLocalize("USER"), UCLocalize("USER_EX"),
8641 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8642 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8647 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8648 return section == 3 ? 44.0f : 0;
8651 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8652 return section == 3 ? container_ : nil;
8655 - (void) reloadData {
8658 [table_ reloadData];
8663 /* Stash Controller {{{ */
8664 @interface StashController : CyteViewController {
8665 _H<UIActivityIndicatorView> spinner_;
8666 _H<UILabel> status_;
8667 _H<UILabel> caption_;
8672 @implementation StashController
8675 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8676 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8678 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8679 CGRect spinrect = [spinner_ frame];
8680 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8681 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8682 [spinner_ setFrame:spinrect];
8683 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8684 [[self view] addSubview:spinner_];
8685 [spinner_ startAnimating];
8688 captrect.size.width = [[self view] frame].size.width;
8689 captrect.size.height = 40.0f;
8690 captrect.origin.x = 0;
8691 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8692 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8693 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8694 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8695 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8696 [caption_ setTextColor:[UIColor whiteColor]];
8697 [caption_ setBackgroundColor:[UIColor clearColor]];
8698 [caption_ setShadowColor:[UIColor blackColor]];
8699 [caption_ setTextAlignment:UITextAlignmentCenter];
8700 [[self view] addSubview:caption_];
8703 statusrect.size.width = [[self view] frame].size.width;
8704 statusrect.size.height = 30.0f;
8705 statusrect.origin.x = 0;
8706 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8707 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8708 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8709 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8710 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8711 [status_ setTextColor:[UIColor whiteColor]];
8712 [status_ setBackgroundColor:[UIColor clearColor]];
8713 [status_ setShadowColor:[UIColor blackColor]];
8714 [status_ setTextAlignment:UITextAlignmentCenter];
8715 [[self view] addSubview:status_];
8718 - (void) releaseSubviews {
8723 [super releaseSubviews];
8729 @interface CYURLCache : SDURLCache {
8734 @implementation CYURLCache
8736 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8739 else if ([event isEqualToString:@"no-cache"])
8741 else if ([event isEqualToString:@"store"])
8743 else if ([event isEqualToString:@"invalid"])
8745 else if ([event isEqualToString:@"memory"])
8747 else if ([event isEqualToString:@"disk"])
8749 else if ([event isEqualToString:@"miss"])
8752 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8756 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8757 if (NSURLResponse *response = [cached response])
8758 if (NSString *mime = [response MIMEType])
8759 if ([mime isEqualToString:@"text/cache-manifest"]) {
8760 NSURL *url([response URL]);
8763 NSLog(@"###: %@", [url absoluteString]);
8766 @synchronized (HostConfig_) {
8767 [CachedURLs_ addObject:url];
8771 [super storeCachedResponse:cached forRequest:request];
8776 @interface Cydia : UIApplication <
8777 ConfirmationControllerDelegate,
8780 UINavigationControllerDelegate,
8781 UITabBarControllerDelegate
8783 _H<UIWindow> window_;
8784 _H<CYTabBarController> tabbar_;
8785 _H<CydiaLoadingViewController> emulated_;
8787 _H<NSMutableArray> essential_;
8788 _H<NSMutableArray> broken_;
8790 Database *database_;
8792 _H<NSURL> starturl_;
8797 _H<StashController> stash_;
8806 @implementation Cydia
8808 - (void) beginUpdate {
8809 [tabbar_ beginUpdate];
8813 return [tabbar_ updating];
8817 if ([broken_ count] != 0) {
8818 int count = [broken_ count];
8820 UIAlertView *alert = [[[UIAlertView alloc]
8821 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8822 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8824 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8826 UCLocalize("TEMPORARY_IGNORE"),
8830 [alert setContext:@"fixhalf"];
8831 [alert setNumberOfRows:2];
8833 } else if (!Ignored_ && [essential_ count] != 0) {
8834 int count = [essential_ count];
8836 UIAlertView *alert = [[[UIAlertView alloc]
8837 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8838 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8840 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8842 UCLocalize("UPGRADE_ESSENTIAL"),
8843 UCLocalize("COMPLETE_UPGRADE"),
8847 [alert setContext:@"upgrade"];
8852 - (void) _saveConfig {
8858 NSString *error(nil);
8860 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8862 NSError *error(nil);
8863 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8864 NSLog(@"failure to save metadata data: %@", error);
8869 NSLog(@"failure to serialize metadata: %@", error);
8876 // Navigation controller for the queuing badge.
8877 - (UINavigationController *) queueNavigationController {
8878 NSArray *controllers = [tabbar_ viewControllers];
8879 return [controllers objectAtIndex:3];
8882 - (void) unloadData {
8883 [tabbar_ unloadData];
8886 - (void) _updateData {
8890 UINavigationController *navigation = [self queueNavigationController];
8892 id queuedelegate = nil;
8893 if ([[navigation viewControllers] count] > 0)
8894 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8896 [queuedelegate queueStatusDidChange];
8897 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8900 - (void) _refreshIfPossible:(NSDate *)update {
8901 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8903 bool recently = false;
8904 if (update != nil) {
8905 NSTimeInterval interval([update timeIntervalSinceNow]);
8906 if (interval <= 0 && interval > -(15*60))
8910 // Don't automatic refresh if:
8911 // - We already refreshed recently.
8912 // - We already auto-refreshed this launch.
8913 // - Auto-refresh is disabled.
8914 if (recently || loaded_ || ManualRefresh) {
8915 // If we are cancelling, we need to make sure it knows it's already loaded.
8918 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8920 // We are going to load, so remember that.
8923 SCNetworkReachabilityFlags flags; {
8924 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8925 SCNetworkReachabilityGetFlags(reachability, &flags);
8926 CFRelease(reachability);
8929 // XXX: this elaborate mess is what Apple is using to determine this? :(
8930 // XXX: do we care if the user has to intervene? maybe that's ok?
8932 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8933 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8934 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8935 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8936 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8937 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8941 // If we can reach the server, auto-refresh!
8943 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8949 - (void) refreshIfPossible {
8950 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8953 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8954 @synchronized (self) {
8955 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8956 [hud setText:UCLocalize("RELOADING_DATA")];
8958 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8961 [self removeProgressHUD:hud];
8965 [essential_ removeAllObjects];
8966 [broken_ removeAllObjects];
8968 NSArray *packages([database_ packages]);
8969 for (Package *package in packages) {
8971 [broken_ addObject:package];
8972 if ([package upgradableAndEssential:NO]) {
8973 if ([package essential])
8974 [essential_ addObject:package];
8979 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8982 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8983 [changesItem setBadgeValue:badge];
8984 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8985 [self setApplicationIconBadgeNumber:changes];
8988 [changesItem setBadgeValue:nil];
8989 [changesItem setAnimatedBadge:NO];
8990 [self setApplicationIconBadgeNumber:0];
8995 [self refreshIfPossible];
8998 - (void) updateData {
9004 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9007 - (void) disemulate {
9008 if (emulated_ == nil)
9011 [window_ addSubview:[tabbar_ view]];
9012 [[emulated_ view] removeFromSuperview];
9014 [window_ setUserInteractionEnabled:YES];
9017 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9018 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9020 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9022 UIViewController *parent;
9023 if (emulated_ == nil)
9032 [parent presentModalViewController:navigation animated:YES];
9035 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9036 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9038 if (navigation != nil)
9039 [navigation pushViewController:progress animated:YES];
9041 [self presentModalViewController:progress force:YES];
9043 [progress invoke:invocation withTitle:title];
9047 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9048 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9051 - (void) repairWithInvocation:(NSInvocation *)invocation {
9053 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9057 - (void) repairWithSelector:(SEL)selector {
9058 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9061 - (void) reloadData {
9062 [self reloadDataWithInvocation:nil];
9067 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9070 - (void) addSource:(NSDictionary *) source {
9074 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9075 AddSource(href, distribution, sections);
9078 - (void) addTrivialSource:(NSString *)href {
9079 AddSource(href, @"./");
9082 - (void) updateValues {
9087 pkgProblemResolver *resolver = [database_ resolver];
9089 resolver->InstallProtect();
9090 if (!resolver->Resolve(true))
9095 // XXX: this is a really crappy way of doing this.
9096 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9097 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9098 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9099 if ([tabbar_ updating])
9100 [tabbar_ cancelUpdate];
9102 if (![database_ prepare])
9105 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9106 [page setDelegate:self];
9107 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9110 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9111 [tabbar_ presentModalViewController:confirm_ animated:YES];
9117 @synchronized (self) {
9122 - (void) clearPackage:(Package *)package {
9123 @synchronized (self) {
9130 - (void) installPackages:(NSArray *)packages {
9131 @synchronized (self) {
9132 for (Package *package in packages)
9139 - (void) installPackage:(Package *)package {
9140 @synchronized (self) {
9147 - (void) removePackage:(Package *)package {
9148 @synchronized (self) {
9155 - (void) distUpgrade {
9156 @synchronized (self) {
9157 if (![database_ upgrade])
9164 [database_ perform];
9165 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9168 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9171 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9175 - (void) showSettings {
9176 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9179 - (void) retainNetworkActivityIndicator {
9180 if (activity_++ == 0)
9181 [self setNetworkActivityIndicatorVisible:YES];
9184 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9188 - (void) releaseNetworkActivityIndicator {
9189 if (--activity_ == 0)
9190 [self setNetworkActivityIndicatorVisible:NO];
9193 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9198 - (void) cancelAndClear:(bool)clear {
9199 @synchronized (self) {
9211 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9212 NSString *context([alert context]);
9214 if ([context isEqualToString:@"conffile"]) {
9215 FILE *input = [database_ input];
9216 if (button == [alert cancelButtonIndex])
9217 fprintf(input, "N\n");
9218 else if (button == [alert firstOtherButtonIndex])
9219 fprintf(input, "Y\n");
9222 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9223 } else if ([context isEqualToString:@"fixhalf"]) {
9224 if (button == [alert cancelButtonIndex]) {
9225 @synchronized (self) {
9226 for (Package *broken in (id) broken_) {
9229 NSString *id = [broken id];
9230 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9231 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9232 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9233 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9239 } else if (button == [alert firstOtherButtonIndex]) {
9240 [broken_ removeAllObjects];
9244 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9245 } else if ([context isEqualToString:@"upgrade"]) {
9246 if (button == [alert firstOtherButtonIndex]) {
9247 @synchronized (self) {
9248 for (Package *essential in (id) essential_)
9249 [essential install];
9254 } else if (button == [alert firstOtherButtonIndex] + 1) {
9256 } else if (button == [alert cancelButtonIndex]) {
9260 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9264 - (void) system:(NSString *)command {
9265 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9268 system([command UTF8String]);
9274 - (void) applicationWillSuspend {
9276 [super applicationWillSuspend];
9279 - (BOOL) isSafeToSuspend {
9282 NSLog(@"isSafeToSuspend: locked_ != 0");
9287 // Use external process status API internally.
9288 // This is probably a really bad idea.
9289 // XXX: what is the point of this? does this solve anything at all?
9290 uint64_t status = 0;
9292 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9293 notify_get_state(notify_token, &status);
9294 notify_cancel(notify_token);
9299 NSLog(@"isSafeToSuspend: status != 0");
9305 NSLog(@"isSafeToSuspend: -> true");
9310 - (void) applicationSuspend:(__GSEvent *)event {
9311 if ([self isSafeToSuspend])
9312 [super applicationSuspend:event];
9315 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9316 if ([self isSafeToSuspend])
9317 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9320 - (void) _setSuspended:(BOOL)value {
9321 if ([self isSafeToSuspend])
9322 [super _setSuspended:value];
9325 - (UIProgressHUD *) addProgressHUD {
9326 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9327 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9329 [window_ setUserInteractionEnabled:NO];
9331 UIViewController *target(tabbar_);
9332 if (UIViewController *modal = [target modalViewController])
9335 UIView *view([target view]);
9336 [view addSubview:hud];
9344 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9347 [hud removeFromSuperview];
9348 [window_ setUserInteractionEnabled:YES];
9351 - (CyteViewController *) pageForPackage:(NSString *)name {
9352 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9355 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9356 NSString *scheme([[url scheme] lowercaseString]);
9357 if ([[url absoluteString] length] <= [scheme length] + 3)
9359 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9360 NSArray *components([path pathComponents]);
9362 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9363 return [self pageForPackage:[components objectAtIndex:1]];
9365 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9368 NSString *base([components objectAtIndex:0]);
9370 CyteViewController *controller = nil;
9372 if ([base isEqualToString:@"url"]) {
9373 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9374 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9375 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9376 } else if (!external && [components count] == 1) {
9377 if ([base isEqualToString:@"manage"]) {
9378 controller = [[[ManageController alloc] init] autorelease];
9381 if ([base isEqualToString:@"sources"]) {
9382 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9385 if ([base isEqualToString:@"home"]) {
9386 controller = [[[HomeController alloc] init] autorelease];
9389 if ([base isEqualToString:@"sections"]) {
9390 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9393 if ([base isEqualToString:@"search"]) {
9394 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9397 if ([base isEqualToString:@"changes"]) {
9398 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9401 if ([base isEqualToString:@"installed"]) {
9402 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9404 } else if ([components count] == 2) {
9405 NSString *argument = [components objectAtIndex:1];
9407 if ([base isEqualToString:@"package"]) {
9408 controller = [self pageForPackage:argument];
9411 if (!external && [base isEqualToString:@"search"]) {
9412 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9415 if (!external && [base isEqualToString:@"sections"]) {
9416 if ([argument isEqualToString:@"all"])
9418 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9421 if (!external && [base isEqualToString:@"sources"]) {
9422 if ([argument isEqualToString:@"add"]) {
9423 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9424 [(SourcesController *)controller showAddSourcePrompt];
9426 Source *source = [database_ sourceWithKey:argument];
9427 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9431 if (!external && [base isEqualToString:@"launch"]) {
9432 [self launchApplicationWithIdentifier:argument suspended:NO];
9435 } else if (!external && [components count] == 3) {
9436 NSString *arg1 = [components objectAtIndex:1];
9437 NSString *arg2 = [components objectAtIndex:2];
9439 if ([base isEqualToString:@"package"]) {
9440 if ([arg2 isEqualToString:@"settings"]) {
9441 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9442 } else if ([arg2 isEqualToString:@"files"]) {
9443 if (Package *package = [database_ packageWithName:arg1]) {
9444 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9445 [(FileTable *)controller setPackage:package];
9451 [controller setDelegate:self];
9455 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9456 CyteViewController *page([self pageForURL:url forExternal:external]);
9459 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9460 [nav setViewControllers:[NSArray arrayWithObject:page]];
9461 [tabbar_ setUnselectedViewController:nav];
9467 - (void) applicationOpenURL:(NSURL *)url {
9468 [super applicationOpenURL:url];
9473 [self openCydiaURL:url forExternal:YES];
9476 - (void) applicationWillResignActive:(UIApplication *)application {
9477 // Stop refreshing if you get a phone call or lock the device.
9478 if ([tabbar_ updating])
9479 [tabbar_ cancelUpdate];
9481 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9482 [super applicationWillResignActive:application];
9485 - (void) saveState {
9486 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9487 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9488 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9494 - (void) applicationWillTerminate:(UIApplication *)application {
9498 - (void) setConfigurationData:(NSString *)data {
9499 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9501 if (!conffile_r(data)) {
9502 lprintf("E:invalid conffile\n");
9506 NSString *ofile = conffile_r[1];
9507 //NSString *nfile = conffile_r[2];
9509 UIAlertView *alert = [[[UIAlertView alloc]
9510 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9511 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9513 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9515 UCLocalize("ACCEPT_NEW_COPY"),
9516 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9520 [alert setContext:@"conffile"];
9521 [alert setNumberOfRows:2];
9525 - (void) addStashController {
9527 stash_ = [[[StashController alloc] init] autorelease];
9528 [window_ addSubview:[stash_ view]];
9531 - (void) removeStashController {
9532 [[stash_ view] removeFromSuperview];
9538 [self setIdleTimerDisabled:YES];
9540 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9541 UpdateExternalStatus(1);
9542 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9543 UpdateExternalStatus(0);
9545 [self removeStashController];
9547 if (ExecFork() == 0) {
9548 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9549 perror("launchctl stop");
9553 - (void) setupViewControllers {
9554 tabbar_ = [[[CYTabBarController alloc] initWithDatabase:database_] autorelease];
9556 NSMutableArray *items([NSMutableArray arrayWithObjects:
9557 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9558 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9559 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9560 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9564 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9565 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9567 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9570 NSMutableArray *controllers([NSMutableArray array]);
9571 for (UITabBarItem *item in items) {
9572 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9573 [controller setTabBarItem:item];
9574 [controllers addObject:controller];
9576 [tabbar_ setViewControllers:controllers];
9578 [tabbar_ setUpdateDelegate:self];
9581 - (void) applicationDidFinishLaunching:(id)unused {
9583 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9584 [self setApplicationSupportsShakeToEdit:NO];
9586 @synchronized (HostConfig_) {
9587 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9590 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9591 initWithMemoryCapacity:524288
9592 diskCapacity:10485760
9593 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9596 [CydiaWebViewController _initialize];
9598 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9600 // this would disallow http{,s} URLs from accessing this data
9601 //[WebView registerURLSchemeAsLocal:@"cydia"];
9603 Font12_ = [UIFont systemFontOfSize:12];
9604 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9605 Font14_ = [UIFont systemFontOfSize:14];
9606 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9607 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9609 essential_ = [NSMutableArray arrayWithCapacity:4];
9610 broken_ = [NSMutableArray arrayWithCapacity:4];
9612 // XXX: I really need this thing... like, seriously... I'm sorry
9613 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9615 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9616 [window_ orderFront:self];
9617 [window_ makeKey:self];
9618 [window_ setHidden:NO];
9621 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9622 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9623 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9624 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9625 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9626 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9627 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9628 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9629 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9632 [self addStashController];
9633 // XXX: this would be much cleaner as a yieldToSelector:
9634 // that way the removeStashController could happen right here inline
9635 // we also could no longer require the useless stash_ field anymore
9636 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9640 database_ = [Database sharedInstance];
9641 [database_ setDelegate:self];
9643 [window_ setUserInteractionEnabled:NO];
9644 [self setupViewControllers];
9646 emulated_ = [[[CydiaLoadingViewController alloc] init] autorelease];
9647 [window_ addSubview:[emulated_ view]];
9649 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9653 - (NSArray *) defaultStartPages {
9654 NSMutableArray *standard = [NSMutableArray array];
9655 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9656 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9657 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9659 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9661 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9662 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9664 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9671 [window_ setUserInteractionEnabled:YES];
9672 [self showSettings];
9675 if ([emulated_ modalViewController] != nil)
9676 [emulated_ dismissModalViewControllerAnimated:YES];
9677 [window_ setUserInteractionEnabled:NO];
9685 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9686 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9687 int standardIndex = 0;
9688 NSArray *standard = [self defaultStartPages];
9695 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9696 if (valid && closed != nil) {
9697 NSTimeInterval interval([closed timeIntervalSinceNow]);
9698 // XXX: Is 15 minutes the optimal time here?
9699 if (interval > 0 && interval <= -(15*60))
9703 if (valid && [saved count] != [standard count])
9707 for (unsigned int i = 0; i < [standard count]; i++) {
9708 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9709 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9710 // but it's good enough for now.
9711 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9718 NSArray *items = nil;
9720 [tabbar_ setSelectedIndex:savedIndex];
9723 [tabbar_ setSelectedIndex:standardIndex];
9727 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9728 NSArray *stack = [items objectAtIndex:tab];
9729 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9730 NSMutableArray *current = [NSMutableArray array];
9732 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9733 NSString *addr = [stack objectAtIndex:nav];
9734 NSURL *url = [NSURL URLWithString:addr];
9735 CyteViewController *page = [self pageForURL:url forExternal:NO];
9737 [current addObject:page];
9740 [navigation setViewControllers:current];
9743 // (Try to) show the startup URL.
9744 if (starturl_ != nil) {
9745 [self openCydiaURL:starturl_ forExternal:NO];
9750 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9751 if (item != nil && IsWildcat_) {
9752 [sheet showFromBarButtonItem:item animated:YES];
9754 [sheet showInView:window_];
9758 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9759 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9760 [progress setTitle:task];
9761 [progress addProgressEvent:event];
9764 - (void) addProgressEventForTask:(NSArray *)data {
9765 CydiaProgressEvent *event([data objectAtIndex:0]);
9766 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9767 [self addProgressEvent:event forTask:task];
9770 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9771 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9777 id Alloc_(id self, SEL selector) {
9778 id object = alloc_(self, selector);
9779 lprintf("[%s]A-%p\n", self->isa->name, object);
9784 id Dealloc_(id self, SEL selector) {
9785 id object = dealloc_(self, selector);
9786 lprintf("[%s]D-%p\n", self->isa->name, object);
9790 Class $WebDefaultUIKitDelegate;
9792 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9793 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9794 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9795 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9798 static NSSet *MobilizedFiles_;
9800 static NSURL *MobilizeURL(NSURL *url) {
9801 NSString *path([url path]);
9802 if ([path hasPrefix:@"/var/root/"]) {
9803 NSString *file([path substringFromIndex:10]);
9804 if ([MobilizedFiles_ containsObject:file])
9805 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9811 Class $CFXPreferencesPropertyListSource;
9812 @class CFXPreferencesPropertyListSource;
9814 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9815 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9816 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9817 url = MobilizeURL(url);
9818 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9819 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9825 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9826 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9827 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9828 url = MobilizeURL(url);
9829 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9830 //NSLog(@"%@ %@", [url absoluteString], value);
9836 Class $NSURLConnection;
9838 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9839 NSMutableURLRequest *copy([request mutableCopy]);
9841 NSURL *url([copy URL]);
9843 NSString *href([url absoluteString]);
9844 NSString *host([url host]);
9845 NSString *scheme([[url scheme] lowercaseString]);
9847 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9849 @synchronized (HostConfig_) {
9850 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9851 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9852 [copy setHTTPShouldUsePipelining:YES];
9854 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
9855 if ([control isEqualToString:@"max-age=0"])
9856 if ([CachedURLs_ containsObject:href]) {
9858 NSLog(@"~~~: %@", href);
9861 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
9863 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
9864 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
9865 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
9869 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9873 int main(int argc, char *argv[]) {
9874 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9878 UpdateExternalStatus(0);
9880 if (Class $UIDevice = objc_getClass("UIDevice")) {
9881 UIDevice *device([$UIDevice currentDevice]);
9882 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9886 UIScreen *screen([UIScreen mainScreen]);
9887 if ([screen respondsToSelector:@selector(scale)])
9888 ScreenScale_ = [screen scale];
9892 UIDevice *device([UIDevice currentDevice]);
9893 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9896 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9897 if (idiom == UIUserInterfaceIdiomPhone)
9899 else if (idiom == UIUserInterfaceIdiomPad)
9902 NSLog(@"unknown UIUserInterfaceIdiom!");
9905 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9907 HostConfig_ = [[[NSObject alloc] init] autorelease];
9908 @synchronized (HostConfig_) {
9909 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9910 TokenHosts_ = [NSMutableSet setWithCapacity:4];
9911 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9912 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9913 CachedURLs_ = [NSMutableSet setWithCapacity:32];
9916 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9918 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9920 MobilizedFiles_ = [NSMutableSet setWithObjects:
9921 @"Library/Preferences/com.apple.Accessibility.plist",
9922 @"Library/Preferences/com.apple.preferences.sounds.plist",
9925 /* Library Hacks {{{ */
9926 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9928 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9930 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9931 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9932 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9933 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9936 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9937 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9938 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9939 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9942 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9943 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9944 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9945 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9946 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9949 $NSURLConnection = objc_getClass("NSURLConnection");
9950 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9951 if (NSURLConnection$init$ != NULL) {
9952 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9953 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9956 /* Set Locale {{{ */
9957 Locale_ = CFLocaleCopyCurrent();
9958 Languages_ = [NSLocale preferredLanguages];
9960 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9961 //NSLog(@"%@", [Languages_ description]);
9964 if (Locale_ != NULL)
9965 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9966 else if (Languages_ != nil && [Languages_ count] != 0)
9967 lang = [[Languages_ objectAtIndex:0] UTF8String];
9969 // XXX: consider just setting to C and then falling through?
9973 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9974 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9977 NSLog(@"Setting Language: %s", lang);
9980 setenv("LANG", lang, true);
9981 std::setlocale(LC_ALL, lang);
9985 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9987 /* Parse Arguments {{{ */
9988 bool substrate(false);
9994 for (int argi(1); argi != argc; ++argi)
9995 if (strcmp(argv[argi], "--") == 0) {
9997 argv[argi] = argv[0];
10003 for (int argi(1); argi != arge; ++argi)
10004 if (strcmp(args[argi], "--substrate") == 0)
10007 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10011 App_ = [[NSBundle mainBundle] bundlePath];
10017 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10018 alloc_ = alloc->method_imp;
10019 alloc->method_imp = (IMP) &Alloc_;*/
10021 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10022 dealloc_ = dealloc->method_imp;
10023 dealloc->method_imp = (IMP) &Dealloc_;*/
10025 /* System Information {{{ */
10029 size = sizeof(maxproc);
10030 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10031 perror("sysctlbyname(\"kern.maxproc\", ?)");
10032 else if (maxproc < 64) {
10034 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10035 perror("sysctlbyname(\"kern.maxproc\", #)");
10038 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10039 char *osversion = new char[size];
10040 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10041 perror("sysctlbyname(\"kern.osversion\", ?)");
10043 System_ = [NSString stringWithUTF8String:osversion];
10045 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10046 char *machine = new char[size];
10047 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10048 perror("sysctlbyname(\"hw.machine\", ?)");
10050 Machine_ = machine;
10052 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10053 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10054 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10056 UniqueID_ = [device uniqueIdentifier];
10058 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10059 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10060 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10062 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10063 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10064 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10066 if (mcc != NULL && mnc != NULL)
10067 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10074 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10075 Build_ = [system objectForKey:@"ProductBuildVersion"];
10076 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10077 Product_ = [info objectForKey:@"SafariProductVersion"];
10078 Safari_ = [info objectForKey:@"CFBundleVersion"];
10081 /* Load Database {{{ */
10083 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10085 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10087 if (Metadata_ == NULL)
10088 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10090 Settings_ = [Metadata_ objectForKey:@"Settings"];
10092 Packages_ = [Metadata_ objectForKey:@"Packages"];
10094 Values_ = [Metadata_ objectForKey:@"Values"];
10095 Sections_ = [Metadata_ objectForKey:@"Sections"];
10096 Sources_ = [Metadata_ objectForKey:@"Sources"];
10098 Token_ = [Metadata_ objectForKey:@"Token"];
10100 Version_ = [Metadata_ objectForKey:@"Version"];
10102 @synchronized (HostConfig_) {
10103 CydiaSource_ = [Metadata_ objectForKey:@"CydiaSource"];
10107 if (Settings_ != nil)
10108 Role_ = [Settings_ objectForKey:@"Role"];
10110 if (Values_ == nil) {
10111 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10112 [Metadata_ setObject:Values_ forKey:@"Values"];
10115 if (Sections_ == nil) {
10116 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10117 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10120 if (Sources_ == nil) {
10121 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10122 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10125 if (Version_ == nil) {
10126 Version_ = [NSNumber numberWithUnsignedInt:0];
10127 [Metadata_ setObject:Version_ forKey:@"Version"];
10130 @synchronized (HostConfig_) {
10131 if (CydiaSource_ == nil) {
10132 CydiaSource_ = @"apt.saurik.com";
10133 [Metadata_ setObject:CydiaSource_ forKey:@"CydiaSource"];
10137 if ([Version_ unsignedIntValue] == 0) {
10138 AddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10139 AddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10140 AddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10141 AddSource(@"http://repo666.ultrasn0w.com/", @"./");
10143 Version_ = [NSNumber numberWithUnsignedInt:1];
10144 [Metadata_ setObject:Version_ forKey:@"Version"];
10153 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10156 if (Packages_ != nil) {
10158 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10162 [Metadata_ removeObjectForKey:@"Packages"];
10168 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10170 #define MobileSubstrate_(name) \
10171 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10172 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10173 if (handle == NULL) \
10174 NSLog(@"%s", dlerror()); \
10177 MobileSubstrate_(Activator)
10178 MobileSubstrate_(libstatusbar)
10179 MobileSubstrate_(SimulatedKeyEvents)
10180 MobileSubstrate_(WinterBoard)
10182 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10183 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10185 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10187 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10188 unlink("/tmp/.cydia.fw");
10190 } else if (access("/User", F_OK) != 0 || version < 4) {
10193 system("/usr/libexec/cydia/firmware.sh");
10197 _assert([[NSFileManager defaultManager]
10198 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10199 withIntermediateDirectories:YES
10204 if (access("/tmp/cydia.chk", F_OK) == 0) {
10205 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10206 _assert(errno == ENOENT);
10207 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10208 _assert(errno == ENOENT);
10211 /* APT Initialization {{{ */
10212 _assert(pkgInitConfig(*_config));
10213 _assert(pkgInitSystem(*_config, _system));
10216 _config->Set("APT::Acquire::Translation", lang);
10218 // XXX: this timeout might be important :(
10219 //_config->Set("Acquire::http::Timeout", 15);
10221 _config->Set("Acquire::http::MaxParallel", 3);
10223 /* Color Choices {{{ */
10224 space_ = CGColorSpaceCreateDeviceRGB();
10226 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10227 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10228 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10229 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10230 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10231 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10232 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10233 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10234 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10236 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10237 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10239 /* UIKit Configuration {{{ */
10240 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10241 if ($GSFontSetUseLegacyFontMetrics != NULL)
10242 $GSFontSetUseLegacyFontMetrics(YES);
10244 // XXX: I have a feeling this was important
10245 //UIKeyboardDisableAutomaticAppearance();
10248 Colon_ = UCLocalize("COLON_DELIMITED");
10249 Elision_ = UCLocalize("ELISION");
10250 Error_ = UCLocalize("ERROR");
10251 Warning_ = UCLocalize("WARNING");
10254 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10256 CGColorSpaceRelease(space_);
10257 CFRelease(Locale_);